diff --git a/Cargo.lock b/Cargo.lock index 887b10ab11..81946466b5 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", @@ -1010,6 +1016,14 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6" +[[package]] +name = "craft-gzip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" +dependencies = [ + "flate2", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1033,6 +1047,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 +1134,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 +1160,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" @@ -1156,7 +1220,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" +source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" dependencies = [ "flate2", "serde", @@ -1203,6 +1267,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 +1788,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 +2836,7 @@ dependencies = [ "moxcms", "num-traits", "png 0.18.1", + "qoi", "tiff", "zune-core 0.5.3", "zune-jpeg 0.5.15", @@ -3200,6 +3290,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 +3495,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 +4467,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 +5852,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 +6670,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 +6683,6 @@ dependencies = [ "log", "proptest", "rayon", - "roxmltree 0.21.2", "rustix 1.1.6", "ruzstd", "same-file", @@ -6625,6 +6749,7 @@ dependencies = [ name = "vectorcraft-format" version = "0.24.1" dependencies = [ + "craft-gzip", "craft-vectorcraft-format", "flate2", "proptest", @@ -6734,6 +6859,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 +6870,6 @@ dependencies = [ "md-5", "objc2-core-foundation", "objc2-core-graphics", - "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6785,16 +6910,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 +7042,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ + "craft-image-codecs", "image", "kurbo 0.13.1", "serde", @@ -8371,6 +8497,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..64f85eb450 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } @@ -30,9 +31,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/ROADMAP.md b/ROADMAP.md index 0270db445e..879133f4c7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -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 diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b66c15070f..4711232643 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,11 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ec6256a114..3568b4683e 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -155,8 +155,18 @@ 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 { + // A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at. + if paths.len() > MAX_URIS { + return None; + } paths.into_iter().find_map(|path| { // text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only. let path = match path.to_str() { @@ -197,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec, limit: usize) -> Option (data.len() <= limit).then_some(data) } +/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports +/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and +/// when the copy comes to more than `limit` bytes. +#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))] +fn copy_within(size: Option, limit: usize, copy: impl FnOnce() -> Option>) -> Option> { + size.filter(|&n| n > 0 && n <= limit)?; + copy().filter(|data| data.len() <= limit) +} + +/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at +/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4. +#[cfg_attr(not(windows), allow(dead_code))] +fn utf8_most(utf16: usize) -> usize { + utf16.div_ceil(2).saturating_mul(3) +} + +/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a +/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit` +/// files. Counting stops at the first name past `limit`. A block too short for its header, or +/// whose names would start past its end, is not within. +#[cfg_attr(not(windows), allow(dead_code))] +fn drop_files_within(block: &[u8], limit: usize) -> bool { + let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?)); + let (Some(start), Some(wide)) = (field(0), field(16)) else { + return false; + }; + let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else { + return false; + }; + let (mut count, mut in_name) = (0usize, false); + for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) { + if unit.iter().all(|&b| b == 0) { + if !in_name { + break; + } + in_name = false; + } else if !in_name { + in_name = true; + count += 1; + if count > limit { + return false; + } + } + } + true +} + /// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted /// data) names no files. const MAX_URIS: usize = 1024; @@ -278,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option { #[cfg(windows)] mod win { - use std::num::NonZeroU32; + use std::num::{NonZeroU32, NonZeroUsize}; use clipboard_win::{formats, options::NoClear, raw}; use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats, + BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png, + dib_image, drop_files_within, png_flavour, utf8_most, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -370,8 +428,11 @@ mod win { let mut files = vec![]; { let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; - // None copied when the clipboard holds no file list. - let _ = raw::get_file_list_path(&mut files); + // None copied when the clipboard holds no file list, or one of more than MAX_BYTES + // or MAX_URIS files: the list is counted before its names are copied. + if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) { + let _ = raw::get_file_list_path(&mut files); + } } // The files are read with the clipboard closed again, not keeping other apps waiting. copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| { @@ -390,44 +451,64 @@ mod win { } } - /// Read the first registered format of `mime` the clipboard holds into `data`. - fn read_registered(mime: &str, data: &mut Vec) -> bool { - formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| { - data.clear(); - raw::get_vec(id, data).is_ok() && !data.is_empty() + /// The size the clipboard reports for format `id`, while it is open. + fn size_of(id: u32) -> Option { + raw::size(id).map(NonZeroUsize::get) + } + + /// The data of format `id`, while the clipboard is open, copied only when its size is at most + /// `limit` bytes ([`copy_within`]). + fn copy_registered(id: u32, limit: usize) -> Option> { + copy_within(size_of(id), limit, || { + let mut data = vec![]; + raw::get_vec(id, &mut data).ok()?; + Some(data) }) } + /// The first registered format of `mime` the clipboard holds that is not empty and at most + /// [`MAX_BYTES`]; a larger one is skipped and the next tried. + fn read_registered(mime: &str) -> Option> { + formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty())) + } + /// A device-independent bitmap as a PNG flavour. fn dib_png(dib: &[u8]) -> Option { png_flavour(&dib_image(dib)?) } /// Copy both bitmap formats while the clipboard is open, then decode them in preference order. - pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option>) -> Option { - let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect(); + /// `size` gives each format's size before `get` copies it, and a format of more than + /// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried. + pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option, mut get: impl FnMut(u32) -> Option>) -> Option { + let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect(); (!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib))))) } /// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and - /// the work that comes back decodes each captured format in preference order. + /// the work that comes back decodes each captured format in preference order. Text whose + /// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read. fn read_one(mime: &'static str) -> Option { - let mut data = vec![]; - let mime = match mime { - BITMAP if read_registered(PNG, &mut data) => PNG, - BITMAP => { - return read_dibs(|id| { - let mut dib = vec![]; - raw::get_vec(id, &mut dib).ok()?; - Some(dib) - }); - } + let (mime, mut data) = match mime { + BITMAP => match read_registered(PNG) { + Some(png) => (PNG, png), + None => { + return read_dibs(size_of, |id| { + let mut dib = vec![]; + raw::get_vec(id, &mut dib).ok()?; + Some(dib) + }); + } + }, TEXT => { - raw::get_string(&mut data).ok()?; - TEXT + let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || { + let mut text = vec![]; + raw::get_string(&mut text).ok()?; + Some(text) + })?; + (TEXT, text) } - m if read_registered(m, &mut data) => m, - _ => return None, + m => (m, read_registered(m)?), }; // Memory blocks can be longer than the data: SVG text ends at its first NUL. if mime == SVG @@ -727,7 +808,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 +822,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 +894,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 +1535,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 +1550,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 +1714,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 +2054,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 +2145,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) @@ -3092,7 +3216,7 @@ mod mac { use objc2_app_kit::NSPasteboard; use objc2_foundation::{NSArray, NSString}; - use super::{Flavour, pasteboard_types}; + use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types}; /// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only. pub fn has(mimes: &[&'static str]) -> bool { @@ -3103,13 +3227,16 @@ mod mac { }) } - /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]). + /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is + /// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger + /// type is skipped and the next tried. pub fn read(mime: &str) -> Option { autoreleasepool(|_| { let pasteboard = NSPasteboard::generalPasteboard(); pasteboard_types(mime).iter().find_map(|&(t, mime)| { - let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec(); - (!data.is_empty()).then_some(Flavour { mime, data }) + let held = pasteboard.dataForType(&NSString::from_str(t))?; + let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?; + Some(Flavour { mime, data }) }) }) } @@ -3296,6 +3423,102 @@ mod tests { assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty()); } + /// A copied file list of more than 1,024 files pastes none, before any file is looked at, + /// wherever the list came from; 1,024 files paste the first that is art. + #[test] + fn a_copied_file_list_longer_than_the_limit_pastes_no_file() { + let d = dir("many"); + let art = d.path().join("art.svg"); + std::fs::write(&art, "").unwrap(); + let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::>(); + let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat(); + assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG)); + // The art first: no file is opened past the count. + let first = [vec![art.clone()], missing(MAX_URIS)].concat(); + assert!(copied_file(first, &PASTE_ORDER).is_none()); + assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none()); + } + + /// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit, + /// and the copy is not asked for otherwise. + #[test] + fn clipboard_data_is_copied_only_when_its_size_fits() { + let copy = |size: Option, got: usize| { + let mut asked = false; + let data = copy_within(size, 8, || { + asked = true; + Some(vec![1; got]) + }); + (data.map(|d| d.len()), asked) + }; + assert_eq!(copy(Some(8), 8), (Some(8), true)); + assert_eq!(copy(Some(1), 1), (Some(1), true)); + for size in [None, Some(0), Some(9), Some(usize::MAX)] { + assert_eq!(copy(size, 1), (None, false), "{size:?}"); + } + // Data that comes to more than the limit after all is refused. + assert_eq!(copy(Some(8), 9), (None, true)); + assert_eq!(MAX_BYTES, 64 << 20); + } + + /// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before + /// the text is converted: a block that could pass the limit as UTF-8 is not read. + #[test] + fn text_is_bounded_by_what_its_utf8_could_come_to() { + for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] { + let utf16 = text.encode_utf16().count() * 2; + assert!(utf8_most(utf16) >= text.len(), "{text:?}"); + } + // Every code unit at 3 bytes of UTF-8: the bound is exact. + assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len()); + let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some(); + assert!(copied(MAX_BYTES / 3 * 2)); + assert!(!copied(MAX_BYTES / 3 * 2 + 2)); + assert!(!copied(MAX_BYTES)); + assert_eq!(utf8_most(usize::MAX), usize::MAX); + } + + /// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one + /// byte a character, each ended by a NUL, and one more NUL. + fn drop_files(names: &[&str], wide: bool) -> Vec { + let mut block = vec![]; + block.extend(20u32.to_le_bytes()); + block.extend([0u8; 12]); + block.extend(u32::from(wide).to_le_bytes()); + for name in names.iter().copied().chain([""]) { + for unit in name.encode_utf16().chain([0]) { + if wide { + block.extend(unit.to_le_bytes()); + } else { + block.push(unit as u8); + } + } + } + block + } + + #[test] + fn a_windows_file_list_is_counted_before_its_names_are_read() { + let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::>(); + for wide in [true, false] { + let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::>(), wide); + assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}"); + assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}"); + assert!(drop_files_within(&list(0), MAX_URIS), "{wide}"); + // Names past the list's closing NUL are not counted. + let mut ended = list(2); + ended.extend(list(MAX_URIS + 1).get(20..).unwrap()); + assert!(drop_files_within(&ended, 2), "{wide}"); + // A list cut short counts the names it holds. + assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}"); + } + // A header cut short, or names that would start past the block's end. + assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS)); + let mut past = drop_files(&["a"], true); + past[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(!drop_files_within(&past, MAX_URIS)); + } + #[test] fn gnome_files_list_names_its_files_after_copy_or_cut() { let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::>(); @@ -3349,19 +3572,48 @@ mod tests { let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED])); let mut captured = Vec::new(); - let read = win::read_dibs(|id| { - captured.push(id); - match id { - CF_DIBV5 => Some(vec![40, 0, 0]), - CF_DIB => Some(valid.clone()), - _ => None, - } - }) + let get = |id: u32| match id { + CF_DIBV5 => Some(vec![40, 0, 0]), + CF_DIB => Some(valid.clone()), + _ => None, + }; + let read = win::read_dibs( + |id| get(id).map(|d| d.len()), + |id| { + captured.push(id); + get(id) + }, + ) .unwrap(); assert_eq!(captured, [CF_DIBV5, CF_DIB]); let flavour = read.flavour().unwrap(); assert_eq!(flavour.mime, PNG); assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]); + // A bitmap larger than the limit is not copied, and the other one still pastes. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); + // Each format has the limit to itself: a first one at the limit that doesn't decode + // leaves the second to paste. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIBV5, CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); } #[test] diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c55785cfdf..8a892a381a 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")] @@ -498,6 +535,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // File Info's metadata templates live in their own folder next to the preferences. + prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..1a33352ffc 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template +/// makes. +pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Metadata Templates") { + session.attach_metadata_templates_dir(dir); + } +} + /// Have File › New start each category's documents from its profile in the `New Document /// Profiles` folder, which `file.newProfiles.edit` makes. pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { 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/hit.rs b/crates/doc/src/hit.rs index a286c25ffc..85182e9f36 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -323,34 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option) -> Vec { - let walk = ArtWalk::open(); + 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() { - walk.restart(); - 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, with the whole - // limit of symbol art to walk. - walk.restart(); - 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. @@ -414,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) { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index f2582c17fa..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); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7b7ef4fee7..902d29e7c5 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -28,6 +28,7 @@ pub mod shared; mod symbol_export_type; mod symbol_nine_slice; pub mod symbol_overrides; +mod symbol_pixel_aligned; mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; @@ -37,6 +38,7 @@ pub use symbol_nine_slice::{ SymbolNineSlice, charge_symbol_art, }; pub use symbol_overrides::SymbolOverride; +pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; pub mod live; 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/symbol_pixel_aligned.rs b/crates/doc/src/symbol_pixel_aligned.rs new file mode 100644 index 0000000000..6eb9d226dc --- /dev/null +++ b/crates/doc/src/symbol_pixel_aligned.rs @@ -0,0 +1,80 @@ +//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their +//! actual size wherever they are placed +//! (). +//! +//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned +//! (the default) is left out of the map. + +use std::collections::HashSet; + +use crate::Document; + +/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol. +pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned"; + +impl Document { + /// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off). + pub fn symbol_pixel_aligned(&self, name: &str) -> bool { + self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false) + } + + /// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map, + /// and the map goes when it is empty. + pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) { + if on { + let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({})); + if let Some(o) = m.as_object_mut() { + o.insert(name.into(), serde_json::json!(true)); + } + return; + } + let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return }; + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_PIXEL_ALIGNED); + } + } + + /// Move the stored setting when a symbol is renamed. + pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let on = self.symbol_pixel_aligned(from); + self.set_symbol_pixel_aligned(from, false); + self.set_symbol_pixel_aligned(to, on); + } + + /// The names of the pixel-aligned symbols the document holds (empty for most documents). + pub fn pixel_aligned_symbols(&self) -> HashSet { + let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() }; + o.iter() + .filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name)) + .map(|(name, _)| name.clone()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_setting_is_off_by_default_and_follows_a_rename() { + let mut d = Document::new(100.0, 100.0); + let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![])); + d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art }); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + d.set_symbol_pixel_aligned("A", true); + assert!(d.symbol_pixel_aligned("A")); + assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()])); + d.symbols[0].name = "B".into(); + d.rename_symbol_pixel_aligned("A", "B"); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.symbol_pixel_aligned("B")); + d.set_symbol_pixel_aligned("B", false); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + assert!(d.pixel_aligned_symbols().is_empty()); + } +} diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 3964542939..2b44af5c8d 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -35,7 +35,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_work}; +pub use wrap::{resolve_wrap, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 75d95ac029..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. diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 0b5fe45dc2..29313ccb22 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use vectorcraft_geom::{PathData, shapes}; -use super::{TextKind, WrapShape}; +use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -82,6 +82,57 @@ pub fn wrap_work(doc: &Document) -> usize { total } +/// Each area text object of `layer`, from the top down, with the wrap objects above it in the +/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in +/// document coordinates. Each wrap object's outline is made once. +fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) { + let mut items = vec![]; + collect(layer, &mut items); + let mut above: Vec<(&Node, WrapShape)> = vec![]; + for it in items.iter().rev() { + match it { + Item::Wrap(n) => { + let mut pd = PathData::default(); + outline(n, &mut pd); + if !pd.is_empty() { + above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() })); + } + } + Item::Text(n) => f(n, &above), + } + } +} + +/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as +/// [`each_text`] gives them: bottom first. +fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { + let inv = t.xf.inverse(); + above + .iter() + .rev() + .map(|(_, s)| { + let mut path = s.path.clone(); + path.transform(inv); + WrapShape { path, wrap: s.wrap } + }) + .collect() +} + +/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap +/// objects whose outlines make them, bottom first, and those shapes (text space), as +/// [`resolve_wrap`] works them out. The copying is [`wrap_work`]. +pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind + && !above.is_empty() + { + f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above)); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes @@ -95,41 +146,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec = vec![]; - for it in items.iter().rev() { - match it { - Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }); - } - } - Item::Text(n) => { - let NodeKind::Text(t) = &n.kind else { continue }; - let inv = t.xf.inverse(); - let shapes: Vec = above - .iter() - .rev() - .map(|s| { - let mut path = s.path.clone(); - path.transform(inv); - WrapShape { path, wrap: s.wrap } - }) - .collect(); - if shapes != t.wrap { - updates.push((n.id, shapes)); - } + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind { + let shapes = shapes_of(t, above); + if shapes != t.wrap { + updates.push((n.id, shapes)); } } - } + }); } let mut changed = Vec::with_capacity(updates.len()); for (id, shapes) in updates { 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/group.rs b/crates/effects/src/group.rs index 94c5509938..63215d897d 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option Node { let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() }; if outline { - let fill = src.appearance.fill_paint(); - let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill }; - appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() }; + // The edges take the paint, opacity, blend mode and overprint of the top fill that paints, + // or of the top stroke that paints when no fill does. + let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i))); + let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0); + if let Some(i) = layer { + (stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint()); + } + appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() }; } let mut n = Node::path(src.id, path, appearance); n.opacity = src.opacity; @@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option f64 { } fn fill_cmyk(src: &Node) -> Option<[f32; 4]> { - let paint = src.appearance.fill_paint(); + // The top fill that paints: a hidden fill adds no color. + let paint = top_painting_fill(&src.appearance)?.paint().clone(); let color = paint.color()?; let tinted = match paint { Paint::Solid { tint, .. } => color.tinted(tint), @@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) } +/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped. +fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> { + a.items.iter().rev().find(|i| i.is_fill() && paints(i)) +} + /// Does `item` paint anything? pub fn paints(item: &AppearanceItem) -> bool { item.visible() diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 50fbf8f759..3b8addadea 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1,6 +1,6 @@ use super::*; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; +use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject}; use vectorcraft_geom::{Point, Rect, shapes}; /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. @@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() { assert_eq!(fill.paint.color(), Some(yellow)); } +/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member +/// whose only fill is hidden does not take part. +#[test] +fn trap_skips_a_hidden_fill() { + let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0); + let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0); + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + let trap = |members: Vec>| { + let mut g = Node::group(NodeId(10), members); + let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100}); + g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true }); + pathfinder_children(None, &g, None).unwrap() + }; + let mut covered = (*sq(1, 0.0, yellow)).clone(); + covered.appearance.items.push(AppearanceItem::Fill(hidden.clone())); + let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]); + assert_eq!(out.len(), 3, "both squares and one trap"); + assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow)); + let only_hidden = Node::path( + NodeId(1), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() }, + ); + assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap"); +} + #[test] fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() { let mut g = two_overlapping_cmyk_squares(); @@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() { assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}"); } +/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color. +#[test] +fn mixes_skip_a_hidden_fill() { + for effect in ["pathfinder.softMix", "pathfinder.hardMix"] { + let mut plain = two_overlapping_cmyk_squares(); + plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true }); + let mut covered = plain.clone(); + let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") }; + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + for c in children.iter_mut() { + Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone())); + } + assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}"); + } +} + +/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend +/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill +/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes. +#[test] +fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() { + use vectorcraft_doc::StrokeLayer; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let mut fill = FillLayer::new(red.clone()); + (fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + hidden.visible = false; + let mut stroke = StrokeLayer::new(blue.clone(), 2.0); + (stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0); + hidden_stroke.visible = false; + let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0); + let look = |items: Vec| Appearance { items, ..Default::default() }; + let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke); + let cases = [ + (look(vec![f(fill.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())), + (look(vec![f(hidden.clone())]), None), + (look(vec![s(stroke.clone())]), Some(blue.clone())), + (look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())), + (look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())), + (look(vec![s(zero_stroke)]), None), + ]; + for (appearance, want) in cases { + let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance)); + let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]); + g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect(); + assert!(!edges.is_empty(), "{out:#?}"); + for n in edges { + let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") }; + match &want { + Some(paint) => { + assert_eq!(&s.paint, paint); + assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}"); + } + None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"), + } + } + } +} + #[test] fn shape_modes_follow_the_pathfinder_panel() { let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap(); 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/solids.rs b/crates/effects/src/solids.rs index 5a2a179437..e10771a8d0 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -625,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); @@ -634,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() @@ -671,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. 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/tests.rs b/crates/effects/src/solids/tests.rs index 9b57c989c6..319cdf2949 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1960,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/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/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/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index db6e4e28a1..1f9490f24e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Symbols", [], None, - "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}", has_doc, symbol_list ), @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 1bfb8edea7..9b718c61b4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> R }) } +/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any +/// value other than true or false, null included, is an error. +fn pixel_grid_param(p: &Value, cmd: &str) -> Result> { + match p.get("alignToPixelGrid") { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")), + } +} + fn nine_slice_json(d: &Document, name: &str) -> Value { d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value) } @@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), "type": type_id(sym.dynamic), + "alignToPixelGrid": d.symbol_pixel_aligned(&sym.name), }) }) .collect(); @@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); + let pixel = pixel_grid_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); + d.set_symbol_pixel_aligned(&name, pixel); let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) @@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), "type": type_id(dynamic), + "alignToPixelGrid": pixel, })) } @@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; let dynamic = type_param(p, C)?; + let pixel = pixel_grid_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { - return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); + match pixel { + None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")), + // Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added. + Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)), + Some(_) => {} + } } if let Some(ref n) = new_name && n != &name @@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { d.rename_symbol_registration(&name, n); d.rename_symbol_export_type(&name, n); d.rename_symbol_nine_slice(&name, n); + d.rename_symbol_pixel_aligned(&name, n); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } @@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { sym.dynamic = dynamic; fit_overrides(d, &instances_of(d, Some(&final_name))); } + // Turning it on snaps the art and the instances at actual size when the edit ends + // (`object::refresh_pixel_aligned`). + if let Some(on) = pixel { + d.set_symbol_pixel_aligned(&final_name, on); + } Ok(()) })?; - let d = &s.doc()?.doc; - Ok(json!({ - "name": final_name, - "registration": d.symbol_registration(&final_name).0, - "exportType": d.symbol_export_type(&final_name).id(), - "nineSlice": nine_slice_json(d, &final_name), - "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), - })) + Ok(options_json(&s.doc()?.doc, &final_name)) +} + +/// What `symbol.options` answers for symbol `name`. +fn options_json(d: &Document, name: &str) -> Value { + json!({ + "name": name, + "registration": d.symbol_registration(name).0, + "exportType": d.symbol_export_type(name).id(), + "nineSlice": nine_slice_json(d, name), + "type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)), + "alignToPixelGrid": d.symbol_pixel_aligned(name), + }) } fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { @@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(name, SymbolRegistration::CENTER); d.clear_symbol_export_type(name); d.set_symbol_nine_slice(name, None); + d.set_symbol_pixel_aligned(name, false); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.remove(CURRENT_SYMBOL); } @@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { let reg = d.symbol_registration(&name); let export = d.symbol_export_type(&name); let nine = d.symbol_nine_slice(&name); + let pixel = d.symbol_pixel_aligned(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); @@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); d.set_symbol_nine_slice(&new, nine); + d.set_symbol_pixel_aligned(&new, pixel); Ok(()) })?; Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) })) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 95c04e39c7..01537c7b68 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), 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)}", + "{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 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), 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\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; 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\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; 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 46a2d37555..a030f5bd8f 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { 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")))?; + // Each id in `through` is an edge of the group, given once. + let group_edges: std::collections::HashSet = b::edges(n).iter().map(|e| e.id).collect(); + let mut seen = std::collections::HashSet::new(); + if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) { + return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice"))); + } let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; let eid = start.id; let like = like.unwrap_or_else(|| b::lp_stroke_paint(start)); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index fa69f1f820..fdaeddf39d 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -766,6 +766,8 @@ pub struct SymbolOptions { pub export_type: SymbolExportType, /// 9-slice guides (`None`: 9-slice scaling off). pub nine_slice: Option, + /// Align to Pixel Grid. + pub pixel_aligned: bool, } impl SymbolOptions { @@ -776,6 +778,7 @@ impl SymbolOptions { registration: d.symbol_registration(name), export_type: d.symbol_export_type(name), nine_slice: d.symbol_nine_slice(name), + pixel_aligned: d.symbol_pixel_aligned(name), } } @@ -785,6 +788,7 @@ impl SymbolOptions { d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); d.set_symbol_nine_slice(name, self.nine_slice); + d.set_symbol_pixel_aligned(name, self.pixel_aligned); } } @@ -1035,10 +1039,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); } } } 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/create.rs b/crates/engine/src/cmd/create.rs index 08944940a2..5571d24b28 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result { add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } +/// The most anchors `shape.ellipse` draws, as many as a polygon's sides. +const MAX_ELLIPSE_ANCHORS: u64 = 1000; + fn ellipse(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, "shape.ellipse")?; - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? }; - add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) + // One message for every number that is not a whole count in range (a fraction, a negative, + // 0, 1, too many); a value that is not a number gets `number_or`'s. + let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS); + let n = number_or(p, key, 4.0, "shape.ellipse")?; + if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) { + return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})"))); + } + let x = n as u64; + let xf = rect_transform(r, p, "shape.ellipse")?; + let rotation = f64_or(p, "rotation", 0.0); + if x != 4 { + // Another count is a plain path: a live ellipse always has 4 anchors. + let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf); + return add_art_turned(s, "Ellipse", path_kind(path, None), rotation); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf }; + add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 8f1b5b97e6..1e78f210e6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -631,13 +631,12 @@ impl LiquifyStroke { } let msg = (!ids.is_empty()).then(|| { let n = ids.len(); - format!( - "{} left {n} object{} under the brush as {} ({}): it reshapes paths only", - self.prm.kind.label(), - if n == 1 { "" } else { "s" }, - if n == 1 { "it was" } else { "they were" }, - kinds.join(", ") - ) + let (tool, kinds) = (self.prm.kind.label(), kinds.join(", ")); + if n == 1 { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + } }); (ids, msg) } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 3b1e8a7666..9404dcc0c7 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -270,6 +270,33 @@ pub fn specs() -> Vec { has_doc, super::fileinfo::file_info ), + cmd!( + "file.info.saveTemplate", + "Save Metadata Template…", + [], + None, + "{name?: save into the metadata templates folder as .xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither", + has_doc, + super::fileinfo::save_template + ), + cmd!( + "file.info.applyTemplate", + "Import Metadata Template…", + [], + None, + "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", + has_doc, + super::fileinfo::apply_template + ), + cmd!( + query "file.info.templates", + "Metadata Templates", + [], + None, + "{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}", + super::always, + super::fileinfo::templates + ), ] } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 49e277e5a0..38ac35c61a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 64b8bdee16..fca15e46c5 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -3,9 +3,10 @@ use super::common::{ samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; +use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; use vectorcraft_doc::StrokeLayer; use vectorcraft_tools::draw2::MIN_BRUSH_SIZE; @@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec { /// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment /// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least -/// `step` long is found. -fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { +/// `step` long is found, and also at the parameters `extra` gives for it. +fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let nseg = sp.segment_count(); if nseg == 0 { return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); @@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot()); let wanted = (3.0 * edge / step).ceil(); let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K }; + let mut ts: Vec = (1..=samples).map(|k| k as f64 / samples as f64).collect(); + let more = extra(c); + if !more.is_empty() { + ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)); + ts.sort_by(f64::total_cmp); + ts.dedup(); + } let mut prev_t = 0.0; let mut prev_rm = remove(c.eval(0.0)); let mut start = if prev_rm { None } else { Some(0.0) }; @@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio runs.push(std::mem::take(&mut cur)); } } - for k in 1..=samples { - let t = k as f64 / samples as f64; + for t in ts { let rm = remove(c.eval(t)); if rm != prev_rm { let (mut lo, mut hi) = (prev_t, t); @@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio /// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output /// object (one object per piece when the path had a single subpath), or None if unchanged. pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + erase_outline_at(pd, step, remove, &|_| vec![]) +} + +/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it. +fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let mut changed = false; let mut subs = vec![]; for sp in &pd.subpaths { - match cut_subpath(sp, step, remove) { + match cut_subpath(sp, step, remove, extra) { Some(pieces) => { changed = true; subs.extend(pieces); @@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; + if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) { + if p.get("points").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "give `points` or `rect`, not both")); + } + return erase_rect(s, marquee_param(rect, C)?); + } let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { @@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a +/// height above 0. +fn marquee_param(v: &Value, cmd: &str) -> Result { + const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0"; + let n: Vec = match v.as_array() { + Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::>().ok_or_else(|| bad(cmd, SHAPE))?, + _ => return Err(bad(cmd, SHAPE)), + }; + let [x, y, w, h] = [n[0], n[1], n[2], n[3]]; + if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) { + return Err(bad(cmd, SHAPE)); + } + Ok(Rect::new(x, y, x + w, y + h)) +} + +/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or +/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +fn erase_rect(s: &mut Session, r: Rect) -> Result { + let region = + PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); + let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1; + // An open path is sampled at least every half of the rectangle's shorter side, and also where + // each segment crosses the rectangle's edges and halfway between those crossings, so a stretch + // inside the rectangle is found however long the segment is. + let step = r.width().min(r.height()) / 2.0; + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + let crossings = |c: CubicBez| { + let mut ts: Vec = (0..4) + .flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4]))) + .map(|x| x.segment_t) + .filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0) + .collect(); + ts.sort_by(f64::total_cmp); + let mids: Vec = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect(); + ts.extend(mids); + ts + }; + let st = s.doc()?; + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { + if pd.is_closed() { + if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { + continue; + } + plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); + } else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index 883c9ba5ed..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 @@ -1099,11 +1145,12 @@ mod tests { } /// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach - /// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments - /// than it measures before it gets that far, its top is not one, as the path turns by about 51° - /// over that reach. + /// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its + /// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51° + /// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long + /// are corners too. #[test] - fn a_corner_is_not_kept_where_the_reach_is_not_measured() { + fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() { let side = 400.0 * std::f64::consts::SQRT_2; let steps = side.ceil() as usize; let mut pts = vec![(-3000.0, 0.0)]; @@ -1120,6 +1167,10 @@ mod tests { let top = steps + 1; assert_eq!(anchors[top].p, Point::new(0.0, 400.0)); assert!(smooth_corners(&anchors, false, 10.0)[top]); + assert!(smooth_corners(&anchors, false, 300.0)[top]); + let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]); + let corners = smooth_corners(&long, false, 0.5); + assert!(corners[2] && corners[3] && corners[4], "{corners:?}"); assert!(!smooth_corners(&anchors, false, 1000.0)[top]); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..0ac559c874 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -179,7 +179,7 @@ pub fn specs() -> 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 30b3dd6304..1f471d84a3 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -978,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; @@ -1002,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); } @@ -1058,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 @@ -1084,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. @@ -1099,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 @@ -1139,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); @@ -1169,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). @@ -1180,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 { .. }) @@ -1201,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 }) }; @@ -1223,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() { @@ -1235,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; } @@ -1280,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 { @@ -1313,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/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 6219ebb8f6..b6b1643ea4 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -3,14 +3,28 @@ //! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]), //! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or //! `.ai` opens with the File Info it gives ([`read_pdf`]). +//! +//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file +//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File +//! Info, and `file.info.templates` lists those in the metadata templates folder. use serde_json::{Map, Value, json}; use vectorcraft_doc::metadata::{MAX_RATING, iso8601}; use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document}; -use super::{Result, Session, bad}; +use super::{Result, Session, bad, switch_or, text_param}; const C: &str = "file.info"; +const SAVE: &str = "file.info.saveTemplate"; +const APPLY: &str = "file.info.applyTemplate"; +const LIST: &str = "file.info.templates"; +/// The extension of a metadata template file. +const TEMPLATE_EXT: &str = "xmp"; +/// The most templates `file.info.templates` lists. +const MAX_LISTED: usize = 1000; +/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate` +/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB. +const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES; /// Longest text field, in characters. const MAX_TEXT: usize = 65_536; /// Longest keyword, in characters. @@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb /// What `file.info` reports (and takes back). pub(crate) fn info_json(d: &Document) -> Value { - let m = &d.metadata; + info_json_with(d, d.info_title(), &d.metadata) +} + +/// [`info_json`] with the title `title` and the metadata `m` in place of the document's. +fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value { json!({ - "title": d.info_title(), + "title": title, "author": m.author, "authorTitle": m.author_title, "description": m.description, @@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { Value::Object(o) => o, _ => return Err(bad(C, "params must be an object")), }; + let (title, m) = edited(s, Some(o))?; + commit(s, title, m)?; + Ok(info_json(&s.doc()?.doc)) +} + +/// The active document's File Info title and metadata with `fields` (as `file.info` takes them) +/// applied. +fn edited(s: &Session, fields: Option<&Map>) -> Result<(String, DocMetadata)> { let d = &s.doc()?.doc; let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone()); - for (k, v) in o { + for (k, v) in fields.into_iter().flatten() { apply(&mut title, &mut m, k, v)?; } + Ok((title, m)) +} + +/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when +/// they are what it has. Whether anything changed. +fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result { let d = &s.doc()?.doc; // A title File Info changes becomes the document's own, as it always has (the tab and Save As // offer it where the document has no file), and replaces the one its file gave. @@ -60,16 +92,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { if retitled { m.title = None; } - if retitled || m != d.metadata { - s.edit("File Info", |d, _| { - if retitled { - d.title = title; - } - d.metadata = m; - Ok(()) - })?; + if !retitled && m == d.metadata { + return Ok(false); } - Ok(info_json(&s.doc()?.doc)) + s.edit("File Info", |d, _| { + if retitled { + d.title = title; + } + d.metadata = m; + Ok(()) + })?; + Ok(true) +} + +/// The optional object `p` gives for `key`. +fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => Ok(Some(o)), + Some(_) => Err(bad(c, format!("`{key}` must be an object"))), + } +} + +impl Session { + /// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the + /// metadata templates in the folder `dir`, which a save makes when it is missing. + pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) { + self.metadata_templates_dir = Some(dir); + } + + /// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web, + /// which has no folders. + pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> { + self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } +} + +/// The metadata template of the File Info `title` and `m`: each field that has a value, the title +/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up. +fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo { + let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string()); + vectorcraft_pdf::FileInfo { + title: super::fileio::is_own_title(title).then(|| title.to_string()), + author: text(&m.author), + author_title: text(&m.author_title), + description: text(&m.description), + keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()), + rating: (m.rating > 0).then_some(m.rating), + copyright_notice: text(&m.copyright_notice), + copyright_url: text(&m.copyright_url), + copyrighted: match m.copyright_status { + CopyrightStatus::Copyrighted => Some(true), + CopyrightStatus::PublicDomain => Some(false), + CopyrightStatus::Unknown => None, + }, + ..Default::default() + } +} + +/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with +/// [`TEMPLATE_EXT`]. +fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(bad(c, "the template name can't be empty")); + } + Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned()) +} + +/// The error for a template over [`MAX_TEMPLATE_FILE`]. +fn too_big(c: &str) -> crate::EngineError { + bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20)) +} + +/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`. +pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result { + let name = text_param(p, "name", SAVE)?; + let path = text_param(p, "path", SAVE)?; + let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?; + let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m)); + if xmp.len() > MAX_TEMPLATE_FILE { + return Err(too_big(SAVE)); + } + match (name, path) { + (Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")), + (Some(name), None) => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf(); + let path = template_path(&dir, name, SAVE)?; + // The name is the file name as it is, so two names never share a file. + let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()); + if listed.as_deref() != Some(name.trim()) { + return Err(bad(SAVE, "the template name isn't usable as a file name")); + } + // Only a file in the folder itself is replaced: a link there is not followed. + if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + let dir = dir.to_string_lossy().into_owned(); + // The app's own folder, under a name checked above: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?; + Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) })) + } + (None, Some(path)) => { + super::fileio::write_file(path, xmp.as_bytes())?; + Ok(json!({ "path": path })) + } + (None, None) => Ok(json!({ "data": xmp })), + } +} + +/// How `file.info.applyTemplate` merges a template's fields into the File Info. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Merge { + /// Clear the fields a template can hold, then take the template's. + Replace, + /// Keep the fields, and take each one the template gives. + Keep, + /// Keep the fields: add the template's keywords, and take its other fields only where the File + /// Info has none. + Append, +} + +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { + let mode = match text_param(p, "mode", APPLY)? { + Some("replace") => Merge::Replace, + Some("keep") => Merge::Keep, + Some("append") => Merge::Append, + _ => return Err(bad(APPLY, "mode must be replace, keep or append")), + }; + let apply = switch_or(p, "apply", true, APPLY)?; + let base = fields_param(p, "base", APPLY)?; + let bytes = template_bytes(s, p)?; + let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?; + let (mut title, mut m) = edited(s, base)?; + merge(&mut title, &mut m, t, mode); + if !apply { + return Ok(info_json_with(&s.doc()?.doc, &title, &m)); + } + let changed = commit(s, title, m)?; + let mut out = info_json(&s.doc()?.doc); + out["changed"] = json!(changed); + Ok(out) +} + +/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or +/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +fn template_bytes(s: &Session, p: &Value) -> Result> { + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + // At most one byte past the limit is read, so a huge file is never read whole. + let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); + let bytes = match given { + [Some(path), None, None] => read(path)?, + [None, Some(name), None] => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; + let mut path = template_path(dir, name, APPLY)?; + // A template `file.info.templates` lists: by its `file` first, then by its `name` with + // the extension in lowercase, then in other letter case. Only files in the folder itself + // are listed: a link there is not followed. + let name = name.trim(); + let own = format!("{name}.{TEMPLATE_EXT}"); + let listed = template_files(dir) + .filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name)) + .min_by_key(|f| (f != name, *f != own)); + if let Some(file) = listed { + path = dir.join(file).to_string_lossy().into_owned(); + } else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) { + // A name that is not a file name as it is never opens another template. + return Err(bad(APPLY, "the template name isn't usable as a file name")); + } + let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()); + if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + // The app's own folder: no root applies. + crate::file_access::unconfined(|| read(&path))? + } + [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data)] => data.as_bytes().to_vec(), + _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + }; + if bytes.len() > MAX_TEMPLATE_FILE { + return Err(too_big(APPLY)); + } + Ok(bytes) +} + +/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as +/// `file.info` would take it; a value it would refuse is left out. +fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) { + if mode == Merge::Replace { + // The title is never cleared: a document always has one. + m.author.clear(); + m.author_title.clear(); + m.description.clear(); + m.keywords.clear(); + m.rating = 0; + m.copyright_status = CopyrightStatus::Unknown; + m.copyright_notice.clear(); + m.copyright_url.clear(); + } + let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); + let fields = [ + ("title", t.title.map(Value::from)), + ("author", t.author.map(Value::from)), + ("authorTitle", t.author_title.map(Value::from)), + ("description", t.description.map(Value::from)), + ("keywords", t.keywords.map(Value::from)), + ("rating", t.rating.map(Value::from)), + ("copyrightStatus", status.map(|s| Value::from(s.id()))), + ("copyrightNotice", t.copyright_notice.map(Value::from)), + ("copyrightUrl", t.copyright_url.map(Value::from)), + ]; + for (k, v) in fields { + let Some(mut v) = v else { continue }; + if mode == Merge::Append { + let empty = match k { + "title" => !super::fileio::is_own_title(title), + "author" => m.author.is_empty(), + "authorTitle" => m.author_title.is_empty(), + "description" => m.description.is_empty(), + "rating" => m.rating == 0, + "copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown, + "copyrightNotice" => m.copyright_notice.is_empty(), + "copyrightUrl" => m.copyright_url.is_empty(), + _ => true, + }; + if !empty { + continue; + } + if k == "keywords" { + let mut all: Vec = m.keywords.iter().cloned().map(Value::from).collect(); + all.extend(v.as_array().cloned().unwrap_or_default()); + v = Value::from(all); + } + } + // `apply` changes the field only when it takes the value. + let _ = apply(title, m, k, &v); + } +} + +/// The file names of the templates in the folder `dir`: its files with a name before the +/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made +/// yet holds none. +fn template_files(dir: &std::path::Path) -> impl Iterator { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty())) +} + +/// `file.info.templates {create?}`: the metadata templates in the folder, by name. +pub(crate) fn templates(s: &mut Session, p: &Value) -> Result { + let create = switch_or(p, "create", false, LIST)?; + let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else { + return Ok(json!({ "templates": [] })); + }; + if create { + // The app's own folder: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?; + } + // The first [`MAX_LISTED`] by name, with no more than that many held at once. + let mut files = std::collections::BTreeSet::new(); + for file in template_files(std::path::Path::new(&dir)) { + files.insert(file); + if files.len() > MAX_LISTED { + files.pop_last(); + } + } + let list: Vec = files + .iter() + .filter_map(|file| { + let (stem, _) = file.rsplit_once('.')?; + let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned(); + Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) })) + }) + .collect(); + let mut out = json!({ "templates": list }); + if super::fileio::shown_path(&dir) == dir.as_str() { + out["folder"] = json!(dir); + } + Ok(out) } /// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each @@ -79,8 +385,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); let fields = [ ("author", f.author.map(Value::from)), + ("authorTitle", f.author_title.map(Value::from)), ("description", f.description.map(Value::from)), ("keywords", f.keywords.map(Value::from)), + ("rating", f.rating.map(Value::from)), ("copyrightStatus", status.map(|s| Value::from(s.id()))), ("copyrightNotice", f.copyright_notice.map(Value::from)), ("copyrightUrl", f.copyright_url.map(Value::from)), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fc5be365d5..d8c9074001 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; mod heifread; mod hpgl; mod jp2read; 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 4a3ca6265a..657cab3060 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), 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", + "{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 ), diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index c3249ba408..9a5474b1e6 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -199,8 +199,12 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet 0.0 { b.inflate(reach, reach) } else { b }); + (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 52ed7f0e7f..f10541a55d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -73,8 +73,10 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, - /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). - pub clip: Option, + /// The clipping path its file draws it through, in the image's pixel space, with its fill rule: + /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, + /// [`psdread::clipping_path`]). + pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -894,12 +896,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 @@ -942,7 +951,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. +/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file +/// names ([`png_with_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -950,7 +960,8 @@ pub fn raster_image(bytes: &[u8]) -> Result { } if psdread::is_psd(bytes) { let cms = vectorcraft_color::cms::active(); - return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi); + let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; + return Ok(png_with_clip(img, psdread::clipping_path(bytes))); } if jxlread::is_jxl(bytes) { let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?; @@ -1118,10 +1129,48 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } +/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from +/// ([`png_with_clip`]). +const CLIP_KEYWORD: &str = "VectorCraft clip"; + +/// Longest clipping path a PNG keeps (bytes of its JSON). +const MAX_PNG_CLIP: usize = 16 << 20; + +/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the +/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the +/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is +/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped. +fn png_with_clip(mut img: RasterImage, clip: Option) -> RasterImage { + let Some(clip) = clip else { return img }; + let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img }; + let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]); + img.blob = ImageBlob::new("image/png", png); + img.key = img.blob.content_key(); + img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd)); + img +} + +/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel +/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path +/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data. +pub(crate) fn png_clip(png: &[u8]) -> Option { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return None; + } + let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat(); + let json = super::ppi::png_chunks(png) + .take_while(|(ty, _)| *ty != b"IDAT") + .find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?; + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; @@ -1131,7 +1180,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), ); - let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes)); + let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path)); n.name = Some(name.to_string()); d.images.insert(key, blob); d.insert(Some(layer), 0, n).map_err(err)?; diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 6738f0727c..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; 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", + "{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/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index 9f76de9b15..cf5506ff3b 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St 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 _ in 0..count { + for i in 0..count { // The ID and group ID. r.take(8)?; let origin = r.u32()?; @@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St 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. A descriptor read that uses up the budget is an - // error. - if r.rest().starts_with(&16u32.to_be_bytes()) { + // 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) { @@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result, St 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()) }; @@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result { /// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped. fn unicode(r: &mut Reader<'_>) -> Result { - let n = text_len(r.u32()? as usize)?; - let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?; + 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 { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 6d66b8da4e..2a7340a79e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -414,6 +414,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() { assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}"); } +/// A square saved as "Square" and the clipping path naming it. +fn square_resources() -> Vec { + let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); + [resource(2000, b"Square", &square), clipping_name(b"Square")].concat() +} + +/// `bytes` written as `name` in `dir`, by its path. +fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping +/// path its new file names, take that clip group's clipping path away when the new file names +/// none, and give it back when a later file names one again. +#[test] +fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let square = write_file(&dir, "square.psd", &red_psd(&square_resources())); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap()); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image))); + s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path"); + s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap(); + let d = &s.doc().unwrap().doc; + match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again"); + // The file is saved again with another clipping path. + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image]})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); +} + +/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a +/// text chunk within the size limit that reads as a path gives one back. +#[test] +fn the_kept_png_holds_the_clipping_path_within_bounds() { + let img = raster_image(&red_psd(&triangle_resources())).unwrap(); + let (path, rule) = img.clip.clone().expect("the file's clipping path"); + assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd); + assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path)); + let plain = raster_image(&red_psd(&[])).unwrap(); + assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none()); + let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]); + assert_eq!(super::load::png_clip(&with("not a path".into())), None); + assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read"); +} + +/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that +/// path, under the even-odd rule; a clipping mask made in the document stays around it. +#[test] +fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain"); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let group = d.parent_of(image).expect("a clip group"); + assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image)); + // The clipping path's fill rule changed in the document makes it the document's own mask: a + // relink keeps it and puts the file's clip group inside it. + let clip = match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, .. }) => children[0].id, + other => panic!("{other:?}"), + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::NonZero; + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inner = d.parent_of(image).unwrap(); + assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group"); + assert!(clip_group(d, inner).1, "the file's clip group is even-odd"); +} + #[test] fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() { let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 9748502de2..2d8d0c951f 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() { 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; diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index d1d9123139..7884c1e86b 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -1,7 +1,10 @@ //! SVG encodings, profiles and embedded fonts through the engine: the options reach the file, //! files in each encoding open again, and `document.serialize` reads them as text. +use std::sync::Arc; + use serde_json::json; +use vectorcraft_doc::Document; use super::*; @@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() { assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard"); } +/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its +/// artboard. +fn nib_doc() -> (Document, f64) { + let mut d = Document::new(100.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let x0 = d.artboards[0].rect.x0; + (d, x0) +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of +/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line. +fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node { + let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0); + if brushed { + look.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into()); + vectorcraft_doc::Node::path(d.alloc_id(), line, look) +} + +fn black() -> vectorcraft_color::Paint { + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) +} + +/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that +/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not. +#[test] +fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() { + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let near = nib_line(&mut d, x0 - 5.0, black(), true); + let far = nib_line(&mut d, x0 - 200.0, black(), true); + let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap()); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard"); + assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard"); + let mut s = Session::new(); + s.add_document(d, None); + let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap(); + let svg = svg["text"].as_str().unwrap().to_string(); + assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}"); + let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap(); + let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped"); +} + +/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed +/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art +/// inside it, and a compound path is painted with its own appearance, not its paths': those stay +/// out when only brush art could reach the artboard. +#[test] +fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() { + use vectorcraft_doc::{LayerColor, Node, NodeKind}; + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let x = x0 - 5.0; + // A brushed line in a plain group on a sublayer. + let line = nib_line(&mut d, x, black(), true); + let nested = line.id; + let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false }); + let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1)); + sublayer.children_mut().unwrap().push(Arc::new(group)); + d.insert(Some(layer), 0, sublayer).unwrap(); + // A brushed stroke without a paint. + let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true); + let unpainted = d.insert(Some(layer), 0, unpainted).unwrap(); + // A clipping group whose clip, far left of the artboard, holds a brushed line just off it. + let mut clip = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0), + ); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let member = nib_line(&mut d, x, black(), true); + let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true }); + let clipped = d.insert(Some(layer), 0, clipped).unwrap(); + // Compound paths of a brushed line: plain itself, then brushed itself. + let mut compounds = vec![]; + for own in [false, true] { + let member = nib_line(&mut d, x, black(), true); + let mut compound = + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = nib_line(&mut d, x, black(), own).appearance; + compounds.push(d.insert(Some(layer), 0, compound).unwrap()); + } + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer"); + assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint"); + assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard"); + assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself"); + assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. 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<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> { Ok(sweep(bounds, None)?.groups()) } @@ -206,27 +209,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, }; let boxes: Vec<(usize, Rect)> = 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<usize> = (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<f64> = 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<f64> = 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<f64> = boxes.iter().map(|(_, b)| b.y0).collect(); + let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect(); + let mut open: Vec<Option<usize>> = 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<usize> = (0..n).collect(); by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0)); let mut by_right: Vec<usize> = (0..n).collect(); @@ -241,7 +242,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, while let Some(&c) = by_right.get(closing) && boxes[c].1.x1 < b.x0 { - set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY); + if let Some(p) = open[c].take() { + trees[tree(c)].take(p, c, &bottom); + } closing += 1; } // The open boxes it joins with their top at most this bottom and their bottom at least @@ -253,21 +256,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Some(_) if shadows => &[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<Rect>], see_through: Option<&[bool]>) -> Result<Sets, let ob = boxes[o].1; see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1 }); - // Whatever overlaps a box inside this one overlaps this one, and joins it when this one is - // see-through. Likewise, whatever later overlaps the part of an open box at or below this - // one's top, when that box ends no further right or lower than this one, overlaps this - // one: the open box then keeps only the part above this one's top. - let cut = b.y0.next_down(); + // Whatever overlaps the open part of a box inside this one overlaps this one, and joins it + // when this one is see-through. Likewise, whatever later overlaps the part of an open box + // this one covers, when that box ends no further right than this one, overlaps this one: + // the open box then keeps only the part above this one's top, when this one reaches its + // bottom, or only the part below this one's bottom, when this one reaches its top. for &o in &met { sets.join(boxes[k].0, boxes[o].0); - let ob = boxes[o].1; - if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 { + let Some(p) = open[o] else { continue }; + if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 { continue; } - if b.y0 <= ob.y0 { - set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY); - } else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] { - set(&mut low[tree(o)], leaf[o], cut); + let (t, u) = (top[o], bottom[o]); + let tr = &mut trees[tree(o)]; + if b.y0 <= t && u <= b.y1 { + tr.take(p, o, &bottom); + open[o] = None; + continue; + } + if holder.is_some() || (b.y1 < u && t < b.y0) { + continue; + } + let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) }; + // Every top it can get has a place; one without stays as it is. + let Some(q) = place(t) else { continue }; + tr.take(p, o, &bottom); + (top[o], bottom[o]) = (t, u); + open[o] = (t <= u).then_some(q); + if t <= u { + tr.put(q, o, &bottom); } } - if holder.is_none() { - set(&mut low[tree(k)], leaf[k], b.y1); + if holder.is_none() + && let Some(p) = place(b.y0) + { + open[k] = Some(p); + trees[tree(k)].put(p, k, &bottom); } } Ok(sets) } +/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom +/// below each of its branches. +struct Open { + size: usize, + /// The lowest bottom of the open boxes below each node (−∞: none open). + low: Vec<f64>, + /// The open boxes at each place, by bottom ([`order`]) and then index. + at: Vec<BTreeSet<(i64, usize)>>, +} + +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::<Vec<_>>()]); } + /// `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<Option<Rect>> { + 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::<Vec<_>>()]; + 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<Option<Rect>> = (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<bool> = (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 28662f013c..541cdd1118 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> { always, font_list ), + cmd!( + query "text.glyphCategories", + "Glyph Categories", + [], + None, + "{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)", + always, + glyph_categories + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1146,44 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> { } } +/// `text.glyphCategories`: the OpenType categories of a font's glyphs +/// ([`vectorcraft_text::FontFace::glyph_categories`]). +fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "text.glyphCategories"; + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(bad(C, format!("`{key}` must be a string"))), + }; + let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?; + let db = vectorcraft_text::FontDb::global(); + if !db.has_family(family) { + return Err(bad(C, format!("font family `{family}` is not available"))); + } + let styles = db.styles(family); + let style = match text("style")? { + Some(style) => styles + .iter() + .find(|s| s.eq_ignore_ascii_case(style)) + .cloned() + .ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?, + None => styles.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?; + let categories: Vec<Value> = face + .glyph_categories() + .iter() + .map(|c| { + let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs}); + if let Some(name) = &c.name { + v["name"] = json!(name); + } + v + }) + .collect(); + Ok(json!({"family": face.family, "style": face.style, "categories": categories})) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] 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<Value> { // 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<Value> { _ => 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<Value> { // 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<Value> { }; 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<Value> { 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<NodeId, bool>) { } } +/// 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<NodeId, Vec<bool>> { + 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<NodeId, Vec<bool>>) { + 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 c533cb5e4e..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] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..ec850576de 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// The clipping path an image's file draws it through, with the fill rule its clip group takes: +/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd). +type FileClip = (PathData, FillRule); + +/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it +/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB +/// file's ([`fileio::png_clip`]). +fn file_clip(blob: &ImageBlob) -> Option<FileClip> { + if let Some(path) = blob.separated_clip() { + return Some((path, FillRule::NonZero)); + } + (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) +} + /// What happens to the clip of an object a link update remakes. enum ClipTo { /// It stays as it is. @@ -705,25 +719,25 @@ enum ClipTo { /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group /// holding just it changes, else it goes into a new clip group. Path(PathData), - /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], - /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group - /// again. - File(PathData), + /// It is clipped to this path, the clipping path its file draws it through, under its fill + /// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`] + /// leaves one) becomes a clip group again. + File(FileClip), /// It goes into a new clip group of this path, inside the clip group that holds it. - Nest(PathData), - /// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is + Nest(FileClip), + /// Placement Options clip it to `placement` while its file draws it through `file`: it is /// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to /// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the /// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it, /// clipped to `placement`. - Both { file: Option<PathData>, placement: PathData }, - /// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the + Both { file: Option<FileClip>, placement: PathData }, + /// Placement Options clip it to `placement` while its file draws it through `file`, and the /// clip group holding just it is not its old file's: that clip group's clipping path becomes /// `placement`, and it goes into a new clip group of `file` inside it. - BothInside { file: PathData, placement: PathData }, - /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that - /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility - /// and transparency. + BothInside { file: FileClip, placement: PathData }, + /// The clipping path of the clip group holding just it goes (its old file's clipping path, + /// which its new file lacks): the group stays as a plain group of it, with its id, name, + /// visibility and transparency. Off, } @@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool { } /// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with -/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file -/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip -/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old -/// pixels, under the nonzero rule its clip groups get) goes. +/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file +/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When +/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's +/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes. fn clip_to( old_xf: Affine, - old_clip: Option<&PathData>, + old_clip: Option<&FileClip>, clip: Option<Clip>, img: &RasterImage, new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { - // Whether the clip group holding just the image is the old DCS file's: a clipping path whose - // fill rule was changed in the document is not. + // Whether the clip group holding just the image is the old file's: a clipping path whose fill + // rule was changed in the document is not. let file_held = match (old_clip, held) { - (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), _ => false, }; - let file = img.clip.as_ref().map(|path| path.transformed(new_xf)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); if let Some(clip) = clip { let placement = clip_shape(clip); return match file { @@ -831,7 +845,7 @@ impl Nested<'_> { fn root(&mut self, n: &mut Arc<Node>) { if !(self.pick)(n) { if let Some(placement) = self.update(n, true) { - *n = Arc::new(self.clip_group(Arc::clone(n), placement)); + *n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero))); } return; } @@ -839,7 +853,8 @@ impl Nested<'_> { let mut new = Arc::new(new); let _ = self.update(&mut new, true); *n = match clip { - ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))), + ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)), ClipTo::Both { file, placement } => self.clip_both(new, file, placement), ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement), ClipTo::Keep | ClipTo::Off => new, @@ -848,8 +863,8 @@ impl Nested<'_> { /// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays /// the same node when none is there, and only the nodes on the way to one are copied. The - /// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's - /// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: + /// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping + /// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: /// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new /// clip group of it. #[must_use] @@ -880,8 +895,8 @@ impl Nested<'_> { match (self.update(&mut new, nested), clip_path) { (None, _) if Arc::ptr_eq(&new, c) => {} (None, _) => slots.push((i, new)), - (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]), - (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))), + (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]), + (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))), } continue; } @@ -894,17 +909,22 @@ impl Nested<'_> { let _ = self.update(&mut new, true); match (clip, clip_path) { (ClipTo::Keep, _) => slots.push((i, new)), - (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]), + (ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]), + (ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]), (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), - (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { + (ClipTo::Path(clip), _) => { + let group = self.clip_group(new, (clip, FillRule::NonZero)); + slots.push((i, Arc::new(group))); + } + (ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), (ClipTo::Off, _) => slots.push((i, new)), // The file's clip group stays `n`, and the placement's clip goes around it. - (ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => { - slots.extend([(0, with_clip(path, file)), (1, new)]); + (ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => { + slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]); around = Some(placement); } (ClipTo::Both { file: Some(file), placement }, None) if plain => { @@ -917,7 +937,7 @@ impl Nested<'_> { } (ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => { let group = self.clip_group(new, file); - slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]); + slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]); } (ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))), (ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))), @@ -958,27 +978,28 @@ impl Nested<'_> { /// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a /// `file` ([`ClipTo::Both`] for an object no clip group holds yet). - fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> { + fn clip_both(&mut self, object: Arc<Node>, file: Option<FileClip>, placement: PathData) -> Arc<Node> { let object = match file { Some(file) => Arc::new(self.clip_group(object, file)), None => object, }; - Arc::new(self.clip_group(object, placement)) + Arc::new(self.clip_group(object, (placement, FillRule::NonZero))) } - /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. - fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node { + /// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes + /// one in the layers. + fn clip_group(&mut self, object: Arc<Node>, clip: FileClip) -> Node { let path = self.clipping_path(clip); let group_id = NodeId(self.next); self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } - /// A clipping path of `clip`, with the next node id. - fn clipping_path(&mut self, clip: PathData) -> Node { + /// A clipping path of `clip` under its fill rule, with the next node id. + fn clipping_path(&mut self, (clip, rule): FileClip) -> Node { let id = NodeId(self.next); self.next += 1; - clipping_path(id, clip) + clipping_path(id, clip, rule) } } @@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when -/// no such clip group holds it. -fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill +/// rule `rule` when one is given; false when no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option<FillRule>) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { _ => None, }); let Some(c) = clip_path else { return false }; - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) { *p = path; + *r = rule.unwrap_or(*r); } true } @@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { /// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, /// else it goes into a new clip group. fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { + if set_clip_path(d, id, path.clone(), None) { return Ok(()); } - new_clip_group(d, id, path) + new_clip_group(d, id, (path, FillRule::NonZero)) } -/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping -/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] -/// leaves one) becomes a clip group again, else it goes into a new clip group. -fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { +/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill +/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it +/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { + if set_clip_path(d, id, path.clone(), Some(rule)) { return Ok(()); } let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), _ => false, }); - let Some(g) = plain else { return new_clip_group(d, id, path) }; - let clip = clipping_path(d.alloc_id(), path); + let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) }; + let clip = clipping_path(d.alloc_id(), path, rule); d.insert(Some(g), 0, clip)?; if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { *clip = true; @@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { Ok(()) } -/// Clipping path `path` (a node) with its path changed to `clip`. -fn with_clip(path: &Node, clip: PathData) -> Arc<Node> { +/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when +/// one is given. +fn with_clip(path: &Node, clip: PathData, rule: Option<FillRule>) -> Arc<Node> { let mut path = Node::clone(path); - if let NodeKind::Path { path: p, .. } = &mut path.kind { + if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind { *p = clip; + *r = rule.unwrap_or(*r); } Arc::new(path) } -/// A clipping path `id` of `path`, unpainted. -fn clipping_path(id: NodeId, path: PathData) -> Node { +/// A clipping path `id` of `path` under fill rule `rule`, unpainted. +fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node { let none = vectorcraft_color::Paint::None; let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { + if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { *clipping = true; + *r = rule; } clip } -/// Put object `id` of `d` into a new clip group of `path`, where it is. -fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { +/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; - let clip = clipping_path(d.alloc_id(), path); + let clip = clipping_path(d.alloc_id(), path, rule); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let nested = nested_ids(d, ids); if also.is_some() || !nested.is_empty() { let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); - // The resolution of each content the images picked show, and the clipping path its DCS file + // The resolution of each content the images picked show, and the clipping path its file // drew it through, looked up once each. - let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new(); + let mut old: BTreeMap<String, ((f64, f64), Option<FileClip>)> = BTreeMap::new(); d.visit_stored(|n, _| { if let NodeKind::Image(im) = &n.kind && pick(n) && !old.contains_key(&im.key) { - old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip))); } }); let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { @@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); - // Placement Options' clip, else a DCS file's clipping path, read again with its plates. - let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + // Placement Options' clip, else the clipping path of a DCS file (read again with its + // plates) or of a PSD or PSB file. + let old_clip = d.images.get(&im.key).and_then(file_clip); clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind @@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), - ClipTo::File(path) => clip_file_to(d, id, path), - ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::File(file) => clip_file_to(d, id, file), + ClipTo::Nest(file) => new_clip_group(d, id, file), ClipTo::Off => unclip(d, id), ClipTo::Both { file, placement } => { match file { @@ -1314,27 +1340,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<Node>| { + 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<Node> { +/// `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<Node> { 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 +1396,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> { 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/object.rs b/crates/engine/src/cmd/object.rs index 5eee2d3fce..a58f206c84 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -38,7 +38,7 @@ pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, + snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 64d47ca0a9..a8bb12b429 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -1,6 +1,9 @@ //! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that //! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid -//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>). +//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>), +//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid. + +use std::collections::HashMap; use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; @@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) { keep_pixel_aligned(n, Scaling::default()); } } + refresh_symbols(before, doc); +} + +/// How far the linear part of an instance's transform may be from its symbol's natural size, as a +/// fraction of that size, for the instance to count as placed at actual size. +const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9; + +/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to +/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes +/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends +/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance +/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a +/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included. +/// An instance in another symbol's art is placed by that symbol's instances and is left as it is. +/// A document without pixel-aligned symbols is not walked. +fn refresh_symbols(before: &Document, doc: &mut Document) { + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let was = before.pixel_aligned_symbols(); + let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let mut every = false; + for name in &aligned { + let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_changed = match (art_before, art_now) { + (Some(b), Some(a)) => !Arc::ptr_eq(b, a), + _ => true, + }; + let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name); + if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed { + snap_symbol_art(doc, name); + every = true; + } + } + let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + if every { + for layer in doc.layers.iter_mut() { + if holds_instance(layer, &natural) { + snap_instances_in(Arc::make_mut(layer), &natural); + } + } + return; + } + let (mut ids, mut masked) = (vec![], vec![]); + changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + for id in ids { + if let Some(n) = doc.node_mut(id) { + snap_instance(n, &natural); + } + } + for id in masked { + if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) { + snap_instances_in(Arc::make_mut(&mut m.art), &natural); + } + } +} + +/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in +/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity +/// mask art holds such instances (`masked`). +fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) { + let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None; + for (i, a) in after.iter().enumerate() { + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + continue; + } + if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { + masked.push(a.id); + } + if let NodeKind::SymbolInstance { symbol, .. } = &a.kind { + if natural.contains_key(symbol) { + ids.push(a.id); + } + } else if let Some(children) = a.children() { + changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked); + } + } +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in +/// `natural`. +fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool { + matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol)) + || n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural))) +} + +/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity +/// masks included. Only what holds such an instance is copied for editing. +fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) { + snap_instance(n, natural); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_instance(&m.art, natural) + { + snap_instances_in(Arc::make_mut(&mut m.art), natural); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_instance(c, natural) { + snap_instances_in(Arc::make_mut(c), natural); + } + } + } +} + +/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's +/// natural size: each path and compound path in it snaps as a pixel-aligned object does +/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when +/// something in it moved, and the answer says whether it did. +pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool { + let natural = doc.symbol_natural_xf(name); + let det = natural.determinant(); + if !det.is_finite() || det.abs() < 1e-18 { + return false; + } + let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false }; + // Instances draw the art's strokes at their stored width, and the art of unlinked opacity + // masks, which `Node::transform` leaves alone, at the natural size too. + let mut art = (*sym.art).clone(); + art.transform(natural, false); + transform_unlinked_masks(&mut art, natural); + if !snap_art(&mut art) { + return false; + } + let inverse = natural.inverse(); + art.transform(inverse, false); + transform_unlinked_masks(&mut art, inverse); + sym.art = Arc::new(art); + true +} + +/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks +/// too. Only what holds such a mask is copied for editing. +fn transform_unlinked_masks(n: &mut Node, xf: Affine) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_unlinked_mask(&m.art, !m.linked) + { + let linked = m.linked; + let art = Arc::make_mut(&mut m.art); + if !linked { + art.transform(xf, false); + } + transform_unlinked_masks(art, xf); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_unlinked_mask(c, false) { + transform_unlinked_masks(Arc::make_mut(c), xf); + } + } + } +} + +/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of +/// its masks too, has an unlinked opacity mask. +fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool { + unlinked + || n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false))) +} + +/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of +/// opacity masks included (those of a compound path's paths too). Returns whether anything +/// changed. +fn snap_art(n: &mut Node) -> bool { + let mut moved = false; + if can_align(n) { + let was = n.clone(); + snap_object(n, Scaling::default()); + moved = *n != was; + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if c.extras().mask.is_some() { + moved |= snap_mask(Arc::make_mut(c)); + } + } + } + } else if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + moved |= snap_art(Arc::make_mut(c)); + } + } + // After the object itself, which a linked mask follows. + snap_mask(n) || moved +} + +/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed. +fn snap_mask(n: &mut Node) -> bool { + let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false }; + let mut art = (*m.art).clone(); + if !snap_art(&mut art) { + return false; + } + m.art = Arc::new(art); + true +} + +/// Move symbol instance `n` to whole points when its transform places its symbol's art at the +/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled, +/// rotated (a half turn included) or sheared instance stays where it is. +fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) { + let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return }; + let Some(nat) = natural.get(symbol.as_str()) else { return }; + let [a, b, c, d, e, f] = xf.as_coeffs(); + let [na, _, _, nd, _, _] = nat.as_coeffs(); + let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0); + let actual = + near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0); + // Flipped along both axes is a half turn, which counts as rotated. + let half_turn = a * na < 0.0 && d * nd < 0.0; + if !actual || half_turn || !e.is_finite() || !f.is_finite() { + return; + } + let (x, y) = (e.round(), f.round()); + if x != e || y != f { + *xf = Affine::new([a, b, c, d, x, y]); + } } /// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the -/// pixel-aligned objects in them to the pixel grid again. +/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid +/// again. pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { for id in ids { if doc.node(*id).is_some_and(holds_aligned) @@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { keep_pixel_aligned(n, Scaling::default()); } } + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + for id in ids { + if doc.node(*id).is_some_and(|n| holds_instance(n, &natural)) + && let Some(n) = doc.node_mut(*id) + { + snap_instances_in(n, &natural); + } + } } /// The objects of `after` that differ from their counterparts in `before` (or are new) and are 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<Vec<(bool, bool)>> { .collect() } -/// Each kind's item target and objects: (fill?, item, ids). -fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> { +/// 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<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> { 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<NodeId>), 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<Vec<OverprintJob>> { 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<AttributesInfo> { 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 61b734b4d4..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<CommandSpec> { "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) ), @@ -982,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize> } fn swap(s: &mut Session, p: &Value) -> Result<Value> { - 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(); @@ -1017,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> { } fn default_paint(s: &mut Session, p: &Value) -> Result<Value> { - 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(); @@ -1086,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))), @@ -1105,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::<Vec<_>>()}); - (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<NodeId, Paint> = 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::<Vec<_>>()}); + 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 4bcdeef0e5..7062407c79 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> { "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), 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}", + "{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 ), diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 83216b2f43..250642285d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -71,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<CommandSpec> { vec![ @@ -79,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> { "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), 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; 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", + "{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 ), @@ -106,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> { "Load Place Cursor", [], None, - "{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 → {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 ), @@ -304,7 +306,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); let mut warnings: Vec<String> = 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); + let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } if pdf { @@ -988,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> { } 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() })); } } @@ -995,6 +1005,22 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> { 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 diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index 69a397c5d1..efa02e06a8 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> { }; let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) 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<Story> { 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<Story> { 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<Option<String>> { } /// The XML of the part `name`. -fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result<roxmltree::Document<'a>> { - // 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<El> { + 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"<!--") { - i = past(start + 4, b"-->"); - } else if rest.starts_with(b"<![CDATA[") { - i = past(start + 9, b"]]>"); - } else if rest.starts_with(b"<?") { - i = past(start + 2, b"?>"); - } else if rest.starts_with(b"<!") || rest.starts_with(b"</") { - depth = depth.saturating_sub(usize::from(rest.starts_with(b"</"))); - i = past(start + 2, 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<Op let Some(xml) = part(zip, &rels, cmd)? else { return Ok(None) }; let doc = parse(&xml, &rels, cmd)?; let target = doc - .root_element() - .children() - .filter(|n| n.tag_name().name() == "Relationship" && n.attribute("TargetMode") != Some("External")) - .find(|n| n.attribute("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind))) - .and_then(|n| n.attribute("Target")); + .elements() + .filter(|n| n.local() == "Relationship" && n.attr("TargetMode") != Some("External")) + .find(|n| n.attr("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind))) + .and_then(|n| n.attr("Target")); Ok(target.map(|t| resolve(folder, t))) } @@ -248,22 +212,22 @@ fn resolve(folder: &str, target: &str) -> 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<Node<'a, 'i>> { - 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<f64> { } /// Twentieths of a point. -fn twips(n: Node, name: &str) -> Option<f64> { +fn twips(n: &El, name: &str) -> Option<f64> { attr(n, name).and_then(|v| measure(v, 20.0)) } /// Half points. -fn half_points(n: Node) -> Option<f64> { +fn half_points(n: &El) -> Option<f64> { 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<usize> { + fn font(&mut self, n: &El) -> Option<usize> { 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<Node<'a, 'i>> { +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#"<?xml version="1.0"?><a><b x="1>2" y='</c>'><c/></b><!-- <d><e> --><![CDATA[<f><g>]]></a>"#), 2); - assert_eq!(nesting("<a><b><c>"), 3, "unclosed elements count"); - assert_eq!(nesting("</a></b><a>"), 1); - assert_eq!(nesting("<a x=\"unterminated"), 1); - assert_eq!(nesting(""), 0); - } - #[test] fn targets_resolve_against_their_folder() { assert_eq!(resolve("", "word/document.xml"), "word/document.xml"); diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..6c7be12540 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.fonts", "text.getRange", "text.glyphAlternates", + "text.glyphCategories", "text.insertInline", "text.missingFonts", "text.replaceFont", diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index bec6767228..7c16b64b02 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> { "Randomize Colors", [], None, - "{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", always, randomize ), @@ -1786,8 +1786,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. - let mut news: Vec<(Color, f32, Option<ModelRule>)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + // the color changes; a model moves with its color. A row with no current colors recolors + // nothing, so it keeps its new color and takes no other row's. + let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); + let mut news: Vec<(Color, f32, Option<ModelRule>)> = + rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); if order { rng.shuffle(&mut news); } @@ -1805,7 +1808,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> { .iter() .map(|r| { let (to, tint, model) = - if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); 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<Value> { 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<Value> { })?; // 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<Value> { } 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<Value> { 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/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 606ab40fcf..c3fc9a4392 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { }; d.symbols[index].art = Arc::new(new_art); follow_objects(d, &se.symbol, (&old, old_group), (&art, group)); + // A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the + // editing layer shows the snapped art. + if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) { + let stored = &d.symbols[index].art; + let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] }; + let mut snapped = snapped.into_iter().map(|n| { + let mut n = (*n).clone(); + n.transform(se.xf, false); + Arc::new(n) + }); + if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) { + for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) { + if let Some(n) = snapped.next() { + *c = n; + } + } + } + } if let Some(e) = d.symbol_edit.as_mut() { e.changed = true; e.group = group; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 63096c9d98..b82be77f43 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -499,12 +499,13 @@ fn instance(name: &str) -> Node { } /// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice -/// guides) given to symbol `to` of `d`. +/// guides, Align to Pixel Grid) given to symbol `to` of `d`. fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) { set_natural_size(d, to, Some(natural_size(src, from))); d.set_symbol_registration(to, src.symbol_registration(from)); d.set_symbol_export_type(to, src.symbol_export_type(from)); d.set_symbol_nine_slice(to, src.symbol_nine_slice(from)); + d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from)); } fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo { diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index eb62962ad9..4f3b814760 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> { "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), 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)}", + "{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 ), 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<Value> { 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<Value> { + 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<CommandSpec> { vec![ cmd!( @@ -1057,6 +1074,15 @@ pub fn specs() -> Vec<CommandSpec> { 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<Vec<u8>> { /// 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<String> { 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<Library> { 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<roxmltree::Node> = 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::<String>()); + 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::<String>()); 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<Library> { } 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<Library> { 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<Library> { 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<Library> { /// 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<Option<DataValue>> { - 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<Option<DataValue>> { + 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<String> = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect(); + let paras: Vec<String> = 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<Item = roxmltree::Node<'a, 'i>> { - 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<Option<DataValue>> { - let var = el.tag_name().name(); +fn graph_value(el: &craft_xml::El, set: &str, cmd: &str) -> Result<Option<DataValue>> { + 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<String> = - elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default(); - let rows: Vec<roxmltree::Node> = - 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<Option<DataV let read: Vec<(Option<String>, Vec<Option<f64>>)> = 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::<f64>().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::<f64>().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/lib.rs b/crates/engine/src/lib.rs index aeb723c963..4f7532108d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -179,6 +179,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option<std::path::PathBuf>, + /// The folder of File Info's metadata templates; `None`: no folder + /// ([`Session::attach_metadata_templates_dir`]). + metadata_templates_dir: Option<std::path::PathBuf>, /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option<std::path::PathBuf>, diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 871ca4f399..88d9bd1761 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2012,7 +2012,11 @@ impl Session { Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { let n = job.host.dialogs.unused(); let kind = LimitKind::Host; - let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" }); + let message = if n == 1 { + format!("`answers` has {n} answer the script did not use") + } else { + format!("`answers` has {n} answers the script did not use") + }; Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) } Ok(Ok(Progress::Done(_))) => { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b2836d159c..26403cbbef 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -93,6 +93,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + metadata_templates_dir: None, new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..64a551e872 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3310,6 +3310,85 @@ fn flare_ring_seed_moves_only_the_rings() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. +#[test] +fn ellipse_with_four_anchors_is_the_live_ellipse() { + let mut s = session(); + let draw = |s: &mut Session, extra: Option<u64>| { + let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80}); + if let Some(n) = extra { + p["anchors"] = json!(n); + } + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() + }; + let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4))); + for n in [&plain, &four] { + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + assert_eq!(n.path_data().unwrap().anchor_count(), 4); + } + assert_eq!(plain.path_data(), four.path_data()); + assert_eq!(plain.live_shape(), four.live_shape()); +} + +/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its +/// bounds the typed size, as one undo step. +#[test] +fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() { + let mut s = session(); + let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0); + let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0); + for n in [2u64, 3, 5, 6, 8] { + let undo = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(node.live_shape().is_none(), "{n}: a plain path"); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "{n}"); + assert_eq!(sp.anchors.len() as u64, n); + for a in &sp.anchors { + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}"); + let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2); + assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p); + } + let b = path.bounds().unwrap(); + for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] { + assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}"); + } + } + // The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do. + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap()); + let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p); + assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p); +} + +/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn. +#[test] +fn ellipse_refuses_a_bad_anchor_count() { + let mut s = session(); + let undo = s.doc().unwrap().history.undo.len(); + let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})"); + for (bad, want) in [ + (json!(0), range("0")), + (json!(1), range("1")), + (json!(2.5), range("2.5")), + (json!(-3), range("-3")), + (json!(1001), range("1001")), + (json!("x"), "`anchors` must be a number, not \"x\"".to_string()), + (json!("6"), "`anchors` must be a number, not \"6\"".to_string()), + (json!(true), "`anchors` must be a number, not true".to_string()), + ] { + let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string(); + assert!(e.contains(&want), "{bad}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); +} + /// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the /// drag sizes the halo, and the flare drawn keeps both. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c7160f9316..b09d7fc220 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() { 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::<Vec<_>>(), [green.clone(), green.clone(), green]); - // `through` takes edge ids, with scope "connected" only. + // `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an + // unknown id or an edge given twice is refused and changes nothing. + let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let depth = s.doc().unwrap().history.undo.len(); 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": []}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}), ] { assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}"); } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap(); + assert_eq!(r["count"], 3, "an edge of the group is taken"); } /// A double-click whose second press lands on the next joined edge and is released back on the @@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]); } +/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled +/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as +/// an edge to join through. +#[test] +fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") }; + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.set_tool_option("paintStrokes", &json!(true)); + s.paint.fill = green.clone(); + s.paint.stroke = green.clone(); + for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] { + s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, a), green, "the first click fills the face"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap(); + assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted"); + assert_eq!(fill_of(&s, b), black); +} + /// 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] diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 519974f33d..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] diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 49fd29e94b..50797e35e3 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() { } } +/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the +/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click. +#[test] +fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() { + let mut s = new_doc(); + set_angle(&mut s, 90.0); + let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6}); + let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p)); + assert_eq!(p["anchors"], json!(6)); + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = bounds(&s, id); + for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] { + assert!(close(got, want), "{b:?}"); + } +} + /// The Line Segment tool's Shift steps of 45° count from the Constrain Angle. #[test] fn constrain_angle_steps_the_line_segment_tool() { diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs index 6f56a09b68..36761466ae 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() { assert!(path(&s, b).bounds().unwrap().width() < 100.0); } +/// The warning about objects under the brush that Liquify leaves as they are names their count +/// with the matching noun and verb. +#[test] +fn liquify_warns_about_one_or_several_skipped_objects() { + let mut s = session(); + let text = + |s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap(); + let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1}); + let first = text(&mut s, 520); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first])); + assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only"); + let second = text(&mut s, 560); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first, second])); + assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only"); +} + /// With nothing selected, a stroke leaves the art on a locked artboard as it is. #[test] fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() { diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..fb4eb55789 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() { assert!(paths(&s).is_empty()); } +/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the +/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a +/// shape wholly inside goes, and only the selected paths take part when something is selected. One +/// undo step puts everything back, and a rectangle that touches nothing adds no undo step. +#[test] +fn erase_region_rect_erases_everything_inside_it() { + let filled = |s: &Session, x: f64, y: f64| { + paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))) + }; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + rect(&mut s, 180.0, 140.0, 10.0, 10.0); + line(&mut s, 50.0, 150.0, 350.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let undo = undo_steps(&s); + let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap(); + assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it"); + assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled"); + let ps = paths(&s); + assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}"); + let open: Vec<f64> = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2, "the line is cut in two: {open:?}"); + assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paths(&s).len(), 3); + assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0)); + // A rectangle away from the art erases nothing and adds no undo step. + let undo = undo_steps(&s); + assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []})); + assert_eq!(undo_steps(&s), undo); + // With the line selected, only the line is erased. + let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0; + s.execute("select.set", &json!({"ids": [ln.0]})).unwrap(); + let closed: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap(); + let after: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + assert_eq!(after, closed, "the unselected squares are unchanged"); + let open: Vec<f64> = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2); + assert!((open.iter().sum::<f64>() - 270.0).abs() < 0.01, "{open:?}"); +} + +/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle +/// falls between the samples the path's length would give. +#[test] +fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() { + let mut s = session(); + line(&mut s, 0.0, 100.0, 10000.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap(); + let mut open: Vec<f64> = paths(&s).iter().map(|(_, pd)| pd.length()).collect(); + open.sort_by(f64::total_cmp); + assert_eq!(open.len(), 2, "{open:?}"); + assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}"); +} + +/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height +/// above 0, and `rect` given with `points`, and changes nothing. +#[test] +fn erase_region_rect_refuses_bad_values() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let shape = "rect is [x, y, width, height] in points, with a width and a height above 0"; + for p in [ + json!({"rect": [10, 10, 0, 20]}), + json!({"rect": [10, 10, 20, -5]}), + json!({"rect": [10, 10, 20]}), + json!({"rect": [10, "10", 20, 20]}), + json!({"rect": [1e308, 0, 1e308, 20]}), + json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}), + ] { + refuses_with(&mut s, "path.eraseRegion", &p, shape); + } + refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both"); +} + /// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is /// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one /// compound path; a drag through the whole ring leaves compound paths whose holes stay holes. @@ -2326,6 +2404,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<Point> = (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] diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index 8a152cd44e..54482826b3 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -582,3 +582,233 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() { } let _ = std::fs::remove_dir_all(dir); } + +/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled +/// Poster. +fn template_session(dir: &std::path::Path) -> Session { + let mut s = session(); + s.attach_metadata_templates_dir(dir.join("Metadata Templates")); + s +} + +#[test] +fn a_saved_metadata_template_is_listed_and_applies_to_another_document() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template"); + let mut s = template_session(&dir); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet"); + s.execute("file.info", &info()).unwrap(); + let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap(); + assert_eq!(r["name"], "Studio"); + let path = dir.join("Metadata Templates").join("Studio.xmp"); + assert!(path.is_file(), "saved into the folder: {r}"); + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][0]["name"], "Studio"); + assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1)); + // A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file. + for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] { + assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}"); + } + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1)); + // Saving is not an edit of the document. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Into a new document, by name, in one undo step. + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], true); + let m = &s.doc().unwrap().doc.metadata; + assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4)); + assert_eq!(m.keywords, ["fair", "Poster", "print"]); + assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada")); + assert_eq!(m.description, "A poster\nfor the fair"); + assert_eq!(r["title"], "Poster", "the template carries the title of its own"); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Applied again, nothing changes and nothing is recorded. + let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], false); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.metadata.author, ""); + // The same name replaces the template. + s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap(); + let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(back.author.as_deref(), Some("Grace")); + assert_eq!(back.title, None, "an Untitled-N title is not written"); +} + +#[test] +fn a_metadata_template_merges_in_three_modes() { + let mut s = session(); + s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap(); + let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { + author: Some("Grace".into()), + description: Some("From the template".into()), + keywords: Some(vec!["print".into(), "Fair".into()]), + rating: Some(5), + copyrighted: Some(false), + ..Default::default() + }); + let merged = + |s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap(); + // Clear and replace: the fields the template lacks are cleared; the title stays. + let r = merged(&mut s, "replace"); + assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5))); + assert_eq!( + (r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()), + (json!(["print", "Fair"]), Some(""), Some("publicDomain")) + ); + assert_eq!(r["title"], "Poster"); + // Keep and replace: the template's fields replace those it has; the others stay. + let r = merged(&mut s, "keep"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a"))); + assert_eq!(r["keywords"], json!(["print", "Fair"])); + // Keep and append: keywords are added (each once), and only empty fields are filled. + let r = merged(&mut s, "append"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template"))); + assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain"))); + // `apply: false` changed nothing; `base` merges into the given fields instead. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada"); + let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Applied: one undo step. + s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), 2); + assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, ""); +} + +#[test] +fn metadata_template_errors() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors"); + let mut s = template_session(&dir); + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + let not_xmp = dir.join("note.xmp"); + std::fs::write(¬_xmp, "<note>not metadata</note>").unwrap(); + let big = dir.join("big.xmp"); + std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap(); + let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + for bad in [ + json!({"data": xmp, "mode": "merge"}), + json!({"data": xmp}), + json!({"data": xmp, "mode": 3}), + json!({"mode": "keep"}), + json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}), + json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": big.to_str().unwrap(), "mode": "keep"}), + json!({"name": "missing", "mode": "keep"}), + json!({"data": "Ada Lovelace", "mode": "keep"}), + json!({"data": xmp, "mode": "keep", "apply": "yes"}), + json!({"data": xmp, "mode": "keep", "base": [1]}), + json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}), + ] { + assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}"); + } + for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] { + assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), 0); + assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder"); + // A link in the folder is not followed, by its name or its file name. + #[cfg(unix)] + { + let outside = dir.join("outside.xmp"); + std::fs::write(&outside, &xmp).unwrap(); + std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap(); + for name in ["Linked", "Linked.xmp"] { + assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}"); + } + let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([])); + // A save by that name leaves the linked file as it was. + let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp); + std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap(); + } + // Without a folder (runs without preferences), a name is an error, the data comes back, and + // the list is empty. + let mut s = session(); + assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err()); + let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string(); + assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada")); + assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []})); +} + +#[test] +fn the_templates_folder_lists_only_xmp_files_and_can_be_made() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list"); + let mut s = template_session(&dir); + let r = s.execute("file.info.templates", &json!({"create": true})).unwrap(); + let folder = dir.join("Metadata Templates"); + assert!(folder.is_dir()); + assert_eq!(r["folder"], folder.to_str().unwrap()); + for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] { + std::fs::write(folder.join(f), "x").unwrap(); + } + std::fs::create_dir(folder.join("c.xmp")).unwrap(); + // Other files, however many, leave the templates listed. + for i in 0..1000 { + std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap(); + } + let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(names, ["a", "b"]); + // A listed name opens whatever the case of its extension. + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP"), xmp).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Its listed file name opens it too. + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][1]["file"], "b.XMP"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + // A listed file name is taken before the name with `.xmp` added. + let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Ada"); + // A name that is not a file name never opens the template its safe form names. + let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("a-b.xmp"), grace).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + for name in ["a/b", "a\\b", "a:b"] { + let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err(); + assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}"); + } +} + +#[test] +fn the_largest_file_info_saves_a_template_that_imports() { + let mut s = session(); + let text = "\"&".repeat(32_768); + let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect(); + let fields = json!({ + "author": text, "authorTitle": text, "description": text, "copyrightNotice": text, + "copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted", + }); + let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string(); + assert!(data.len() > 1 << 20, "{} bytes", data.len()); + let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap(); + assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000))); +} + +#[test] +fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() { + let mut m = DocMetadata::default(); + let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() }; + crate::cmd::fileinfo::read_pdf(&mut m, f); + assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3)); +} diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..5eb059bd3b 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -49,6 +49,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { assert!(!d.is_dirty(), "nothing to save"); } +/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a +/// stylistic set's name, and refuses a font that isn't available and params that aren't strings. +#[test] +fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + let mut s = Session::new(); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap(); + assert_eq!(r["family"], CATEGORIES_FAMILY); + assert_eq!(r["style"], "Regular"); + assert_eq!( + r["categories"], + json!([ + {"id": "ligatures", "glyphs": [g('L')]}, + {"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]}, + {"id": "smallCaps", "glyphs": [g('B')]}, + {"id": "figures", "glyphs": figures}, + ]) + ); + assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r); + for (p, says) in [ + (json!({}), "missing `family`"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"), + ] { + let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } +} + /// Refreshing the font list while a background save writes the file leaves the document saved /// once the file is written. #[test] 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/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/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/persp_text.rs b/crates/engine/src/tests/persp_text.rs index b5dc5e7a53..443913a635 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() { assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none()); } +/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane. +#[test] +fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() { + let (mut s, _) = persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + let at = Point::new(470.0, 300.0); + let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6}); + let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap(); + let n = undo_len(&s); + let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right)); + assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6); +} + #[test] fn the_canvas_draws_type_in_perspective_foreshortened() { let (mut s, rect) = persp_session(); diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 06057d1fc0..b70098d9c9 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1158,3 +1158,304 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() { assert!(!aligned(&s, off)); assert_eq!(not_aligned(&mut s, &[compound]), vec![other]); } + +/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them. +fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> { + let d = &s.doc().unwrap().doc; + let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") }; + let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art; + let mut out = vec![]; + art.walk(&mut |n| { + if let Some(p) = n.path_data() { + out.extend(p.anchors().map(|(_, _, a)| { + let q = *xf * a.p; + (q.x, q.y) + })); + } + }); + out +} + +/// The transform of symbol instance `inst`. +fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine { + match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind { + NodeKind::SymbolInstance { xf, .. } => *xf, + _ => panic!("{inst} is not a symbol instance"), + } +} + +/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection +/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a +/// point; a symbol made without it keeps the art where it was drawn. +#[test] +fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let inst = r["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(list["symbols"][0]["alignToPixelGrid"], true); + + path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0); + let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap(); + assert_eq!(plain["alignToPixelGrid"], false); + let pts = placed_points(&s, plain["id"].as_u64().unwrap()); + assert!(!whole(&pts), "{pts:?}"); +} + +/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges +/// fall on the grid. +#[test] +fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert!(halves(&pts), "{pts:?}"); +} + +/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled +/// one where it is; instances placed later land on whole points; asking again for the value the +/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value +/// that is not true or false is refused. +#[test] +fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap(); + let scaled = instance_xf(&s, b); + assert!(!whole(&placed_points(&s, a))); + + let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let pts = placed_points(&s, a); + assert!(whole(&pts), "{pts:?}"); + assert_eq!(instance_xf(&s, b), scaled); + let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, c); + assert!(whole(&pts), "{pts:?}"); + + let steps = undo_len(&s); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(undo_len(&s), steps); + + assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy"); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy")); + s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid")); + assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px")); + s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none()); + + path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err()); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err()); + s.execute("symbol.new", &json!({"name": "Q"})).unwrap(); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err()); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err()); +} + +/// An instance reflected across one axis goes back to whole points after a move; one turned a half +/// turn counts as rotated and moves by exactly the amount asked. +#[test] +fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e, f] = instance_xf(&s, inst).as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let [.., e0, f0] = instance_xf(&s, inst).as_coeffs(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e1, f1] = instance_xf(&s, inst).as_coeffs(); + assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}"); +} + +/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the +/// path places it. +#[test] +fn an_instance_on_a_path_stays_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "attached: {pts:?}"); + let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]); + s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "path edited: {pts:?}"); +} + +/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of +/// the art. +#[test] +fn mask_art_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask +/// is drawn at the symbol's natural size. +#[test] +fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap(); + std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false; + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's +/// art snaps with the rest of the art. +#[test] +fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id; + d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made +/// pixel-aligned. +#[test] +fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inst = d.remove(NodeId(b)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true))); + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap(); + let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") }; + let [.., e, f] = xf.as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); +} + +/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored +/// on the pixel grid, so its instances stay on it. +#[test] +fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [part]})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + // The editing layer shows the art as it is stored. + let shown = points(&s, part); + assert!(whole(&shown), "{shown:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} 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/recolor.rs b/crates/engine/src/tests/recolor.rs index e582f30353..8a950fcbb3 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -409,6 +409,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() { assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept"); } +/// A row with no current colors (New Row) keeps its new color through Randomize, and its color +/// goes to no row that holds current colors: the other rows shuffle their own colors only. +#[test] +fn randomize_leaves_an_empty_row_out() { + let mut s = session(); + let map = json!([ + {"from": [], "to": "rgb 0 255 0"}, + {"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + ]); + for seed in 0..16 { + let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed})); + assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color"); + let mut tos: Vec<String> = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect(); + tos.sort(); + assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors"); + } + let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3})); + assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness"); +} + #[test] fn edit_group_rewrites_in_order_as_one_undo_step() { let mut s = session(); diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index f955a6fdb3..baa8989208 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() { assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing"); } +/// The error about answers left over names their count with the matching noun. +#[test] +fn unused_answers_are_counted_in_the_singular_and_the_plural() { + let mut s = one_doc(); + let ok = json!({"kind": "alert", "value": "ok"}); + for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] { + let given = Value::Array(vec![ok.clone(); extra + 1]); + let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string(); + assert!(e.contains(says), "{e}"); + } +} + #[test] fn invalid_answers_are_rejected_before_run() { let mut s = one_doc(); diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index b369346096..cc89a8261b 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -468,6 +468,15 @@ fn malformed_docx_fails_cleanly() { assert!(e.contains("not a WordprocessingML document"), "{e}"); let e = place(&mut s, "a.docx", &store(&[("word/document.xml", b"<w:document><w:body>")])).unwrap_err(); assert!(e.contains("not well-formed XML"), "{e}"); + for xml in [ + format!(r#"<w:document xmlns:w="{W_NS}"><w:body><w:p><w:r><w:t>partial text</w:t></w:r></w:p>"#), + document("<w:p><w:r><w:t>A&missing;B</w:t></w:r></w:p>"), + document("<w:p><w:r><w:t xml:space=\"preserve\" xml:space=\"default\">text</w:t></w:r></w:p>"), + document("<w:p xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\"><w:r><w:t>text</w:t></w:r></w:p>"), + ] { + 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("<w:p/>").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/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#"<variableSets><variableSet><variables><variable varName="Name" trait="textcontent"/></variables><sampleDataSets><sampleDataSet dataSetName="Row 1"><Name><p>Charlie</p></Name></sampleDataSet></sampleDataSets></variableSet></variableSets>"#; + 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<String> = 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!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000)); let cases = [ ("not well-formed XML", "<variableSets><variableSet>".to_string()), + ("not well-formed XML", ok.replace("<p>x</p>", "<p>A&missing;B</p>")), + ("not well-formed XML", ok.replace("</variableSets>", "")), + ("not well-formed XML", ok.replace("varName=\"Name\"", "varName=\"Name\" varName=\"Other\"")), + ("not well-formed XML", ok.replace("<variable ", "<variable xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\" ")), + ("missing `varName`", ok.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Name\"")), ("no `variableSets` element", "<svg><variables/></svg>".to_string()), ("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".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 59eb78a51b..1134f6963a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -255,7 +255,7 @@ 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 + // The lending tool 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); 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.rs b/crates/eps/src/ai_editing.rs index f27e646791..b6ddb245c2 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -265,6 +265,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi /// [`export_ai_editing`] writing at most `max_objects` objects, counted as the reader counts them. fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Result<AiEditingOutput, String> { + export_held(doc, o, max_objects, true) +} + +/// [`export_within`]; with `keep_wraps`, wrapped area type the reader wraps the same is written as +/// type ([`writer::wraps_held`]). When such type is written and art is left out at the object +/// limit, the wrap objects above it may be among what is left out, and the document is written +/// again with that type as its outlines. +fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep_wraps: bool) -> Result<AiEditingOutput, String> { + let doc = source; let board = doc.artboards.first().ok_or("the document has no artboard")?.rect; if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) { return Err("the document has no artboard".into()); @@ -277,6 +286,8 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re let (symbol_styled, pattern_styled) = writer::styled_definitions(doc); let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; let links = writer::style_links(doc); + // Before baking, which leaves the wrap objects that may be written as they are unchanged. + let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() }; // Live geometry effects as their result, as the PDF part draws them. let baked = baked(doc); let doc = baked.as_ref().unwrap_or(doc); @@ -309,6 +320,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re w.brushes_live = scale == 1.0; w.symbol_doc = symbol_doc; w.max_objects = max_objects; + w.wraps_held = wraps_held; w.reserve_swatch_gradients(); if scale == 1.0 { w.styled = styled; @@ -320,6 +332,9 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re for layer in &doc.layers { w.layer(layer); } + if w.wrapped_type_cut() { + return export_held(source, o, max_objects, false); + } // The symbols no instance uses too; their art adds definitions. w.symbols(); // The brushes, once the layers have said whether an object is written with one. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index c1e1d664df..598e66bc3d 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10810,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<String>); + +/// 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<EnvelopeRoute>, Vec<String>) { + 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<Option<Color>> = 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<f64> = 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 @@ -10923,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); @@ -11508,6 +11634,349 @@ fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f 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) } +/// A `w` × `h` document of area type "Body" in the frame `frame`, with `over` above it (bottom +/// first), its wrap shapes resolved as the canvas resolves them. +fn wrapped_body(w: f64, h: f64, frame: Rect, over: impl FnOnce(&mut Document) -> Vec<Node>) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let mut doc = Document::new(w, h); + let layer = doc.layers[0].id; + let size = frame.height() / 20.0; + let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(size, Color::BLACK)); + body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(size, Color::BLACK))]; + body.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + body.xf = Affine::IDENTITY; + let body = named(text_node(&mut doc, body), "Body"); + let over = over(&mut doc); + for n in std::iter::once(body).chain(over) { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + doc +} + +/// The characters, frame and wrap shapes of the area type on `doc`'s first layer, as it is (its +/// shapes not resolved again). +fn area_type(doc: &Document) -> Option<(String, Option<Rect>, usize)> { + use vectorcraft_doc::TextKind; + doc.layers[0].children().unwrap().iter().find_map(|n| match &n.kind { + NodeKind::Text(t) if matches!(&t.kind, TextKind::Area { .. }) => { + let TextKind::Area { frame } = &t.kind else { return None }; + Some((t.runs.iter().map(|r| r.text.as_str()).collect(), frame.transformed(t.xf).bounds(), t.wrap.len())) + } + _ => None, + }) +} + +/// Area type wrapped only by plain paths, compound paths and groups that don't clip is written as +/// type and reopens as area type with its characters, its frame and the same wrap shapes, which +/// the reader works out again from the objects above it ([`crate::import`]'s +/// `resolve_text_wrap`): a filled path with a negative offset and Invert Wrap, a locked path with +/// only a stroke, a compound path, a group of two squares with a hidden member, an offset of +/// -1000 pt, and an empty group and an open line with options, which wrap nothing. +#[test] +fn area_type_wrapped_by_plain_objects_stays_type() { + type Make = fn(&mut Document) -> Vec<Node>; + fn ring(doc: &mut Document, r: Rect) -> Node { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(r.inset(-10.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + ring + } + let cases: [(&str, Make); 6] = [ + ("a path, a negative offset, Invert Wrap", |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -4.25, true)] + }), + ("a locked stroked path", |doc| { + let mut n = Node::path( + doc.alloc_id(), + shapes::ellipse(Rect::new(80.0, 30.0, 180.0, 130.0)), + Appearance::basic(Paint::None, solid(Color::BLACK), 2.0), + ); + n.locked = true; + vec![wrapped(n, 6.0, false)] + }), + ("a compound path", |doc| vec![wrapped(ring(doc, Rect::new(80.0, 30.0, 200.0, 150.0)), 7.0, true)]), + ("a group", |doc| { + let a = square(doc, Rect::new(40.0, 40.0, 80.0, 80.0), Color::gray(0.5)); + let mut hidden = square(doc, Rect::new(120.0, 40.0, 160.0, 80.0), Color::gray(0.5)); + hidden.visible = false; + let b = square(doc, Rect::new(200.0, 100.0, 240.0, 140.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![a, hidden, b], false), -2.0, false)] + }), + ("an offset of -1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -1000.0, false)]), + ("an empty group and an open line", |doc| { + let line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 20.0).into(), (280.0, 180.0).into()), + Appearance::basic(Paint::None, solid(Color::BLACK), 1.0), + ); + let empty = group(doc, vec![], false); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(n, 3.0, false), wrapped(empty, 5.0, false), wrapped(line, 5.0, false)] + }), + ]; + for (name, make) in cases { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0, "{name}: the type is wrapped"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{name}: {:?}", out.warnings); + assert!(text_out.contains("/AI11Text"), "{name}"); + let back = read_back(&doc); + let after = area_type(&back).unwrap_or_else(|| panic!("{name}: no area type\n{text_out}")); + assert_eq!(after.0, before.0, "{name}"); + let (b, a) = (before.1.unwrap(), after.1.unwrap()); + assert!([b.x0 - a.x0, b.y0 - a.y0, b.x1 - a.x1, b.y1 - a.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {a:?}"); + assert_eq!(after.2, before.2, "{name}: the reader wrapped it"); + assert!(same_region(&area_wrap_region(&doc), &area_wrap_region(&back)), "{name}\n{text_out}"); + // The object that wraps it comes back as the same kind, lock and options. + let source = |d: &Document| { + let n = d.layers[0].children().unwrap()[1].clone(); + (std::mem::discriminant(&n.kind), n.locked, n.visible, n.extras().wrap) + }; + assert_eq!(source(&back), source(&doc), "{name}\n{text_out}"); + } +} + +/// Area type stays outlines when a wrap object above it is not written as itself, or its shapes +/// are not the ones the objects above it give it: an object with an effect, a blend, a symbol +/// instance, a path with a gradient, a compound path with a hidden member, a group holding type, +/// a compound path of one subpath (read back as a path), an offset past 1000 pt, a clipping group, and shapes of an object that has moved since. +#[test] +fn area_type_wrapped_by_other_objects_stays_outlines() { + type Make = fn(&mut Document) -> Vec<Node>; + let cases: [(&str, Make); 10] = [ + ("an effect", |doc| { + let n = styled_rect(doc, "Shadowed", Rect::new(100.0, 40.0, 160.0, 120.0), solid(Color::gray(0.5)), Paint::None, vec![drop_shadow()]); + vec![wrapped(n, 4.0, false)] + }), + ("a blend", |doc| { + 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() }; + vec![wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 4.5, false)] + }), + ("a symbol instance", |doc| { + two_leaves(doc); + vec![wrapped(instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])), 4.5, false)] + }), + ("a gradient", |doc| { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]); + let ap = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0); + vec![wrapped(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 40.0, 160.0, 120.0)), ap), 4.0, false)] + }), + ("a compound path with a hidden member", |doc| { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 180.0, 130.0)), Appearance::default()); + inner.visible = false; + let mut ring = + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(ring, 4.0, false)] + }), + ("a group holding type", |doc| { + let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(100.0, 100.0), "Label", style(20.0, Color::BLACK)); + let label = text_node(doc, label); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![n, label], false), 4.0, false)] + }), + ("a compound path of one subpath", |doc| { + let only = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut one = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(only)], rule: FillRule::NonZero }); + one.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(one, 4.0, false)] + }), + ("an offset past 1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 1000.5, false)]), + ("a clipping group", |doc| { + let clip = clipping(doc, shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0))); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![clip, n], true), 4.0, false)] + }), + ("a path moved since", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)]), + ]; + let mut typed = vec![]; + for (name, make) in cases { + let mut doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + assert_ne!(area_type(&doc).unwrap().2, 0, "{name}: the type is wrapped"); + if name == "a path moved since" { + let id = doc.layers[0].children().unwrap()[1].id; + doc.node_mut(id).unwrap().transform(Affine::translate((30.0, 0.0)), false); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + if !out.warnings.iter().any(|w| w == writer::TYPE) || area_type(&read_back(&doc)).is_some() { + typed.push(name); + } + } + assert!(typed.is_empty(), "written as type: {typed:?}"); +} + +/// Each frame of threaded area type is checked on its own: a thread whose first frame is wrapped +/// by a path and a group and whose second by the group alone is written as type and reopens as the +/// same thread with the same shapes in each frame; with a blend over the second frame, the whole +/// thread is written as outlines. +#[test] +fn threaded_area_type_wrapped_by_plain_objects_stays_type() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + for blend in [false, true] { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + first.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve thirteen fourteen ", st.clone())]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 90.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("fifteen sixteen seventeen eighteen nineteen twenty", st.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(210.0, 10.0, 390.0, 90.0)) }; + let (first, second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second")); + doc.text_threads.push(vec![first.id, second.id]); + let path = wrapped(square(&mut doc, Rect::new(60.0, 20.0, 100.0, 60.0), Color::gray(0.5)), -3.0, true); + let over_second = if blend { + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(250.0, 20.0, 260.0, 30.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(340.0, 60.0, 350.0, 70.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(30.0), ..Default::default() }; + wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 2.0, false) + } else { + let a = square(&mut doc, Rect::new(250.0, 20.0, 290.0, 60.0), Color::gray(0.5)); + let b = square(&mut doc, Rect::new(120.0, 50.0, 300.0, 80.0), Color::gray(0.5)); + wrapped(group(&mut doc, vec![a, b], false), 2.0, false) + }; + // Bottom first: the first frame, the path, the second frame, the group or blend. + for n in [first, path, second, over_second] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + type Region = Vec<(Vec<[f64; 4]>, f64, bool)>; + let shapes = |d: &Document| -> Vec<Region> { + d.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some( + 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(), + ), + _ => None, + }) + .collect() + }; + let before = shapes(&doc); + assert_eq!(before.iter().map(Vec::len).collect::<Vec<_>>(), [2, 1], "blend: {blend}"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + if blend { + assert!(out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert!(back.text_threads.is_empty()); + continue; + } + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert_eq!(back.text_threads.len(), 1); + let names: Vec<_> = back.text_threads[0].iter().map(|id| back.node(*id).and_then(|n| n.name.clone())).collect(); + assert_eq!(names, [Some("First".to_string()), Some("Second".to_string())]); + let after = shapes(&back); + assert_eq!(after.len(), 2); + for (b, a) in before.iter().zip(&after) { + assert!(same_region(b, a), "{before:?}\n{after:?}"); + } + } +} + +/// Wrapped area type is written as type only while the wrap shapes of all the area type the reader +/// reads stay within what it copies: 150 frames under a wrap object of 10,000 anchors are, and +/// with 100 more frames under it, none are. +#[test] +fn area_type_wrapped_past_the_reader_limit_stays_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let area = |doc: &mut Document| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", style(10.0, Color::BLACK)); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)) }; + t.xf = Affine::IDENTITY; + let n = text_node(doc, t); + doc.insert(Some(doc.layers[0].id), 0, n).unwrap() + }; + let mut doc = Document::new(100.0, 100.0); + let ids: Vec<_> = (0..150).map(|_| area(&mut doc)).collect(); + let mut zigzag = vec![(40.0, 0.0).into()]; + zigzag.extend((1..10_000).map(|i| vectorcraft_geom::Point::new(40.0 + 20.0 * f64::from(i) / 10_000.0, if i % 2 == 0 { 0.0 } else { 100.0 }))); + let n = wrapped( + Node::path(doc.alloc_id(), PathData::new(vec![vectorcraft_geom::SubPath::polyline(&zigzag, true)]), Appearance::default()), + 6.0, + false, + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + let held = writer::wraps_held(&doc, &std::collections::HashMap::new()); + assert!(ids.iter().all(|id| held.contains(id)), "{} of {}", held.len(), ids.len()); + for _ in 0..100 { + area(&mut doc); + } + assert!(vectorcraft_doc::text::wrap_work(&doc) > crate::import::MAX_WRAP_WORK); + assert!(writer::wraps_held(&doc, &std::collections::HashMap::new()).is_empty()); +} + +/// Wrapped area type stays type with room for every object, and is written as outlines when art is +/// left out at the object limit: one object short, the wrap object above it would be left out and +/// the reader would not wrap the type. +#[test] +fn area_type_wrapped_past_the_object_limit_is_written_as_outlines() { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)] + }); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let all = export_within(&doc, &opts(), read).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::TYPE), "{:?}", all.warnings); + let short = export_within(&doc, &opts(), read - 1).unwrap(); + assert!(short.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", short.warnings); + assert!(short.warnings.iter().any(|w| w == writer::TYPE), "{:?}", short.warnings); + let (back, _) = crate::ai_alone(&short.program).unwrap(); + assert!(area_type(&back).is_none(), "{}", String::from_utf8_lossy(&short.program)); +} + +/// On a large canvas, area type wrapped by a plain path is written as type and reopens with the +/// same wrap shapes, the offset at its size. +#[test] +fn area_type_wrapped_on_a_large_canvas_stays_type() { + let doc = wrapped_body(20_000.0, 20_000.0, Rect::new(1000.0, 1000.0, 9000.0, 9000.0), |doc| { + vec![wrapped(square(doc, Rect::new(3000.0, 3000.0, 5000.0, 6000.0), Color::gray(0.5)), -12.5, true)] + }); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + let back = read_back(&doc); + let after = area_type(&back).expect("area type"); + assert_eq!((after.0.as_str(), after.2), (before.0.as_str(), before.2)); + let (b, a) = (area_wrap_region(&doc), area_wrap_region(&back)); + let close = b.len() == a.len() + && b.iter().zip(&a).all(|(b, a)| { + b.0.len() == a.0.len() + && b.0.iter().zip(&a.0).all(|(x, y)| x.iter().zip(y).all(|(x, y)| (x - y).abs() < 1e-2)) + && (b.1 - a.1).abs() < 1e-3 + && b.2 == a.2 + }); + assert!(close, "{b:?}\n{a:?}"); +} + /// 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. diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 1b48697e32..7c211add4d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -31,6 +31,7 @@ pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] @@ -49,7 +50,7 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; /// [`vectorcraft_doc::MAX_DEPTH`]. pub(super) const MAX_NEST: u32 = 8; -pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; +pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; @@ -228,6 +229,10 @@ pub(super) struct Writer<'a> { bound: Vec<(vectorcraft_doc::NodeId, String, Vec<String>)>, /// The text document: the stories of the type written as text. pub(super) texts: texts::TextDoc, + /// The area type with wrap shapes that may be written as type ([`texts::wraps_held`]). + pub(super) wraps_held: HashSet<NodeId>, + /// Area type with wrap shapes was written as type. + wrapped_typed: bool, /// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false /// on a large canvas, where they are written as their art. pub(super) symbols_live: bool, @@ -348,6 +353,8 @@ impl<'a> Writer<'a> { typed: false, bound: vec![], texts: texts::TextDoc::default(), + wraps_held: HashSet::new(), + wrapped_typed: false, cms: vectorcraft_color::cms::active(), body: String::new(), warnings: vec![], @@ -404,6 +411,12 @@ impl<'a> Writer<'a> { } } + /// Was area type with wrap shapes written as type, and art left out at the object limit + /// ([`Self::take_objects`])? The reader may then wrap that type by fewer objects than it had. + pub(super) fn wrapped_type_cut(&self) -> bool { + self.wrapped_typed && self.left_out > 0 + } + /// Whether `count` more objects may be written: the objects written so far, counted as the /// reader counts them ([`object_count`]), stay within [`Self::max_objects`]. Past it the art is /// left out, with a warning. @@ -1482,7 +1495,11 @@ impl<'a> Writer<'a> { let thread = doc.text_threads.iter().find(|th| th.contains(&n.id)); let contents = self.contents_level.filter(|(hidden, nest, _)| (*hidden, *nest) == (self.hidden, self.nest)); // Type that can't be a stub is written as its outlines, which count their own objects. - if (self.hidden > 0 && contents.is_none()) || self.clip.is_some() || self.in_symbol || (thread.is_none() && !texts::holds(n, t)) { + if (self.hidden > 0 && contents.is_none()) + || self.clip.is_some() + || self.in_symbol + || (thread.is_none() && !texts::holds(n, t, self.wraps_held.contains(&n.id))) + { self.outlined += 1; return self.outlined_text(n, xy); } @@ -1495,7 +1512,7 @@ impl<'a> Writer<'a> { } let placed = if let Some(thread) = thread { // A thread is checked for what it loses, in every frame, when its story is written. - let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id)); + let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) @@ -1507,6 +1524,7 @@ impl<'a> Writer<'a> { return self.outlined_text(n, xy); }; self.typed = true; + self.wrapped_typed |= !t.wrap.is_empty(); if lost { self.warn(texts::TYPE_ATTRIBUTES); } diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 09c6a33550..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)) { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 9bc831e537..506d13d9fc 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -17,6 +17,7 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Write; +use std::sync::Arc; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; @@ -197,8 +198,8 @@ fn solid(p: &Paint) -> Option<Option<Color>> { /// Can the text document hold type `t` of object `n` as it is: point type that isn't mirrored, or /// area type or type on a path that is only moved ([`shape`]); characters other than inline graphics /// and ruby; solid fills and strokes; no fills, strokes, effects or opacity mask of the object's -/// own; some text. -pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { +/// own; some text. Area type with wrap shapes only when `wrap_held` ([`wraps_held`]). +pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject, wrap_held: bool) -> bool { let xf = t.xf.as_coeffs(); let shape_ok = match &t.kind { TextKind::Point => xf.iter().all(|v| v.is_finite()) && t.xf.determinant() > 1e-12, @@ -210,10 +211,9 @@ pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { } }; // Area type with wrap shapes: the text document doesn't hold them. The reader works them out - // again from the art above the type, which can wrap it differently (a live object written as - // its drawn pieces) or not at all. + // again from the art above the type, which wraps it the same only where `wraps_held` says so. shape_ok - && t.wrap.is_empty() + && (t.wrap.is_empty() || wrap_held) && t.ruby.is_empty() && !t.stacks_warichu() && t.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) @@ -324,6 +324,112 @@ fn plain(n: &Node) -> bool { && n.extras().mask.is_none() } +/// The area type of `doc` whose wrap shapes the reader of the editing data works out again as they +/// are ([`vectorcraft_doc::text::resolve_wrap`], which the reader runs on what it reads): the +/// shapes are the ones the wrap objects above it give it now, and each of those objects is written +/// as itself and read back with the same outline and options ([`wrap_source_held`]), in layers +/// and groups written as they are ([`plain_containers`]). `styled`: the objects written with an +/// art style. Empty when the shapes of the document's area type would hold more anchors than the +/// reader copies into them ([`crate::import::MAX_WRAP_WORK`]). +pub(in crate::ai_editing) fn wraps_held(doc: &Document, styled: &HashMap<NodeId, Arc<Node>>) -> HashSet<NodeId> { + let mut held = HashSet::new(); + if vectorcraft_doc::text::wrap_work(doc) > crate::import::MAX_WRAP_WORK { + return held; + } + let mut plain_in = HashSet::new(); + for layer in &doc.layers { + plain_containers(layer, true, styled, &mut plain_in); + } + let mut checked: HashMap<NodeId, bool> = HashMap::new(); + vectorcraft_doc::text::wrap_sources(doc, |n, sources, shapes| { + let NodeKind::Text(t) = &n.kind else { return }; + if t.wrap.is_empty() || shapes != t.wrap || !plain_in.contains(&n.id) { + return; + } + let ok = sources.iter().all(|s| *checked.entry(s.id).or_insert_with(|| plain_in.contains(&s.id) && wrap_source_held(s, styled))); + if ok { + held.insert(n.id); + } + }); + held +} + +/// Adds to `out` the objects with text wrap options and the text objects in `n` (a top-level layer +/// when `top`) that sit only in layers and groups written as they are: layers and sublayers that +/// don't clip and have no effects, and groups that don't clip, have no fills, strokes, effects, +/// art style, opacity mask or graph and aren't written with an art style (`styled`). +fn plain_containers(n: &Node, top: bool, styled: &HashMap<NodeId, Arc<Node>>, out: &mut HashSet<NodeId>) { + let plain = match &n.kind { + NodeKind::Layer { clip, .. } => !clip && n.appearance.effects.is_empty(), + NodeKind::Group { clip, .. } => !top && !clip && n.appearance.items.is_empty() && own_plain(n, styled), + _ => false, + }; + if !plain { + return; + } + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + if c.extras().wrap.is_some() || matches!(c.kind, NodeKind::Text(_)) { + out.insert(c.id); + } + plain_containers(c, false, styled, out); + } +} + +/// Has object `n` no effects, art style, opacity mask or graph, and isn't it a ruler guide or +/// written with an art style (`styled`)? +fn own_plain(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + !styled.contains_key(&n.id) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty()) + && n.extras().graphic_style.is_none() + && n.extras().mask.is_none() + && n.extras().graph.is_none() + && !n.is_ruler_guide() +} + +/// Is wrap object `n` written as itself and read back with the same outline and text wrap options: +/// an offset the writer and the reader keep as it is (-1000 to 1000 pt) and a plain object +/// ([`plain_wrap_art`])? +fn wrap_source_held(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + n.extras().wrap.is_some_and(|w| w.offset.is_finite() && w.offset.abs() <= 1000.0) && plain_wrap_art(n, styled) +} + +/// Is `n` written as one object of its own kind that the reader reads back with the same outline +/// ([`vectorcraft_doc::text::resolve_wrap`]): a path of one subpath, a compound path of visible +/// paths with two subpaths or more in all, each painted with no paint, a solid fill, a plain line of a solid color or both, or a +/// group that doesn't clip of such paths, compound paths and groups (hidden ones too) without text +/// wrap options of their own; each without effects, art style, opacity mask or graph +/// ([`own_plain`]). Each subpath has two anchors or more. +fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); + let painted = || match super::visible_items(n).as_slice() { + [] => true, + [AppearanceItem::Fill(f)] => solid(&f.paint), + [AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + _ => false, + }; + let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2); + own_plain(n, styled) + && match &n.kind { + NodeKind::Path { path, clipping: false, guide: false, .. } => path.subpaths.len() == 1 && whole(path) && painted(), + // One subpath in all would be written, and read back, as a path. + NodeKind::Compound { children, .. } => { + let subpaths: usize = children.iter().filter_map(|c| c.path_data()).map(|p| p.subpaths.len()).sum(); + let members = children.iter().all(|c| { + c.visible + && matches!(&c.kind, NodeKind::Path { path, clipping: false, guide: false, .. } if !path.subpaths.is_empty() && whole(path)) + }); + painted() && subpaths > 1 && members + } + NodeKind::Group { children, clip: false } => { + n.appearance.items.is_empty() && children.iter().all(|c| c.extras().wrap.is_none() && plain_wrap_art(c, styled)) + } + _ => false, + } +} + /// Is the end bracket of type on an open path so near the path's end that the reader reads it as /// no bracket (`Story::node`: within 0.02 of a segment)? fn end_read_as_none(t: &TextObject) -> bool { @@ -1000,7 +1106,8 @@ impl TextDoc { /// `thread` (its frames in order, all area type the document holds, the first holding the /// story) the first time one of its frames is written. `None` when the thread can't be written /// as one story: `writable` says which frames are written where type can be text (every frame - /// of the thread must be). + /// of the thread must be), and `wraps_held` which frames with wrap shapes the reader wraps the + /// same ([`wraps_held`]; every frame with wrap shapes must be one). pub(in crate::ai_editing) fn thread( &mut self, doc: &Document, @@ -1008,6 +1115,7 @@ impl TextDoc { id: NodeId, canvas: Affine, writable: &dyn Fn(NodeId) -> bool, + wraps_held: &HashSet<NodeId>, ) -> Option<(usize, usize)> { let first = *thread.first()?; if self.planned.insert(first) { @@ -1026,7 +1134,7 @@ impl TextDoc { && t.vertical == vertical && writable(n.id) // The text document doesn't hold wrap shapes (see `holds`). - && t.wrap.is_empty() + && (t.wrap.is_empty() || wraps_held.contains(&n.id)) && plain(n) && t.ruby.is_empty() && !t.stacks_warichu() diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6f77c141ac..4e9fcc58ae 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -96,7 +96,7 @@ pub(crate) use ai::{ pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; -pub(crate) use native::{MAX_TEXT, scale_document, scale_symbols}; +pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; pub use text::family_style; pub(crate) use text::{document_font, postscript_face}; diff --git a/crates/eps/src/import/ai/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<Node>]) -> 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<Node>], 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<Node>) -> Vec<Arc<Node>> { } /// 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<Node>, inner: Vec<Node>) -> Option<NodeKind> { - 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<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> { + 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<Node>, inner: Vec<Node>) -> Option<NodeKind> { - envelope_as(o, before, inner, true) +fn live_on_saved_grid(o: &Obj, before: Option<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> { + envelope_as(o, before, inner, true, scale) } /// [`live`], or with `on_grid` [`live_on_saved_grid`]. -fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool) -> Option<NodeKind> { +fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool, scale: f64) -> Option<NodeKind> { 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<Node>, inner: Vec<Node>, 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<Node>, pub(super) inner: Vec<Node>, 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<NodeId>, waiting: usize, ) -> Result<(NodeId, Vec<Node>), 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<NodeKind> = live(&obj, before, inner).into_iter().chain(on_grid).collect(); + let kinds: Vec<NodeKind> = 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/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 830e3a48d0..9db1470093 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -885,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)); @@ -894,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; @@ -982,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/native.rs b/crates/eps/src/import/native.rs index 5acaba34a4..3a6347fea9 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -49,7 +49,7 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; -pub(crate) use build::{scale_document, scale_symbols}; +pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 09368870e8..bb970debe3 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -773,7 +773,7 @@ fn settle_warped_type( } /// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). -const MAX_WRAP_WORK: usize = 2_000_000; +pub(crate) const MAX_WRAP_WORK: usize = 2_000_000; /// [`relayout_wrapped`], or an error when the wrap shapes would hold more than [`MAX_WRAP_WORK`] /// anchors. diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index bd004d2d1e..e020dda9c3 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-doc = { workspace = true } vectorcraft-brush = { workspace = true } craft-vectorcraft-format = { workspace = true } +craft-gzip = { workspace = true } serde ={ workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9add0798c7..a8c7358aa7 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -57,12 +57,14 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; +use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; pub use craft_vectorcraft_format::{ BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, sniff, }; -use stream::{Gz, Indent, KeyScan, Out}; +use stream::Out; /// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs, /// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them, @@ -367,35 +369,44 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect(); let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false)); let mut out = if o.compress { Out::Gz(Box::new(Gz::new(w).map_err(encode_err)?)) } else { Out::Plain(w) }; - let mut env = Envelope { pretty, first: true }; - // Older apps only know the name from before the rename. - env.field(&mut out, "format", &if o.version < 3 { LEGACY_EXTENSION } else { EXTENSION })?; - env.field(&mut out, "version", &o.version)?; - env.field(&mut out, "generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?; - if let Some(compatible) = o.pdf_compatible { - env.field(&mut out, "pdfCompatible", &compatible)?; - } - if let Some(png) = &o.preview { - env.field(&mut out, "preview", &Image::inline("image/png", png))?; - } - if !profiles.is_empty() { - env.field(&mut out, "profiles", &profiles)?; - } - if let Some(pdf) = &pdf { - env.field(&mut out, "pdf", pdf)?; - } - env.key(&mut out, "document")?; - let mut scan = KeyScan::new(Indent { inner: &mut out, on: pretty }); - // Without blobs no key matters. - scan.active = images.is_none() && !blobs.is_empty(); - let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); - write_body(&mut buffered, v1.as_ref(), &d, pretty)?; - buffered.flush().map_err(encode_err)?; - drop(buffered); - let used = std::mem::take(&mut scan.keys); - let images = images.unwrap_or_else(|| entries.images(&used, &mut out_blobs)); - env.field(&mut out, "images", &images)?; - env.finish(&mut out)?; + let generator = format!("VectorCraft {}", env!("CARGO_PKG_VERSION")); + let preview = o.preview.as_deref().map(|png| Image::inline("image/png", png)); + let header = FileHeader { + version: o.version, + generator: &generator, + pdf_compatible: o.pdf_compatible, + preview: preview.as_ref(), + profiles: &profiles, + pdf: pdf.as_ref(), + }; + write_file_json(&mut out, &header, pretty, |document| { + let mut scan = KeyScan::new(document); + // Without blobs no key matters. + scan.active = images.is_none() && !blobs.is_empty(); + let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); + match v1.as_ref() { + Some(v) => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, v) + } else { + serde_json::to_writer(&mut buffered, v) + } + } + None => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, &d) + } else { + serde_json::to_writer(&mut buffered, &d) + } + } + } + .map_err(std::io::Error::other)?; + buffered.flush()?; + drop(buffered); + let used = std::mem::take(&mut scan.keys); + Ok(images.unwrap_or_else(|| entries.images(&used, &mut out_blobs))) + }) + .map_err(encode_err)?; if o.compress { let json = out.written().unwrap_or(0); let tail: Vec<u64> = out_blobs.parts().iter().map(|p| p.bytes.len() as u64).collect(); @@ -409,13 +420,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.len() >> 20, MAX_BLOBS >> 20))); } } - if !out_blobs.is_empty() { - out.write_all(BLOB_MAGIC).map_err(encode_err)?; - for part in out_blobs.parts() { - out.packed(is_packed(&part.mime)).map_err(encode_err)?; - out.write_all(part.bytes).map_err(encode_err)?; - } - } + out_blobs.write_to_with(&mut out, |out, mime| out.packed(is_packed(mime))).map_err(encode_err)?; out.finish().map_err(encode_err) } @@ -450,10 +455,6 @@ fn encode_err(e: impl std::fmt::Display) -> FormatError { FormatError::Encode(e.to_string()) } -fn to_json(v: &impl Serialize, pretty: bool) -> Result<Vec<u8>, FormatError> { - if pretty { serde_json::to_vec_pretty(v) } else { serde_json::to_vec(v) }.map_err(encode_err) -} - /// The document's JSON: its version 1 form `v1`, else `d` (generic, not `dyn Write`: serde_json /// writes token by token). fn write_body(w: impl Write, v1: Option<&serde_json::Value>, d: &Document, pretty: bool) -> Result<(), FormatError> { @@ -467,33 +468,6 @@ fn write_json(w: impl Write, v: &impl Serialize, pretty: bool) -> Result<(), For if pretty { serde_json::to_writer_pretty(w, v) } else { serde_json::to_writer(w, v) }.map_err(encode_err) } -/// The file's top-level object, written member by member (the document is streamed in). -struct Envelope { - pretty: bool, - first: bool, -} - -impl Envelope { - fn field(&mut self, out: &mut impl Write, key: &str, value: &impl Serialize) -> Result<(), FormatError> { - let json = to_json(value, self.pretty)?; - self.key(out, key)?; - Indent { inner: out, on: self.pretty }.write_all(&json).map_err(encode_err) - } - - /// The start of member `key` (a plain name): its value follows, indented one level when - /// pretty (as serde_json would: see [`Indent`]). - fn key(&mut self, out: &mut impl Write, key: &str) -> Result<(), FormatError> { - let sep: &[u8] = if std::mem::take(&mut self.first) { b"{" } else { b"," }; - let indent: &[u8] = if self.pretty { b"\n " } else { b"" }; - let colon: &[u8] = if self.pretty { b"\": " } else { b"\":" }; - [sep, indent, b"\"", key.as_bytes(), colon].iter().try_for_each(|part| out.write_all(part)).map_err(encode_err) - } - - fn finish(self, out: &mut impl Write) -> Result<(), FormatError> { - out.write_all(if self.pretty { b"\n}" } else { b"}" }).map_err(encode_err) - } -} - pub fn load(bytes: &[u8]) -> Result<Document, FormatError> { load_info(bytes).map(|(doc, _)| doc) } diff --git a/crates/format/src/stream.rs b/crates/format/src/stream.rs index bed508601f..bc24a67aed 100644 --- a/crates/format/src/stream.rs +++ b/crates/format/src/stream.rs @@ -2,10 +2,9 @@ //! not) and the data after it is copied in from the document's own buffers, so a save holds no //! copy of the file in memory besides what the caller's writer keeps. -use std::collections::HashSet; use std::io::{self, Write}; -use flate2::{Compress, Compression, Crc, FlushCompress, Status}; +use craft_gzip::Gz; /// The output of a save: plain, or gzip ([`Gz`]). pub(crate) enum Out<W: Write> { @@ -26,7 +25,7 @@ impl<W: Write> Out<W> { pub(crate) fn written(&self) -> Option<u64> { match self { Out::Plain(_) => None, - Out::Gz(gz) => Some(gz.total), + Out::Gz(gz) => Some(gz.written()), } } @@ -61,299 +60,3 @@ impl<W: Write> Write for Out<W> { } } } - -/// Bytes of compressed output gathered before they go to the writer. -const OUT_CHUNK: usize = 64 << 10; - -/// A gzip stream, written as [`flate2::write::GzEncoder`] at the default level writes it (the -/// same header and the same data; the deflate blocks are the same too where flate2 deflates with -/// miniz_oxide, not with zlib-rs, which writes them by how the data is fed), except that data which -/// is compressed already ([`Gz::packed`]) is stored as it is: the default level spends a second -/// or more per photo on it for next to nothing, and makes it slower to unpack. Where the level -/// changes the deflate blocks so far end with a sync flush and a fresh compressor writes on, -/// which makes one valid deflate stream that every reader unpacks. -pub(crate) struct Gz<W: Write> { - out: W, - deflate: Compress, - /// What `deflate` writes: stored blocks (packed data), else the default level. - stored: bool, - crc: Crc, - buf: Vec<u8>, - /// Bytes written (unpacked). - total: u64, -} - -impl<W: Write> Gz<W> { - pub(crate) fn new(mut out: W) -> io::Result<Self> { - // flate2's header for the default level: no name, no time, unknown OS. - out.write_all(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255])?; - Ok(Self { - out, - deflate: Compress::new(Compression::default(), false), - stored: false, - crc: Crc::new(), - buf: Vec::with_capacity(OUT_CHUNK), - total: 0, - }) - } - - /// Run the compressor over `input` with `flush` until it has taken it all (and, flushing, - /// written everything out). - fn deflate(&mut self, mut input: &[u8], flush: FlushCompress) -> io::Result<()> { - loop { - if self.buf.len() == self.buf.capacity() { - self.out.write_all(&self.buf)?; - self.buf.clear(); - } - let (before_in, before_out) = (self.deflate.total_in(), self.deflate.total_out()); - let status = self.deflate.compress_vec(input, &mut self.buf, flush).map_err(io::Error::other)?; - let taken = usize::try_from(self.deflate.total_in() - before_in).unwrap_or(input.len()).min(input.len()); - input = input.get(taken..).unwrap_or_default(); - let made = self.deflate.total_out() - before_out; - let full = self.buf.len() == self.buf.capacity(); - match flush { - FlushCompress::None if input.is_empty() => return Ok(()), - FlushCompress::Finish if status == Status::StreamEnd => return Ok(()), - // A flush is done once it left room in the output. - FlushCompress::Sync if input.is_empty() && !full => return Ok(()), - _ => {} - } - if taken == 0 && made == 0 && !full { - return Err(io::Error::other("the compressor made no progress")); - } - } - } - - /// What is written next is compressed already (stored as it is), or not (compressed at the - /// default level). - fn packed(&mut self, packed: bool) -> io::Result<()> { - if packed == self.stored { - return Ok(()); - } - self.deflate(&[], FlushCompress::Sync)?; - self.deflate = Compress::new(if packed { Compression::none() } else { Compression::default() }, false); - self.stored = packed; - Ok(()) - } - - fn finish(mut self) -> io::Result<()> { - self.deflate(&[], FlushCompress::Finish)?; - self.out.write_all(&self.buf)?; - self.out.write_all(&self.crc.sum().to_le_bytes())?; - self.out.write_all(&self.crc.amount().to_le_bytes())?; - self.out.flush() - } -} - -impl<W: Write> Write for Gz<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.crc.update(buf); - self.total += buf.len() as u64; - self.deflate(buf, FlushCompress::None) - } - - fn flush(&mut self) -> io::Result<()> { - // Flushing would end a deflate block: the stream is flushed when it is finished. - Ok(()) - } -} - -/// Indents JSON text written through it one level (two spaces after each newline), as a member -/// of the file's top-level object; newlines only occur between tokens, inside strings they are -/// escaped. -pub(crate) struct Indent<W: Write> { - pub(crate) inner: W, - pub(crate) on: bool, -} - -impl<W: Write> Write for Indent<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - if !self.on { - return self.inner.write_all(buf); - } - let mut lines = buf.split(|&b| b == b'\n'); - self.inner.write_all(lines.next().unwrap_or_default())?; - for line in lines { - self.inner.write_all(b"\n ")?; - self.inner.write_all(line)?; - } - Ok(()) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -/// The member that names an image. -const TAG: &[u8] = b"\"key\":"; - -/// Passes JSON text through, collecting the string values of every `"key": "…"` member at any -/// depth (what the images a document uses are named by). Quotes inside JSON strings are escaped, -/// so every match is a real member. -pub(crate) struct KeyScan<W: Write> { - pub(crate) inner: W, - pub(crate) keys: HashSet<String>, - /// Looking for keys (else it only passes the text on). - pub(crate) active: bool, - /// How much of [`TAG`] the last bytes matched. - matched: usize, - /// Right after a tag: skipping whitespace to its value. - after_tag: bool, - /// The value string so far, quotes included. - value: Option<Vec<u8>>, - escaped: bool, -} - -impl<W: Write> KeyScan<W> { - pub(crate) fn new(inner: W) -> Self { - Self { inner, keys: HashSet::new(), active: true, matched: 0, after_tag: false, value: None, escaped: false } - } - - fn scan(&mut self, buf: &[u8]) { - if !self.active { - return; - } - let mut i = 0; - while let Some(&b) = buf.get(i) { - // Nothing in progress: skip to the next quote. - if self.matched == 0 && !self.after_tag && self.value.is_none() { - match buf.get(i..).and_then(|r| r.iter().position(|&c| c == b'"')) { - Some(at) => i += at, - None => return, - } - self.matched = 1; - i += 1; - continue; - } - self.step(b); - i += 1; - } - } - - fn step(&mut self, b: u8) { - if let Some(v) = self.value.as_mut() { - v.push(b); - if self.escaped { - self.escaped = false; - } else if b == b'\\' { - self.escaped = true; - } else if b == b'"' - && let Some(v) = self.value.take() - && let Ok(s) = serde_json::from_slice::<String>(&v) - { - self.keys.insert(s); - } - } else if self.after_tag && !b.is_ascii_whitespace() { - self.after_tag = false; - if b == b'"' { - self.value = Some(vec![b]); - } - } - if TAG.get(self.matched) == Some(&b) { - self.matched += 1; - if self.matched == TAG.len() { - self.matched = 0; - self.after_tag = true; - self.value = None; - self.escaped = false; - } - } else { - self.matched = usize::from(b == b'"'); - } - } -} - -impl<W: Write> Write for KeyScan<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.scan(buf); - self.inner.write_all(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -#[cfg(test)] -mod tests { - use proptest::prelude::*; - - use super::*; - - /// How the keys were found before saves were streamed: in the whole JSON text at once. - fn string_members(json: &[u8]) -> HashSet<String> { - let mut out = HashSet::new(); - let mut rest = json; - while let Some(at) = rest.windows(TAG.len()).position(|w| w == TAG) { - rest = rest.get(at + TAG.len()..).unwrap_or_default(); - let value = rest.trim_ascii_start(); - if value.first() == Some(&b'"') - && let Some(Ok(s)) = serde_json::Deserializer::from_slice(value).into_iter::<String>().next() - { - out.insert(s); - } - } - out - } - - /// The keys `KeyScan` finds in `json` written in pieces of `chunk` bytes. - fn scanned(json: &[u8], chunk: usize) -> HashSet<String> { - let mut scan = KeyScan::new(Vec::new()); - for piece in json.chunks(chunk.max(1)) { - scan.write_all(piece).unwrap(); - } - assert_eq!(scan.inner, json, "the text passes through"); - scan.keys - } - - #[test] - fn finds_the_keys_the_whole_text_search_found() { - let v = serde_json::json!({"key": "a", "x": [{"key": "b \"q\" \\ é"}, {"monkey": "no"}, {"k": "key"}], "s": "\"key\": \"no\"", "key2": "n", "o": {"key": 3}}); - for json in [serde_json::to_vec(&v).unwrap(), serde_json::to_vec_pretty(&v).unwrap()] { - let want = string_members(&json); - assert_eq!(want, HashSet::from(["a".to_string(), "b \"q\" \\ é".to_string()])); - for chunk in [1, 2, 3, 7, 64, json.len()] { - assert_eq!(scanned(&json, chunk), want, "chunk {chunk}"); - } - } - } - - fn arb_json() -> impl Strategy<Value = serde_json::Value> { - let key = prop::sample::select(vec!["key", "k", "kkey", "key ", "x"]).prop_map(str::to_string); - let leaf = prop_oneof![ - Just(serde_json::Value::Null), - any::<i32>().prop_map(serde_json::Value::from), - "[a-z\"\\\\: ké\n]{0,8}".prop_map(serde_json::Value::from), - ]; - leaf.prop_recursive(4, 32, 6, move |inner| { - prop_oneof![ - prop::collection::vec(inner.clone(), 0..5).prop_map(serde_json::Value::from), - prop::collection::vec((key.clone(), inner), 0..5).prop_map(|m| serde_json::Value::Object(m.into_iter().collect())), - ] - }) - } - - proptest! { - #[test] - fn scanning_in_pieces_finds_what_the_whole_text_search_found(v in arb_json(), chunk in 1usize..40, pretty in any::<bool>()) { - let json = if pretty { serde_json::to_vec_pretty(&v) } else { serde_json::to_vec(&v) }.unwrap(); - prop_assert_eq!(scanned(&json, chunk), string_members(&json)); - } - } -} diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 0ae8a75190..5bebc07384 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,6 +103,38 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// Ellipse inscribed in `r` with `n` smooth anchors (at least 2) spaced evenly by angle, clockwise +/// on screen from the left one, as [`ellipse`] runs. Each segment is a cubic whose handles are +/// 4/3·tan(θ/4) of the tangent at its ends (θ = 360°/`n`), scaled along each axis; the path is then +/// fitted to `r`, so its bounds are `r` whatever the count. 4 anchors give [`ellipse`]. +pub fn ellipse_with_anchors(r: Rect, n: u32) -> PathData { + let n = n.max(2); + let r = r.abs(); + let c = r.center(); + let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); + let step = TAU / f64::from(n); + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let anchors = (0..n) + .map(|i| { + // From the left anchor (angle π). With y down, sin is negative just past π, so the next + // anchor is above the centre: left, then top, then right, as `ellipse` runs. + let a = PI + step * f64::from(i); + let p = Point::new(c.x + rx * a.cos(), c.y + ry * a.sin()); + let d = Vec2::new(-rx * a.sin(), ry * a.cos()) * k; + Anchor { p, h_in: p - d, h_out: p + d, kind: AnchorKind::Smooth } + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + // Between anchors a curve can reach a little past the ellipse or stop short of it (0.15% of + // the height with 3 anchors): fit the bounds to `r` along each axis that has a size. + let Some(b) = path.bounds() else { return path }; + let fit = |want: f64, got: f64| if want > 0.0 && got > 0.0 { want / got } else { 1.0 }; + let (sx, sy) = (fit(r.width(), b.width()), fit(r.height(), b.height())); + path.transformed( + kurbo::Affine::translate(r.origin().to_vec2()) * kurbo::Affine::scale_non_uniform(sx, sy) * kurbo::Affine::translate(-b.origin().to_vec2()), + ) +} + /// How an ellipse or shape arc is closed or left open when cut between start and end angles. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -693,6 +725,29 @@ mod tests { assert!((area - PI * 50.0 * 30.0).abs() / area < 0.001); } + #[test] + fn ellipse_with_four_anchors_is_the_ellipse_and_others_fit_the_box() { + let r = Rect::new(10.0, 20.0, 110.0, 80.0); + let (four, plain) = (ellipse_with_anchors(r, 4), ellipse(r)); + for (a, b) in four.subpaths[0].anchors.iter().zip(&plain.subpaths[0].anchors) { + assert!(a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}"); + } + for n in [2, 3, 5, 7, 9, 1000] { + let p = ellipse_with_anchors(r, n); + assert_eq!(p.anchor_count(), n as usize); + let b = p.bounds().unwrap(); + assert!( + (b.x0 - r.x0).abs() < 1e-9 && (b.y0 - r.y0).abs() < 1e-9 && (b.x1 - r.x1).abs() < 1e-9 && (b.y1 - r.y1).abs() < 1e-9, + "{n}: {b:?}" + ); + let area = p.subpaths[0].area().abs(); + assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + } + // A box with no height leaves the path flat rather than dividing by zero. + let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); + assert!(flat.subpaths[0].anchors.iter().all(|a| a.p.y == 5.0 && a.p.x.is_finite())); + } + #[test] fn rounded_rect_clamps() { let p = rounded_rectangle(Rect::new(0.0, 0.0, 20.0, 10.0), 100.0); 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/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 4b55d6aff1..e549c2a362 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -244,7 +244,7 @@ pub fn tool_definitions() -> Vec<Value> { tool( "draw_shape", "Draw shape", - "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", + "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius; ellipse: anchors, default 4, where any other count from 2 to 1000 draws a plain path rather than a live shape). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", obj( with_draw_options(json!({ "shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]}, @@ -253,6 +253,7 @@ pub fn tool_definitions() -> Vec<Value> { "width": num("Width (rectangle/ellipse)"), "height": num("Height (rectangle/ellipse)"), "radius": num("Corner radius (rectangle) or radius (polygon)"), + "anchors": {"type": "integer", "minimum": 2, "maximum": 1000, "description": "Ellipse anchors, spaced evenly by angle (default 4, a live ellipse; any other count draws a plain path)"}, "cx": num("Centre x (polygon/star)"), "cy": num("Centre y (polygon/star)"), "sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"}, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8e651622af..3066e8e835 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -188,7 +188,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( @@ -656,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", 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 32878eb2bc..f280f02ee5 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -1,4 +1,4 @@ -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}; @@ -126,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<Image> { let key = im.key.as_str(); let c = self.compression; @@ -142,6 +144,7 @@ impl Exporter<'_> { let out = self.out.clone(); 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 { @@ -153,6 +156,12 @@ impl Exporter<'_> { } 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()) { @@ -160,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()); diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 1cb0a45273..36a4f0ed8e 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -2,10 +2,13 @@ //! dictionary (ISO 32000-1 §14.3.3) and the XMP packet of the catalog's metadata stream (§14.3.2, //! ISO 16684-1). Where both give a field, the XMP packet's value is taken; a packet that can't be //! read leaves the information dictionary's values. +//! +//! File › File Info's metadata templates are XMP packets of the same properties: [`metadata_template`] +//! writes one and [`read_template`] reads one back. 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,11 +18,18 @@ 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 PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use + +/// The longest metadata template [`read_template`] reads, in bytes. +pub const MAX_TEMPLATE_BYTES: usize = MAX_XMP; + +const XMP_NAMESPACES: Canonical<'static> = + Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]); // brand-ok: the XMP namespace prefix the files use /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -28,10 +38,15 @@ pub struct FileInfo { pub title: Option<String>, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option<String>, + /// XMP `photoshop:AuthorsPosition`. + pub author_title: Option<String>, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. pub description: Option<String>, /// XMP `dc:subject`, else XMP `pdf:Keywords` or Info `Keywords` split at commas and semicolons. pub keywords: Option<Vec<String>>, + /// XMP `xmp:Rating`, a whole number from 0 to 5 (a rejected file's -1 and other values are + /// left out). + pub rating: Option<u8>, /// XMP `dc:rights` (its `x-default` item, else its first). pub copyright_notice: Option<String>, /// XMP `xmpRights:WebStatement`. @@ -73,42 +88,115 @@ fn packet(pdf: &Pdf) -> Option<Vec<u8>> { } /// 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<FileInfo> { + read_xmp(packet, false) +} + +/// The File Info fields of the metadata template `bytes`, an XMP packet as [`metadata_template`] +/// writes one (or any XMP file); `None` when it is longer than [`MAX_TEMPLATE_BYTES`], isn't XML in +/// UTF-8 or UTF-16, has no `rdf:RDF` element, or nests more than [`MAX_NESTING`] deep. +pub fn read_template(bytes: &[u8]) -> Option<FileInfo> { + if bytes.len() > MAX_TEMPLATE_BYTES { + return None; + } + read_xmp(bytes, true) +} + +/// [`xmp`]; with `need_rdf`, `None` for XML that has no `rdf:RDF` element. +fn read_xmp(packet: &[u8], need_rdf: bool) -> Option<FileInfo> { let text = xml_text(packet)?; - // roxmltree parses nested elements recursively. - if nesting(&text) > MAX_NESTING { + let opts = Options { + names: Names::Canonical(&XMP_NAMESPACES), + doctype: Doctype::Reject, + limits: Limits { max_depth: MAX_NESTING, ..Limits::DEFAULT }, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).ok()?; + let rdfs: Vec<&El> = std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).collect(); + if need_rdf && rdfs.is_empty() { return None; } - let xml = roxmltree::Document::parse(&text).ok()?; // The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value. - let descriptions: Vec<Node<'_, '_>> = 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> = rdfs.iter().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() { + author_title: first("photoshop:AuthorsPosition"), // brand-ok: the XMP property name the files use + description: first("dc:description"), + keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, + rating: first("xmp:Rating").and_then(|r| rating(&r)), + 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)), }) } +/// An `xmp:Rating` value as File Info takes one: a whole number from 0 to 5, written as an integer +/// or as a real with no fraction (`3`, `3.0`). The rejected rating -1, fractions and other values +/// give `None`. +fn rating(s: &str) -> Option<u8> { + let r: f64 = s.trim().parse().ok()?; + (r.fract() == 0.0 && (0.0..=5.0).contains(&r)).then_some(r as u8) +} + +/// The metadata template of `f`: an XMP packet (ISO 16684-1) holding its title (`dc:title`), author +/// (`dc:creator`), author title (`photoshop:AuthorsPosition`), description (`dc:description`), +/// keywords (`dc:subject`), rating (`xmp:Rating`), copyright status (`xmpRights:Marked`), notice +/// (`dc:rights`) and URL (`xmpRights:WebStatement`), each where `f` gives it, which +/// [`read_template`] reads back. The dates are left out. +pub fn metadata_template(f: &FileInfo) -> String { + use crate::post::xml_text as esc; + let alt = |name: &str, v: &str| format!(" <{name}><rdf:Alt><rdf:li xml:lang=\"x-default\">{}</rdf:li></rdf:Alt></{name}>\n", esc(v)); + let simple = |name: &str, v: &str| format!(" <{name}>{}</{name}>\n", esc(v)); + let blank = |v: &Option<String>| v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); + let mut props = String::new(); + if let Some(v) = blank(&f.title) { + props.push_str(&alt("dc:title", &v)); + } + if let Some(v) = blank(&f.author) { + props.push_str(&format!(" <dc:creator><rdf:Seq><rdf:li>{}</rdf:li></rdf:Seq></dc:creator>\n", esc(&v))); + } + if let Some(v) = blank(&f.author_title) { + props.push_str(&simple("photoshop:AuthorsPosition", &v)); // brand-ok: the XMP property name the files use + } + if let Some(v) = blank(&f.description) { + props.push_str(&alt("dc:description", &v)); + } + let keywords: Vec<&str> = f.keywords.iter().flatten().map(|k| k.trim()).filter(|k| !k.is_empty()).collect(); + if !keywords.is_empty() { + let items: String = keywords.iter().map(|k| format!("<rdf:li>{}</rdf:li>", esc(k))).collect(); + props.push_str(&format!(" <dc:subject><rdf:Bag>{items}</rdf:Bag></dc:subject>\n")); + } + if let Some(r) = f.rating { + props.push_str(&simple("xmp:Rating", &r.to_string())); + } + if let Some(c) = f.copyrighted { + props.push_str(&simple("xmpRights:Marked", if c { "True" } else { "False" })); + } + if let Some(v) = blank(&f.copyright_notice) { + props.push_str(&alt("dc:rights", &v)); + } + if let Some(v) = blank(&f.copyright_url) { + props.push_str(&simple("xmpRights:WebStatement", &v)); + } + format!( + "<?xpacket begin=\"\u{FEFF}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"{X}\">\n <rdf:RDF xmlns:rdf=\"{RDF}\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"{DC}\" xmlns:xmp=\"{XMP}\" xmlns:xmpRights=\"{XMP_RIGHTS}\" xmlns:photoshop=\"{PHOTOSHOP}\">\n{props} </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>\n" // brand-ok: the XMP namespace prefix the files use + ) +} + /// A packet's text: UTF-8 (with or without a byte order mark), or UTF-16 told by its byte order /// mark or by a zero byte beside the `<` it starts with. fn xml_text(b: &[u8]) -> Option<String> { @@ -123,58 +211,14 @@ fn xml_text(b: &[u8]) -> Option<String> { } } -/// 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"<!--") { - i = past(start + 4, b"-->"); - } else if rest.starts_with(b"<![CDATA[") { - i = past(start + 9, b"]]>"); - } else if rest.starts_with(b"<?") { - i = past(start + 2, b"?>"); - } else if rest.starts_with(b"<!") || rest.starts_with(b"</") { - depth = depth.saturating_sub(usize::from(rest.starts_with(b"</"))); - i = past(start + 2, 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<String> { +fn property(descriptions: &[&El], name: &str) -> Vec<String> { 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 +229,10 @@ fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String> /// 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<String> { - let array = p.children().find(|c| ["Seq", "Bag", "Alt"].into_iter().any(|t| c.has_tag_name((RDF, t)))); +fn items(p: &El) -> Vec<String> { + 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 +243,19 @@ fn items(p: Node<'_, '_>) -> Vec<String> { /// 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 0b7024e731..872080bfb5 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -320,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 @@ -521,7 +524,10 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// 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), @@ -531,7 +537,7 @@ pub(crate) fn recode( profiles: SourceProfiles, to_srgb: Option<ToSrgb>, ) -> 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 }; @@ -549,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) @@ -573,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), @@ -585,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)) => { @@ -604,18 +617,19 @@ pub(crate) fn recode( && 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 }; + 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 @@ -650,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 @@ -681,6 +696,7 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c /// [`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 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), @@ -704,16 +720,22 @@ pub(crate) fn recode_cmyk( let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS) .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), @@ -722,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. @@ -767,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<DynamicImage> { - 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<DynamicImage, bool> { + 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/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<Item = &'p craft_pdf::syntax::page::Page<'d>>) -> [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..9cef615783 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,7 +76,7 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; pub use export::{check_page_sizes, export, export_with_report, page_areas}; -pub use file_info::{FileInfo, file_info}; +pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; pub use import::{ @@ -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<usize>, - /// 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<Vec<usize>>, diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index c6fdd8048d..79e872e59b 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -180,7 +180,7 @@ fn rights_properties(info: &DocMetadata) -> String { /// `s` as XML character data: `&`, `<`, `>` and `"` escaped, a carriage return written as the /// character reference ` `, and the characters XML 1.0 doesn't allow left out. -fn xml_text(s: &str) -> String { +pub(crate) fn xml_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index c9746d0fc4..57ccef1c6d 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -622,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<Option<Vec<u8>>> { diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 26c6826723..90cc66bc5f 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -270,6 +270,54 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { 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<u8>| { + 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<u8> { diff --git a/crates/pdf/src/tests/file_info.rs b/crates/pdf/src/tests/file_info.rs index 4c837ba67f..57bbdcd58c 100644 --- a/crates/pdf/src/tests/file_info.rs +++ b/crates/pdf/src/tests/file_info.rs @@ -94,8 +94,10 @@ fn the_xmp_packet_gives_file_info() { FileInfo { title: Some("Poster".into()), author: Some("Ada Lovelace, Charles Babbage".into()), + author_title: None, description: Some("A poster\nfor the fair".into()), keywords: Some(vec!["fair".into(), "print".into()]), + rating: None, copyright_notice: Some("(c) 2026 Ada".into()), copyright_url: Some("https://example.com/rights".into()), copyrighted: Some(false), @@ -270,3 +272,48 @@ fn a_written_pdf_gives_its_copyright_back() { let f = file_info(&export(&d, &PdfOptions::uncompressed()).unwrap(), None).unwrap(); assert_eq!((f.author.as_deref(), f.copyright_notice.as_deref()), (Some("Ada"), Some("(c) Ada"))); } + +#[test] +fn a_metadata_template_gives_its_file_info_back() { + let f = FileInfo { + title: Some("Fair poster".into()), + author: Some("Ada & <Lovelace>".into()), + author_title: Some("Designer, \"lead\"".into()), + description: Some("A poster\r\nfor the fair".into()), + keywords: Some(vec!["fair".into(), "print, large".into()]), + rating: Some(4), + copyright_notice: Some("(c) 2026 Ada".into()), + copyright_url: Some("https://example.com/rights?a=1&b=2".into()), + copyrighted: Some(true), + ..Default::default() + }; + let xmp = metadata_template(&f); + assert!(xmp.starts_with("<?xpacket begin=") && xmp.trim_end().ends_with("<?xpacket end=\"w\"?>"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(f)); + // A public-domain status writes Marked False; fields without a value and the dates are left out. + let f = FileInfo { copyrighted: Some(false), author: Some(" ".into()), created: Some(CREATED), ..Default::default() }; + let xmp = metadata_template(&f); + assert!(!xmp.contains("dc:creator") && !xmp.contains("CreateDate") && xmp.contains("<xmpRights:Marked>False</xmpRights:Marked>"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(FileInfo { copyrighted: Some(false), ..Default::default() })); + // The template is the PDF packet's format: a PDF whose metadata stream holds one reads the same. + let f = FileInfo { author: Some("Ada".into()), author_title: Some("Editor".into()), rating: Some(2), ..Default::default() }; + let read = file_info(&pdf(None, Some(&metadata_template(&f))), None).unwrap(); + assert_eq!((read.author, read.author_title, read.rating), (f.author, f.author_title, f.rating)); +} + +#[test] +fn a_metadata_template_reads_ratings_and_refuses_what_is_not_xmp() { + let rated = |r: &str| read_template(packet(&description(&format!("xmp:Rating=\"{r}\""), "")).as_bytes()).unwrap().rating; + assert_eq!([rated("0"), rated("5"), rated("3.0"), rated(" 2 ")], [Some(0), Some(5), Some(3), Some(2)]); + // A rejected file's -1, fractions, ratings past 5 and words are left out. + assert_eq!([rated("-1"), rated("2.5"), rated("6"), rated("high")], [None; 4]); + // XML without `rdf:RDF`, text and a packet that isn't well-formed are not templates. + assert_eq!(read_template(b"<root><title>Poster"), None); + assert_eq!(read_template(b"Ada Lovelace"), None); + assert_eq!(read_template(packet("").as_bytes()), None); + // An XMP packet with no File Info is a template with no fields. + assert_eq!(read_template(packet("").as_bytes()), Some(FileInfo::default())); + // Longer than the longest template read, it is refused without being parsed. + let long = packet(&description("", &" ".repeat(MAX_TEMPLATE_BYTES))); + assert_eq!(read_template(long.as_bytes()), None); +} 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/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/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/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 7e67f09cf7..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; 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/importer.rs b/crates/svg/src/import/importer.rs index 5c62eb10b3..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 { @@ -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_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/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/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..b45564c887 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -54,7 +54,7 @@ pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins}; pub(crate) use glyph_pen::FlipPen; -pub use gsub::{GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a245efeea2..a88d4ed86a 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -94,6 +94,211 @@ pub(super) struct GsubIndex { /// The first feature, listed ones first, that gives each glyph: by a single, multiple, /// alternate or ligature substitution, and the glyph it replaces (not known for a ligature). reached: HashMap)>, + /// The face's glyph categories ([`FontFace::glyph_categories`]), read the first time they are + /// asked for. + categories: std::sync::OnceLock>, +} + +/// A kind of glyph that the Glyphs panel's Show menu lists by OpenType feature +/// ([`FontFace::glyph_categories`]). The kinds, the features in each and their order are +/// VectorCraft's own. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum GlyphCategoryKind { + /// `liga`, `dlig` and `hlig`. + Ligatures, + /// `swsh` and `cswh`. + Swashes, + /// `salt`. + StylisticAlternates, + /// One of `ss01` to `ss20`, by its number. + StylisticSet(u8), + /// `smcp` and `c2sc`. + SmallCaps, + /// `ornm`. + Ornaments, + /// `frac`, `afrc`, `numr` and `dnom`. + Fractions, + /// `lnum`, `onum`, `pnum` and `tnum`. + Figures, +} + +impl GlyphCategoryKind { + /// Every kind in the order the Show menu lists them, the stylistic sets by number. + pub fn all() -> Vec { + let sets = (1..=20).map(Self::StylisticSet); + [Self::Ligatures, Self::Swashes, Self::StylisticAlternates] + .into_iter() + .chain(sets) + .chain([Self::SmallCaps, Self::Ornaments, Self::Fractions, Self::Figures]) + .collect() + } + + /// The `GSUB` features whose substitutions give the kind's glyphs. + pub fn features(self) -> Vec<[u8; 4]> { + match self { + Self::Ligatures => vec![*b"liga", *b"dlig", *b"hlig"], + Self::Swashes => vec![*b"swsh", *b"cswh"], + Self::StylisticAlternates => vec![*b"salt"], + Self::StylisticSet(n) => { + let [a, b] = [b'0' + n / 10 % 10, b'0' + n % 10]; + vec![[b's', b's', a, b]] + } + Self::SmallCaps => vec![*b"smcp", *b"c2sc"], + Self::Ornaments => vec![*b"ornm"], + Self::Fractions => vec![*b"frac", *b"afrc", *b"numr", *b"dnom"], + Self::Figures => vec![*b"lnum", *b"onum", *b"pnum", *b"tnum"], + } + } + + /// The kind's id: `ligatures`, `swashes`, `stylisticAlternates`, `ss01` to `ss20`, `smallCaps`, + /// `ornaments`, `fractions` or `figures`. + pub fn id(self) -> String { + match self { + Self::Ligatures => "ligatures".into(), + Self::Swashes => "swashes".into(), + Self::StylisticAlternates => "stylisticAlternates".into(), + Self::StylisticSet(n) => format!("ss{n:02}"), + Self::SmallCaps => "smallCaps".into(), + Self::Ornaments => "ornaments".into(), + Self::Fractions => "fractions".into(), + Self::Figures => "figures".into(), + } + } + + /// The kind whose [`Self::id`] is `id`. + pub fn from_id(id: &str) -> Option { + Self::all().into_iter().find(|k| k.id() == id) + } +} + +/// The glyphs of one [`GlyphCategoryKind`] that a face has ([`FontFace::glyph_categories`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GlyphCategory { + pub kind: GlyphCategoryKind, + /// A stylistic set's name from the font's `name` table, when the font gives one. + pub name: Option, + /// The glyphs the kind's features give, each once, by glyph id. + pub glyphs: Vec, +} + +/// Read `face`'s glyph categories ([`FontFace::glyph_categories`]). The caps of [`GsubIndex::read`] +/// bound what a damaged table makes it read, and all the lookups together give at most +/// `MAX_ENTRIES` glyphs. +fn read_categories(face: &FontFace) -> Vec { + let Some(font) = face.skrifa() else { return vec![] }; + let Ok(gsub) = font.gsub() else { return vec![] }; + let (Ok(features), Ok(lookups)) = (gsub.feature_list(), gsub.lookup_list()) else { return vec![] }; + let glyphs = font.maxp().map_or(0, |m| u32::from(m.num_glyphs())); + let kinds = GlyphCategoryKind::all(); + // The lookups of each kind's features, in every script's feature records. + let mut wanted: Vec> = vec![vec![]; kinds.len()]; + let mut total = 0_usize; + for record in features.feature_records().iter().take(MAX_FEATURES) { + let tag = record.feature_tag().to_be_bytes(); + let Some(k) = kinds.iter().position(|kind| kind.features().contains(&tag)) else { continue }; + let Ok(feature) = record.feature(features.offset_data()) else { continue }; + for i in feature.lookup_list_indices().iter().take(MAX_FEATURE_LOOKUPS) { + if total >= MAX_LOOKUPS { + break; + } + if !wanted[k].contains(&i.get()) { + wanted[k].push(i.get()); + total += 1; + } + } + } + let all = lookups.lookups(); + let mut reads = MAX_SUBTABLE_READS; + // What each lookup gives, read once when several kinds share it. + let mut read: HashMap> = HashMap::new(); + // The glyphs all the lookups read together may give: at most `MAX_ENTRIES`. + let mut left = MAX_ENTRIES; + let mut outputs = |lookup: u16, reads: &mut usize| -> Vec { + if let Some(out) = read.get(&lookup) { + return out.clone(); + } + // A lookup not read yet once the read budget is spent gives nothing, and is not cached. + if *reads == 0 || left == 0 { + return vec![]; + } + // Each subtable adds only what still fits in what is left of the glyph budget. + let cap = left; + let mut out: Vec = vec![]; + // The glyphs an earlier subtable of the lookup covers: OpenType applies the first subtable + // that covers a glyph, so a later one's substitution of it is never made. + let mut covered: std::collections::HashSet = std::collections::HashSet::new(); + let mut first = |from: u32| covered.insert(from); + if let Ok(subtables) = all.get(usize::from(lookup)).and_then(|l| l.subtables()) { + let n = MAX_SUBTABLES.min(*reads); + let room = |out: &Vec| cap.saturating_sub(out.len()); + match subtables { + SubstitutionSubtables::Single(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(single_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Alternate(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(alternate_sets(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, set)| set).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Multiple(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(multiple_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Ligature(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(ligature_glyphs(&t, r).into_iter().take(r)); + if room(&out) == 0 { + break; + } + } + } + _ => {} + } + } + left = left.saturating_sub(out.len()); + read.insert(lookup, out.clone()); + out + }; + let names = face.stylistic_sets(); + let mut categories = vec![]; + for (kind, lookups) in kinds.into_iter().zip(wanted) { + let mut found: Vec = vec![]; + for lookup in lookups { + let room = MAX_ENTRIES.saturating_sub(found.len()); + found.extend(outputs(lookup, &mut reads).into_iter().filter(|g| *g != 0 && *g < glyphs).take(room)); + if found.len() >= MAX_ENTRIES { + break; + } + } + found.sort_unstable(); + found.dedup(); + found.truncate(MAX_ENTRIES); + if found.is_empty() { + continue; + } + let name = match kind { + GlyphCategoryKind::StylisticSet(n) => names.iter().find(|s| s.number == n).and_then(|s| s.name.clone()), + _ => None, + }; + categories.push(GlyphCategory { kind, name, glyphs: found }); + } + categories } /// The glyph single substitution `t` puts in place of each glyph its coverage holds. @@ -383,4 +588,70 @@ impl FontFace { let name = font.glyph_names().get(skrifa::GlyphId::new(gid))?; (!name.is_synthesized()).then(|| name.as_str().to_string()) } + + /// The kinds of glyph the face's `GSUB` table gives ([`GlyphCategoryKind`]), in the order of + /// [`GlyphCategoryKind::all`], each with the glyphs that the single, alternate, multiple and + /// ligature substitutions of its features put in place of others (in extension lookups too), + /// each glyph once by id, `.notdef` and ids past the face's glyph count left out. A single, + /// alternate or multiple substitution of a glyph an earlier subtable of its lookup covers is + /// left out, since that substitution is never made. A kind + /// without glyphs is left out. A stylistic set takes its name from the font's `name` table, + /// when the font gives one. Contextual lookups are not followed, nor is the choice of a + /// variable font's instance of `FeatureVariations`. Read once for the face; empty when it has + /// no `GSUB` table or the table cannot be read. + pub fn glyph_categories(&self) -> &[GlyphCategory] { + self.gsub_index().categories.get_or_init(|| read_categories(self)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test font lists ligatures, stylistic set 2 with its name, small caps and figures, by + /// glyph id; its `cswh` feature has no lookups, so it lists no swashes, and small caps leave out + /// the C of a substitution an earlier subtable shadows. + #[test] + fn categories_list_the_glyphs_each_kind_of_feature_gives() { + use crate::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(categories_font().expect("the test font builds")), 1); + let face = db.face(CATEGORIES_FAMILY, "Regular").expect("the test face"); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let found: Vec<(String, Option, Vec)> = + face.glyph_categories().iter().map(|c| (c.kind.id(), c.name.clone(), c.glyphs.clone())).collect(); + assert_eq!( + found, + [ + ("ligatures".to_string(), None, vec![g('L')]), + ("ss02".to_string(), Some("Round Dots".to_string()), vec![g('G')]), + ("smallCaps".to_string(), None, vec![g('B')]), + ("figures".to_string(), None, figures), + ] + ); + assert!(std::ptr::eq(face.glyph_categories(), face.glyph_categories()), "read once"); + } + + /// A face whose `GSUB` table has no features has no categories. + #[test] + fn a_face_without_features_has_no_categories() { + use crate::test_fonts::{HALF_FORM_FAMILY, half_form_font}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(half_form_font(false).expect("the test font builds")), 1); + let face = db.face(HALF_FORM_FAMILY, "Regular").expect("the test face"); + assert!(face.glyph_categories().is_empty()); + } + + #[test] + fn kinds_round_trip_through_their_ids() { + for kind in GlyphCategoryKind::all() { + assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind)); + } + assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]); + assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]); + assert_eq!(GlyphCategoryKind::from_id("ss21"), None); + assert_eq!(GlyphCategoryKind::from_id("Ligatures"), None); + } } diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 0aa6e1aee5..7a7c904591 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -258,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); } } } @@ -286,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 diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..d9b4fb47b5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition, - LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, - user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind, + GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, + WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 59da6827bd..8ba1746a4d 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -598,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. @@ -1354,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)], @@ -1413,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(); @@ -1507,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. @@ -1888,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); } } } @@ -1902,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; @@ -1931,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 d17ce78603..578651672f 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -901,6 +901,66 @@ pub fn capped_candidates_font() -> Option> { Some(builder.build()) } +/// The family of [`categories_font`]. +pub const CATEGORIES_FAMILY: &str = "Categorytest Sans"; + +/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table of a `liga` ligature of +/// f and i into L, an `onum` alternate substitution of 1 by 7 and 8, an `smcp` single substitution +/// of a by B (a second subtable's substitution of a by C is shadowed by it), an `ss02` single substitution of g by G named "Round Dots" (name id 256), and a +/// `cswh` feature without lookups. Family [`CATEGORIES_FAMILY`]. `None` when it can't be built. +pub fn categories_font() -> Option> { + use write_fonts::tables::gsub::{ + AlternateSet, AlternateSubstFormat1, Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubst, SingleSubstFormat2, SubstitutionLookup, + SubstitutionLookupList, + }; + use write_fonts::tables::layout::{ + CoverageFormat1, Feature, FeatureList, FeatureParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, StylisticSetParams, + }; + use write_fonts::types::GlyphId16; + + let font = skrifa::FontRef::new(SOURCE_SANS).ok()?; + let charmap = font.charmap(); + let name = name_table(&[ + (1, CATEGORIES_FAMILY), + (2, "Regular"), + (4, "Categorytest Sans Regular"), + (6, "CategorytestSans-Regular"), + (256, "Round Dots"), + ])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let cover = |c| Some(CoverageFormat1::new(vec![gid(c)?])); + let single = |from, to| Some(SingleSubst::from(SingleSubstFormat2::new(cover(from)?.into(), vec![gid(to)?]))); + let liga = LigatureSubstFormat1::new(cover('f')?.into(), vec![LigatureSet::new(vec![Ligature::new(gid('L')?, vec![gid('i')?])])]); + let onum = AlternateSubstFormat1::new(cover('1')?.into(), vec![AlternateSet::new(vec![gid('7')?, gid('8')?])]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![liga])), + SubstitutionLookup::Alternate(Lookup::new(Default::default(), vec![onum])), + // The second subtable's substitution of a is never made: the first one covers a. + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('a', 'B')?, single('a', 'C')?])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('g', 'G')?])), + ]); + let named = Some(FeatureParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))); + // Features sorted by tag, as OpenType requires. + let records = vec![ + FeatureRecord::new(Tag::new(b"cswh"), Feature::new(None, vec![])), + FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"onum"), Feature::new(None, vec![1])), + FeatureRecord::new(Tag::new(b"smcp"), Feature::new(None, vec![2])), + FeatureRecord::new(Tag::new(b"ss02"), Feature::new(named, vec![3])), + ]; + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2, 3, 4])), vec![]))]); + builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`joining_alternates_font`]. pub const JOINING_ALTERNATES_FAMILY: &str = "Jointest Sans"; 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/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index b32535d83e..a8c0a0ae90 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -256,12 +256,20 @@ enum LpDragFrom { /// 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)> { + // Only a face whose bounds meet the drag's bounds can be crossed. + let Some(drag) = chunks.iter().flatten().fold(None, |r: Option, p| Some(r.map_or(Rect::from_points(*p, *p), |r| r.union_pt(*p)))) else { + return vec![]; + }; 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() + && bounds.x0 <= drag.x1 + && drag.x0 <= bounds.x1 + && bounds.y0 <= drag.y1 + && drag.y0 <= bounds.y1 { hit.push(f); regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds)); @@ -487,8 +495,8 @@ 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`), a press's drag or release crossing `part` included; `now` when the - /// last press did not paint it. + /// filled there is `part`), a press's drag or release crossing `part` included; `now` when no + /// press of the sequence painted `part` and the last press's drag did not cross 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 = |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); @@ -541,8 +549,11 @@ impl LivePaintBucketTool { if clicks == 2 && let Some(group) = cx.doc.node(g) { - // The other edge either click painted joins as the stroke paint it had before. - let through: Vec = self + // The other edge of this group either click painted joins as the stroke paint it + // had before. A face either click filled is not an edge and does not join. + let group_edges: std::collections::HashSet = edges(group).iter().map(|x| x.id).collect(); + let mut through: Vec = vec![]; + for id in self .presses .len() .checked_sub(2) @@ -552,8 +563,11 @@ impl LivePaintBucketTool { .flatten() .filter(|q| q.before == like) .filter_map(|q| q.part) - .filter(|id| *id != e.id) - .collect(); + { + if id != e.id && group_edges.contains(&id) && !through.contains(&id) { + through.push(id); + } + } self.note_reached(group, connected_edges_through(group, e.id, &like, &through), true); if !through.is_empty() { v["through"] = json_ids(&through); @@ -797,7 +811,7 @@ 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 press that did not reach the tool 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); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a1f1785923..89250fa0fb 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -22,6 +22,8 @@ //! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths. //! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke //! begins closes the path on release. +//! Alt held at the Eraser's press draws a marquee instead of a stroke, a square while Shift is +//! held, and the release erases everything inside it. //! Alt held at the Knife's press makes it cut along the straight line from the press point to the //! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that //! line to 45° steps from the canvas axes. @@ -163,6 +165,11 @@ pub struct GestureTool { /// The pointer has moved from the press point, by any distance (a move too short to add a /// point counts). moved: bool, + /// Active Eraser drag draws a marquee (Alt held at the press): the release erases the + /// rectangle from the press point to the pointer, a square while Shift is held. + marquee: bool, + /// Shift was held at the last event of the Eraser's marquee drag. + square: bool, /// Active Pencil drag draws a straight line (Shift or Alt held at the press), or active Knife /// drag cuts along one (Alt held at the press): the stroke is the press point and the pointer. straight: bool, @@ -190,6 +197,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 @@ -867,6 +878,8 @@ impl GestureTool { smooth_fidelity: SMOOTH_FIDELITY, smoothing: false, moved: false, + marquee: false, + square: false, straight: false, unconstrained: false, shift_line: None, @@ -878,6 +891,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), @@ -945,6 +960,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); } } @@ -966,6 +983,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 @@ -980,6 +1005,11 @@ impl GestureTool { self.id == "blobBrush" && m.alt && !self.moved } + /// Would a press with `m` held draw the Eraser's marquee? Alt held at the press. + fn alt_marquee(&self, m: Mods) -> bool { + self.id == "eraser" && m.alt + } + /// Shift keeps an active straight Knife cut at 45° steps; without Shift it follows the pointer. /// Releasing Alt does not end a straight cut. fn knife_shift(&mut self, m: Mods) { @@ -1043,6 +1073,43 @@ impl GestureTool { ] } + /// The Eraser's marquee: the rectangle from the press point to the pointer, or with Shift held + /// the square on the larger of its sides, in the direction the pointer went. `None` outside a + /// marquee drag. + fn marquee_rect(&self) -> Option { + let (&a, &b) = (self.points.first()?, self.points.last()?); + if !self.marquee { + return None; + } + let d = b - a; + let b = if self.square { + let side = d.x.abs().max(d.y.abs()); + a + Vec2::new(side.copysign(d.x), side.copysign(d.y)) + } else { + b + }; + Some(Rect::from_points(a, b)) + } + + /// A drag or the release of the Eraser's marquee: the marquee runs from the press point to the + /// pointer, and the release erases it. `None` for any other event. + fn marquee_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + if !(self.active && self.marquee && matches!(ev.kind, PointerKind::Drag | PointerKind::Up)) { + return None; + } + self.square = ev.mods.shift; + self.points.truncate(1); + self.points.push(ev.pos); + if !matches!(ev.kind, PointerKind::Up) { + return Some(vec![]); + } + let out = self.finish(cx, ev.mods); + self.active = false; + self.marquee = false; + self.clear(); + Some(out) + } + /// Forget the stroke. fn clear(&mut self) { self.moved = false; @@ -1053,6 +1120,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); @@ -1113,12 +1182,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 @@ -1144,12 +1275,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() { @@ -1329,6 +1473,13 @@ impl GestureTool { } return vec![]; } + if let Some(r) = self.marquee_rect() { + // A click, or a drag along one axis, encloses no area: nothing is erased. + if r.width() <= 0.0 || r.height() <= 0.0 || r.width().max(r.height()) < cx.tol(1.0) { + return vec![]; + } + return vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [r.x0, r.y0, r.width(), r.height()]}))]; + } match self.id { "pencil" | "paintbrush" => { if !self.began { @@ -1404,6 +1555,9 @@ impl Tool for GestureTool { if self.varies_size() { self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); } + if let Some(out) = self.marquee_pointer(cx, ev) { + return out; + } match ev.kind { PointerKind::Down => { self.active = true; @@ -1420,6 +1574,9 @@ impl Tool for GestureTool { // too, the line keeps Shift's 45° steps. Alt makes the Knife cut along a straight line. self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt); self.unconstrained = self.straight && !ev.mods.shift; + // Alt makes the Eraser draw a marquee, and Shift keeps it square. + self.marquee = self.alt_marquee(ev.mods); + self.square = ev.mods.shift; let extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None }; self.set_extend(cx, extend); // The stroke's previews select the path it continues, so the others are kept now. @@ -1601,6 +1758,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { vec![Action::Cancel] } else { vec![] } } @@ -1633,6 +1791,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { stale.into_iter().chain([Action::Commit]).collect() } else { vec![] } } @@ -1640,6 +1799,14 @@ impl Tool for GestureTool { self.area_pending.set(false); self.band_pending.set(false); let mut o = self.snap.guides().to_vec(); + // The Eraser's marquee shows without the tip outline. + if self.active + && self.points.len() >= 2 + && let Some(r) = self.marquee_rect() + { + o.push(Overlay::Marquee(r)); + return o; + } // A path being drawn shows itself, except with the Pencil's Live preview off. if !self.active || self.points.len() < 2 || (self.began && self.previews()) { o.extend(self.tip_outline(cx)); @@ -1660,31 +1827,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..2e417b38b2 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2032,6 +2032,82 @@ fn eraser_and_knife_exec_on_release() { assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3)); } +/// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the +/// tip outline, and the release erases that rectangle; a drag back up and left gives the same +/// kind of rectangle, measured from its top-left corner. +#[test] +fn eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 170.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 190.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(50.0, 150.0, 250.0, 190.0))]); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 200.0).with_mods(alt)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [50.0, 150.0, 200.0, 50.0]}))]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + // A click erases nothing. + let acts = drag_held(&mut t, &cx, &[(250.0, 200.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a click: {acts:?}"); + // Alt only at the press is enough, and the drag can go up and left of the press point. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 200.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 120.0)); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 120.0)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 120.0, 150.0, 80.0]}))]); + // Without Alt the drag is a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v.get("rect").is_none() && v["points"].is_array())); +} + +/// Alt+Shift keeps the Eraser's marquee square on its larger side, in the direction the pointer +/// went; Shift can be pressed or let go during the drag. +#[test] +fn eraser_alt_shift_drag_keeps_the_marquee_square() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let alt_shift = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(alt_shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt_shift)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 140.0, 260.0, 200.0))]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 170.0, 260.0, 200.0))], "Shift let go"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 280.0).with_mods(alt_shift)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [120.0, 200.0, 80.0, 80.0]}))]); + // A drag along one axis gives a square too. + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 140.0)], alt_shift); + assert_eq!(acts[2], vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 100.0, 40.0, 40.0]}))]); +} + +/// A marquee that encloses no area erases nothing, and Escape during the drag cancels the marquee: +/// the release that follows sends nothing. +#[test] +fn eraser_marquee_click_or_escape_erases_nothing() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 160.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a drag along one axis: {acts:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(alt)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(alt)), vec![]); + // The next plain drag erases a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"].is_array())); +} + /// The points of the Knife's release command. fn knife_points(acts: &[Action]) -> Vec<(f64, f64)> { let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; @@ -2933,6 +3009,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 197d41aaaf..70f6422055 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -291,8 +291,8 @@ 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. + /// A press on the canvas did not reach the tool: it went to the view tools (held Space, the + /// middle button), or with Cmd/Ctrl held to the selection tool the session lends. 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, diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a5c92b00b0..97e980e3c0 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -51,6 +51,8 @@ const ROWS: &[Row] = &[ (&["livePaintBucket"], None, &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight", "color", "width"]), (&["polygon"], None, &["sides"]), (&["star"], None, &["points"]), + // The Ellipse dialog's Anchors. + (&["ellipse"], None, &["anchors"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..9eda809c03 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -84,6 +84,9 @@ pub struct ShapeTool { began: bool, pub sides: u32, pub points: u32, + /// The anchors an ellipse made by a click has (the Ellipse dialog opens on it); 4 is a live + /// ellipse. + pub anchors: u32, pub corner_radius: f64, /// Star inner radius as a fraction of the outer radius. pub star_ratio: f64, @@ -146,6 +149,7 @@ impl ShapeTool { began: false, sides: 6, points: 5, + anchors: 4, corner_radius: 12.0, star_ratio: 0.5, inner: None, @@ -787,6 +791,7 @@ impl Tool for ShapeTool { json!({ "sides": self.sides, "points": self.points, + "anchors": self.anchors, "cornerRadius": self.corner_radius, "starRatio": self.star_ratio, "length": self.line_length, @@ -799,6 +804,7 @@ impl Tool for ShapeTool { match key { "sides" => self.sides = v.as_u64().unwrap_or(6).clamp(3, 1000) as u32, "points" => self.points = v.as_u64().unwrap_or(5).clamp(3, 1000) as u32, + "anchors" => self.anchors = v.as_u64().unwrap_or(4).clamp(2, 1000) as u32, "cornerRadius" => self.corner_radius = finite.unwrap_or(12.0).clamp(0.0, MAX_CORNER_RADIUS), "starRatio" => self.star_ratio = v.as_f64().unwrap_or(0.5).clamp(0.01, 1.0), "length" => self.line_length = finite.map_or(self.line_length, |n| n.abs().min(1e6)), 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/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/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 3a45d90157..34611fd0d7 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -536,3 +536,93 @@ fn other_panes_draw_through_their_documents_profiles() { assert!(close(shown, device), "the back CMYK document draws through its Device CMYK: {shown:?}, not {device:?} (front: {front:?})"); assert!(near(cms::active().display_rgb(&color).map(|v| (v * 255.0).round() as u8), p3), "the front document's profile stays active"); } + +/// With a display profile, the tiled pane of a document behind the front one blends its +/// translucent art with that document's own simulated paper in sRGB, then converts the blend: +/// drawn over its converted paper, the pane shows the converted blend, not the art converted alone +/// and not a blend with the front document's paper. Opaque and empty pixels convert as before. +#[test] +fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_conversion() { + use crate::display_profile::{Found, Reading}; + let mut app = app_with(2); + app.canvas.panes.worker_started = true; // every pane renders on this thread + let (front_paper, back_paper) = ([0x20, 0x40, 0xc0], [0xe0, 0xc0, 0x20]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("document.setup", json!({"gridColors": ["#2040c0", "#ffffff"], "simulatePaper": true})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.setup", json!({"gridColors": ["#e0c020", "#ffffff"], "simulatePaper": true})).unwrap(); + let half = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let uid = app.session.documents()[1].uid; + let ctx = egui::Context::default(); + // The second document's pane: the raster one frame uploads, its width, and the key it was rendered for. + let pane = |app: &mut VectorcraftApp| -> (Vec, usize, CacheKey) { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| app.canvas_area(ui)); + let (key, tex) = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, s)| s).expect("the second document's pane rendered"); + let id = tex.id(); + let up = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.pixels.clone(), img.width()) + }); + let key = key.clone(); + out.textures_delta.clear(); + let (pixels, width) = up.expect("the pane uploads"); + (pixels, width, key) + }; + app.session.prefs.monitor_profile_display = false; + let (srgb, width, key) = pane(&mut app); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + app.session.prefs.monitor_profile_display = true; + let (shown, _, key) = pane(&mut app); + let backdrop = key.backdrop.as_deref().expect("the pane's Preview blends with its paper"); + assert!( + !backdrop.artboards.is_empty() && backdrop.artboards.iter().all(|(_, c)| *c == back_paper), + "the pane blends with its own document's paper: {backdrop:?}" + ); + assert_eq!(srgb.len(), shown.len()); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + // Pixel `s` over the paper `paper` in sRGB, converted. + let blend = |s: Color32, paper: [u8; 3]| { + let k = 255 - u32::from(s.a()); + t.apply8([0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (u32::from(paper[j]) * k + 127) / 255).min(255) as u8)).map(u32::from) + }; + let differs = |a: [u32; 3], b: [u32; 3]| (0..3).any(|j| a[j].abs_diff(b[j]) > 2); + let under = t.apply8(back_paper); + for (s, c) in srgb.iter().zip(&shown) { + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before"); + } + } + // The middle of the pane is the middle of the document, inside the 50% fill. + let at = srgb.len() / width / 2 * width + width / 2; + let (s, c) = (srgb[at], shown[at]); + assert!((50..=205).contains(&s.a()), "the 50% fill at the middle: {s:?}"); + assert_eq!(c.a(), s.a(), "the alpha is kept"); + let want = blend(s, back_paper); + let got = over(c, under); + assert!((0..3).all(|j| got[j].abs_diff(want[j]) <= 1), "{got:?} shown, {want:?} wanted"); + // The check tells the two papers and the plain conversion apart. + assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color"); + assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6803e977a1..0051ded2d3 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -777,6 +777,61 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert!(chips(&mut app) > 0); } +/// A press between a Live Paint Bucket triple-click's clicks that the view tools take (a +/// middle-button pan, a pan with Space held) counts as a press that paints nothing: the +/// triple-click matches the fill the face had before the first click. +#[test] +fn bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before() { + use egui::{Event, Modifiers, PointerButton}; + use vectorcraft_color::{Color, Paint}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + for case in ["middle", "space"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = [0.0, 50.0, 100.0] + .iter() + .map(|x| app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()) + .collect(); + app.session.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = app.session.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + for (x, hex) in [(25, "#ff0000"), (75, "#ff0000"), (125, "#0000ff")] { + app.session.execute("livePaint.fill", &json!({"group": g, "point": [x, 125], "color": hex})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("livePaintBucket"); + app.session.paint.fill = green.clone(); + if let Some(v) = app.view_mut() { + v.center = Point::new(200.0, 150.0); + v.zoom = 1.0; + v.fitted = true; + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = xf.to_screen(Point::new(25.0, 125.0)); + let click = |app: &mut VectorcraftApp, button, pos, modifiers| { + let b = |pressed| Event::PointerButton { pos, button, pressed, modifiers }; + frame(app, &ctx, vec![Event::PointerMoved(pos), b(true)]); + frame(app, &ctx, vec![b(false)]); + }; + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + if case == "middle" { + click(&mut app, PointerButton::Middle, at, Modifiers::NONE); + } else { + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, &ctx, vec![space(true)]); + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + frame(&mut app, &ctx, vec![space(false)]); + } + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + frame(&mut app, &ctx, vec![]); + let group = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(g)).unwrap().clone(); + let fill = |x: f64| vectorcraft_tools::builder::face_at(&group, Point::new(x, 125.0)).unwrap().appearance.fill_paint(); + assert_eq!([fill(25.0), fill(75.0)], [green.clone(), green.clone()], "{case}: the faces that were red"); + assert_eq!(fill(125.0), Paint::solid(Color::from_hex("#0000ff").unwrap()), "{case}: the blue face"); + } +} + /// The Image Trace panel's eye-button hold ends when the pointer is released, even when the /// panel stopped drawing while the button was held, so a later press on the canvas does not /// show the source image. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fe48f28952..fab55b8986 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -592,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); @@ -605,11 +606,18 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } + if d.kind == new_document::KIND || new_document::popup_open(d) { + new_document::note_set(d, &field); + } 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/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 3f3cbae3f2..77f3218da6 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -4,6 +4,10 @@ //! Fields: what `file.info` reports (and takes back) plus `__keyword`, the keyword being typed //! (Enter or Add turns it into chips; OK keeps it too). OK runs `file.info` with them: one undo //! step. On an error the dialog stays open. +//! +//! The ≡ menu at the top saves the fields as a metadata template (`file.info.saveTemplate`), imports +//! one (`file.info.applyTemplate`, after a choice of how to merge it into the fields), lists the +//! templates of the metadata templates folder and shows that folder. use serde_json::{Value, json}; use vectorcraft_doc::CopyrightStatus; @@ -11,18 +15,38 @@ use vectorcraft_doc::metadata::MAX_RATING; use super::document_setup::{LABEL, choice}; use super::{DialogSpec, form}; +use crate::picks::PickRequest; use crate::state::Dialog; use crate::theme::Tokens; -use crate::{VectorcraftApp, icons, widgets}; +use crate::{FilePick, VectorcraftApp, icons, widgets}; pub(super) const KIND: &str = "fileInfo"; /// The keyword being typed. const PENDING: &str = "__keyword"; +/// The template waiting for a merge choice: `{path}` or `{name}`. +const IMPORT: &str = "__import"; +/// The merge choice for [`IMPORT`]: `file.info.applyTemplate`'s `mode`. +const IMPORT_MODE: &str = "__importMode"; +/// The templates in the metadata templates folder, listed when the menu opens: `[label, file]` +/// pairs, the label being the name, or the file name where two templates share a name. +const TEMPLATES: &str = "__templates"; +/// The merge choices, as `file.info.applyTemplate` names them. +const MODES: [&str; 3] = ["replace", "keep", "append"]; +/// The extension of a metadata template file. +const XMP_EXT: &str = "xmp"; /// Width of the text fields. const FIELD: f32 = 320.0; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("File Info").into(), body, confirm, min_width: 500.0, max_width: Some(500.0), ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("File Info").into(), + body, + confirm, + // OK and Enter wait while a template being imported waits for its merge choice. + ok_enabled: Some(|_, d| !d.fields.get(IMPORT).is_some_and(Value::is_object)), + min_width: 500.0, + max_width: Some(500.0), + ..DialogSpec::FORM +}; /// Open File Info on the active document's. pub fn open(app: &mut VectorcraftApp) -> Result { @@ -60,8 +84,193 @@ fn add_keywords(d: &mut Dialog) { d.fields.insert(PENDING.into(), json!("")); } -fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// What the templates menu asked for, done once the menu is drawn. +enum Act { + Save, + Import, + Template(String), + Folder, +} + +/// A file dialog for metadata templates. +fn xmp_pick() -> FilePick { + FilePick { filters: vec![FilePick::filter("XMP metadata templates", &[XMP_EXT])], ..Default::default() } +} + +/// Whether the session has a metadata templates folder for Templates Folder to show (the web build +/// has none). +fn has_templates_folder(app: &VectorcraftApp) -> bool { + app.session.metadata_templates_dir().is_some() +} + +/// The ≡ templates menu at the top right, and the merge choice for a template it picked. +fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); + let can_save = crate::picks::can(app, &PickRequest::Save(xmp_pick())); + let can_open = crate::picks::can(app, &PickRequest::Open(xmp_pick())); + let has_folder = has_templates_folder(app); + let mut act = None; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); + let resp = ui.interact(rect, ui.scope_id().with("file-info-templates"), egui::Sense::click()); + icons::paint(ui, "menu", rect.shrink(1.0), if resp.hovered() { t.text_strong } else { t.text_dim }); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Templates"))); + let resp = resp.on_hover_text(tl!("Templates")); + if resp.clicked() { + // Listed once as the menu opens, not on every frame it shows. + let listed = app.session.execute("file.info.templates", &json!({})).map(|r| r["templates"].clone()).unwrap_or_default(); + let listed: Vec<(&str, &str)> = + listed.as_array().into_iter().flatten().filter_map(|t| Some((t.get("name")?.as_str()?, t.get("file")?.as_str()?))).collect(); + let entries: Vec = listed + .iter() + .map(|&(name, file)| { + let shared = listed.iter().filter(|(n, _)| *n == name).count() > 1; + json!([if shared { file } else { name }, file]) + }) + .collect(); + d.fields.insert(TEMPLATES.into(), json!(entries)); + } + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(220.0); + if can_save && widgets::menu_item(ui, tl!("Save Metadata Template…"), true, false) { + act = Some(Act::Save); + } + if can_open && widgets::menu_item(ui, tl!("Import…"), true, false) { + act = Some(Act::Import); + } + let entries: Vec<(String, String)> = d + .fields + .get(TEMPLATES) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))) + .collect(); + if !entries.is_empty() { + ui.separator(); + widgets::menu_scroll(ui, |ui| { + for (label, file) in entries { + if widgets::menu_item_name(ui, &label, true, false) { + act = Some(Act::Template(file)); + } + } + }); + } + if has_folder { + ui.separator(); + if widgets::menu_item(ui, tl!("Templates Folder"), true, false) { + act = Some(Act::Folder); + } + } + }); + }) + }); + let r = match act { + None => Ok(()), + // The file dialogs, shown off the UI thread, act on the dialog as it is then. + Some(Act::Save) => crate::picks::in_dialog(app, d, save_template), + Some(Act::Import) => crate::picks::in_dialog(app, d, pick_template), + // `file.info.applyTemplate` takes a listed template's file name as its `name`. + Some(Act::Template(file)) => { + d.fields.insert(IMPORT.into(), json!({ "name": file })); + Ok(()) + } + Some(Act::Folder) => show_folder(app), + }; + if let Err(e) = r { + app.status(e); + } + import_options(app, ui, d); +} + +/// Save Metadata Template…: the fields as they are in the dialog, to a file picked in a save +/// dialog that starts in the metadata templates folder. A name typed without `.xmp` takes it, so +/// the templates list shows the file; a file already there under that name is replaced only after +/// a question. +fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut d2 = d.clone(); + add_keywords(&mut d2); + let folder = app.session.execute("file.info.templates", &json!({ "create": true })).ok().and_then(|r| r["folder"].as_str().map(str::to_string)); + let name = format!("{}.{XMP_EXT}", d2.str("title").trim()); + let pick = FilePick { name, folder, ..xmp_pick() }; + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(picked) = crate::picks::save(app, &pick) else { return Ok(()) }; + let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") }; + // The save dialog did not ask about the completed name: ask here, and the answer runs this again. + if path != picked && crate::picks::ask_to_replace(app, PickRequest::Save(pick), &picked, None, &path) { + return Ok(()); + } + app.run("file.info.saveTemplate", json!({ "path": path, "fields": form::params(&d2) })).map(|_| ()) +} + +/// Import…: a template picked in an open dialog waits for its merge choice. +fn pick_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(path) = crate::picks::open(app, &xmp_pick()) else { return Ok(()) }; + d.fields.insert(IMPORT.into(), json!({ "path": path })); + Ok(()) +} + +/// Templates Folder: the metadata templates folder (made when it is missing) in the file manager. +fn show_folder(app: &mut VectorcraftApp) -> Result<(), String> { + let r = app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?; + let folder = r["folder"].as_str().ok_or("no metadata templates folder here")?.to_string(); + crate::io::open_in_app(app, &folder) +} + +/// The merge choice for the template [`IMPORT`] names: OK merges it into the dialog's fields +/// (nothing changes in the document until the dialog's own OK), Cancel drops it. +fn import_options(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let Some(source) = d.fields.get(IMPORT).and_then(Value::as_object).cloned() else { return }; + widgets::subheader(ui, tl!("Import Options")); + let mode = d.fields.get(IMPORT_MODE).and_then(Value::as_str).filter(|m| MODES.contains(m)).unwrap_or("keep").to_string(); + let labels = [ + tl!("Clear existing fields and use the template's"), + tl!("Keep existing fields, but replace those the template has"), + tl!("Keep existing fields, but append those the template has"), + ]; + for (value, label) in MODES.into_iter().zip(labels) { + if widgets::radio(ui, label, mode == value, true) { + d.fields.insert(IMPORT_MODE.into(), json!(value)); + } + } + let mut ok = false; + let mut cancel = false; + ui.horizontal(|ui| { + ok = widgets::flat_button(ui, tl!("OK"), 64.0).clicked(); + cancel = widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked(); + }); + ui.add_space(10.0); + if ok { + if let Err(e) = import(app, d, source, &mode) { + app.status(e); + } + } else if cancel { + d.fields.remove(IMPORT); + } +} + +/// Merge the template `source` names into the dialog's fields as `mode` says. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, source: serde_json::Map, mode: &str) -> Result<(), String> { + let mut p = Value::Object(source); + p["mode"] = json!(mode); + p["apply"] = json!(false); + let mut d2 = d.clone(); + add_keywords(&mut d2); + p["base"] = form::params(&d2); + let merged = app.session.execute("file.info.applyTemplate", &p).map_err(|e| e.to_string())?; + for (k, v) in merged.as_object().into_iter().flatten() { + d.fields.insert(k.clone(), v.clone()); + } + d.fields.insert(PENDING.into(), json!("")); + d.fields.remove(IMPORT); + Ok(()) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + templates_menu(app, ui, d); for (key, label) in [("title", tl!("Document Title:")), ("author", tl!("Author:")), ("authorTitle", tl!("Author Title:"))] { widgets::label_row(ui, label, LABEL, |ui| { form::text(ui, d, key, FIELD); @@ -233,4 +442,86 @@ mod tests { assert!(crate::dialogs::confirm(&mut app).is_err()); assert!(app.ui.dialog.is_some()); } + + #[test] + fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info.saveTemplate", json!({"name": "Studio", "fields": {"author": "Grace", "keywords": ["print"], "rating": 3}})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + d.fields.insert(super::PENDING.into(), json!("fair")); + // A listed template waits for its merge choice; the choice draws. + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + d.fields.insert(super::IMPORT_MODE.into(), json!("append")); + frame(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + super::import(&mut app, &mut d, json!({"name": "Studio"}).as_object().unwrap().clone(), "append").unwrap(); + assert!(!d.fields.contains_key(super::IMPORT)); + // Appended: the typed author stays, the typed keyword is kept and the template's added. + assert_eq!( + (d.fields["author"].clone(), d.fields["keywords"].clone(), d.fields["rating"].clone()), + (json!("Ada"), json!(["fair", "print"]), json!(3)) + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "nothing changes before OK"); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.metadata.author.as_str(), st.doc.metadata.rating), ("Ada", 3)); + assert_eq!(st.history.undo.len(), 1); + } + + #[test] + fn templates_folder_is_offered_only_where_there_is_one() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-folder"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert!(!super::has_templates_folder(&app), "a session without a folder, as on the web, offers no Templates Folder"); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + assert!(super::has_templates_folder(&app)); + } + + #[test] + fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let ok = |app: &VectorcraftApp, d: &crate::state::Dialog| super::SPEC.ok_enabled.is_none_or(|f| f(app, d)); + assert!(ok(&app, &d)); + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + assert!(!ok(&app, &d), "OK and Enter wait while the merge choice is shown"); + d.fields.remove(super::IMPORT); + assert!(ok(&app, &d)); + } + + #[test] + fn a_template_saved_without_an_extension_gets_xmp_and_is_listed() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-save-ext"); + let folder = dir.join("Metadata Templates"); + let typed = folder.join("Studio").to_string_lossy().into_owned(); + let services = crate::Services { + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(typed.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.attach_metadata_templates_dir(folder.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert!(folder.join("Studio.xmp").is_file() && !folder.join("Studio").exists(), "the typed name takes .xmp"); + let listed = app.session.execute("file.info.templates", &json!({})).unwrap(); + assert!(listed.to_string().contains("Studio"), "{listed}"); + // A file already there under the completed name is not replaced without asking. + std::fs::write(folder.join("Studio.xmp"), b"kept").unwrap(); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert_eq!(std::fs::read(folder.join("Studio.xmp")).unwrap(), b"kept"); + assert_eq!(d.kind, crate::dialogs::confirm::REPLACE, "the dialog asks before replacing it"); + } } 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/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cfd6c3b0d3..4f48d4ad2f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -12,7 +12,10 @@ //! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, //! `previewMode`, `alignNewObjectsToPixelGrid`, `profile`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and //! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing -//! any of them afterwards makes the settings custom. +//! any of them afterwards makes the settings custom. The dialog opens in Preferences › Units › +//! General, also on a Recent entry made in other units (one in pixels, or a saved preset in the +//! units it was saved in, keeps its units); units chosen +//! in the Units menu or set with `ui.dialog.set` stay when another tab or preset is chosen. use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; @@ -57,6 +60,9 @@ const SAVING: &str = "__saving"; /// Preset Details has drawn the saving top: set from the mode's second frame, so the first one fills /// in the default name and focuses it. const SAVING_SHOWN: &str = "__savingShown"; +/// The units were chosen in the Units menu (or set with `ui.dialog.set`): presets chosen after that +/// keep the chosen units. +const UNITS_CHOSEN: &str = "__unitsChosen"; /// The units New Document offers (all ten). const UNITS: [Unit; 10] = [ Unit::Pixels, @@ -82,17 +88,49 @@ const HEADER: f32 = 100.0; const MORE_WIDTH: f32 = 310.0; /// Open New Document on the most recent settings (or Letter), named after the next untitled -/// document. +/// document, in Preferences › Units › General. pub fn open(app: &mut VectorcraftApp) { let category = if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" }; - let first = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()).unwrap_or_default(); let mut d = Dialog::new(KIND, json!({ "category": category, "name": app.session.peek_untitled(), "advanced": false })); - apply(&mut d, &first); + if !apply_first(app, &mut d, category) { + apply(&mut d, &DocSettings { units: app.session.default_units(), ..DocSettings::default() }); + } app.ui.dialog = Some(d); } -/// Fill the fields from a preset. +/// Fill the fields from the first preset of `category`, as opening the dialog and choosing a tab +/// do; false when the category has none. The most recent entry keeps its size and takes +/// Preferences › Units › General, as the built-in presets do, unless it is in pixels or it is a +/// saved preset in the units it was saved in. Its card stays the chosen one and shows those units; +/// choosing another card brings back that card's own units. +fn apply_first(app: &VectorcraftApp, d: &mut Dialog, category: &str) -> bool { + let Some(first) = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()) else { return false }; + // `file.new` reads a named preset in its own units, and names the entry Custom in others. + let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units); + if !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved { + apply(d, &first); + return true; + } + let own = first.units; + apply(d, &DocSettings { units: app.session.default_units(), ..first }); + // The card is still the entry it was: its own units say which entry it is. + if let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) { + a.insert("units".into(), json!(own.label())); + } + true +} + +/// `field` of New Document `d` is about to be set by `ui.dialog.set`: setting the units is a choice +/// that presets chosen after it keep. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if field == "units" { + d.fields.insert(UNITS_CHOSEN.into(), json!(true)); + } +} + +/// Fill the fields from a preset, keeping the units when they were chosen in the Units menu. fn apply(d: &mut Dialog, s: &DocSettings) { + let chosen = if d.bool(UNITS_CHOSEN) { d.fields.get("units").cloned() } else { None }; let Value::Object(mut v) = s.to_json() else { return }; for k in ["size", "orientation"] { v.remove(k); @@ -105,6 +143,9 @@ fn apply(d: &mut Dialog, s: &DocSettings) { d.fields.insert(k.clone(), val.clone()); } d.fields.insert(APPLIED.into(), Value::Object(v)); + if let Some(u) = chosen { + d.fields.insert("units".into(), u); + } } /// Keep the fields and the chosen preset in step: a new `preset` (also from `ui.dialog.set`) fills @@ -305,8 +346,8 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Some(i) = widgets::tab_bar(ui, &names, cat) { d.fields.insert("category".into(), json!(names[i])); // A tab opens on its first preset, so the details match its cards. - if let Some(first) = names.get(i).and_then(|c| newdoc::category(&app.session, c)).and_then(|v| v.into_iter().next()) { - apply(d, &first); + if let Some(c) = names.get(i) { + apply_first(app, d, c); } } let list = names.get(cat).and_then(|c| newdoc::category(&app.session, c)).unwrap_or_default(); @@ -705,6 +746,7 @@ fn units_dropdown(ui: &mut egui::Ui, d: &mut Dialog, width: f32) { let labels = UNITS.map(Unit::label); if let Some(u) = widgets::dropdown(ui, "newdoc-units", unit(d).label(), &labels, width).and_then(|i| UNITS.get(i)) { d.fields.insert("units".into(), json!(u.label())); + d.fields.insert(UNITS_CHOSEN.into(), json!(true)); } } @@ -1569,6 +1611,103 @@ mod tests { assert!(h.state().session.active().unwrap().doc.setup.align_new_objects_to_pixel_grid); } + /// Create, then the new document's units. + fn create(h: &mut Harness) -> vectorcraft_doc::Unit { + h.get_by_label("Create").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status); + h.state().session.active().unwrap().doc.units + } + + /// With Preferences › Units › General in millimeters, New Document opens on the most recent + /// entry in millimeters even though that entry was made in points, and New Without Dialog makes + /// the same document. An entry in pixels stays in pixels, as the screen presets do. + #[test] + fn the_dialog_opens_in_the_general_units_over_a_recent_entry() { + use vectorcraft_doc::Unit::{Millimeters as Mm, Pixels as Px}; + let mut h = big(); + h.state_mut().run("file.new", json!({"units": "Points"})).unwrap(); + h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap(); + assert_eq!(h.state().session.prefs.recent_new_docs[0].units, vectorcraft_doc::Unit::Points); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Recent"), json!("Millimeters"))); + assert_eq!(create(&mut h), Mm, "the dialog's Create"); + h.state_mut().run("file.new", json!({"units": "Points"})).unwrap(); + h.state_mut().run("file.newWithoutDialog", json!({})).unwrap(); + assert_eq!(h.state().session.active().unwrap().doc.units, Mm, "New Without Dialog"); + h.state_mut().run("file.new", json!({"preset": "Web 1920×1080"})).unwrap(); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(field(h.state(), "units"), json!("Pixels")); + assert_eq!(create(&mut h), Px); + } + + /// A Recent entry that is a saved preset in the units it was saved in opens in those units, so + /// Create keeps the preset's name in Recent; the General unit is millimeters. + #[test] + fn a_recent_saved_preset_keeps_its_units_and_name() { + let mut h = big(); + h.state_mut().run("file.newPresets.save", json!({"name": "Zine", "width": "5.5 in", "height": "8.5 in", "units": "Inches"})).unwrap(); + h.state_mut().run("file.new", json!({"preset": "Zine"})).unwrap(); + h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap(); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!((field(h.state(), "preset"), field(h.state(), "units")), (json!("Zine"), json!("Inches"))); + assert_eq!(create(&mut h), vectorcraft_doc::Unit::Inches); + let recent = &h.state().session.prefs.recent_new_docs; + assert_eq!((recent.len(), recent[0].name.as_str()), (1, "Zine"), "{recent:?}"); + } + + /// Units set with `ui.dialog.set` while More Settings or Manage Profiles is open stay chosen + /// when a preset is chosen after them. + #[test] + fn units_set_over_a_popup_stay_chosen() { + for popup in [super::MORE, super::PROFILES] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.kind = popup.into(); + crate::dialogs::set_field(d, "units".into(), json!("Millimeters")); + crate::dialogs::set_field(d, "preset".into(), json!("A4")); + d.kind = super::KIND.into(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!((field(&app, "preset"), field(&app, "units")), (json!("A4"), json!("Millimeters")), "{popup}"); + } + } + + /// Millimeters chosen in the Units menu stay chosen when another tab or preset is chosen after + /// them, and reach the new document. + #[test] + fn units_chosen_in_the_menu_survive_tabs_and_presets() { + use vectorcraft_doc::Unit::Millimeters as Mm; + let mut h = big(); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Print"), json!("Points"))); + h.get_by_role_and_label(Role::ComboBox, "Units").click(); + h.run_steps(3); + h.get_by_label("Millimeters").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "units"), json!("Millimeters")); + // A Recent entry made in inches, which the Recent tab opens on. + h.state_mut().run("file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})).unwrap(); + for tab in ["Web", "Recent", "Print"] { + h.get_by_role_and_label(Role::Button, tab).click(); + h.run_steps(3); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!(tab), json!("Millimeters")), "the {tab} tab"); + } + // A preset chosen by name, as `ui.dialog.set` chooses it. + crate::dialogs::set_field(h.state_mut().ui.dialog.as_mut().unwrap(), "preset".into(), json!("A4")); + h.run_steps(3); + assert_eq!( + (field(h.state(), "width"), field(h.state(), "units")), + (json!(vectorcraft_doc::Unit::Millimeters.to_pt(210.0)), json!("Millimeters")) + ); + assert_eq!(create(&mut h), Mm); + } + /// A long translation of Align New Objects to Pixel Grid wraps inside the Preset Details column. #[test] fn align_new_objects_label_wraps_inside_the_details_column() { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 1325794e00..672ee10ec2 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -248,7 +248,7 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { number(ui, d, "taper", tl!("Taper"), (1.0, 100.0), "%", 1, None); choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); ui.add_space(10.0); - heading(ui, c3("Bevel")); + bevel_heading(ui, d); let shapes: Vec<(Value, &str)> = super::effect::own_choices(EXTRUDE, "bevel", false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect(); choice(ui, d, "bevel", tl!("Bevel Shape"), &shapes); @@ -262,6 +262,53 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { }); } +/// Extrude & Bevel's bevel settings (every parameter named `bevel…`) with their defaults. +fn bevel_defaults() -> serde_json::Map { + match vectorcraft_effects::default_params(EXTRUDE) { + Some(Value::Object(m)) => m.into_iter().filter(|(k, _)| k.starts_with("bevel")).collect(), + _ => serde_json::Map::new(), + } +} + +/// Does any setting in `defaults` differ from its default in `d`? A setting the 3D and Materials +/// panel's selected effects hold with different values (null) counts as changed. +fn differs_from(d: &Dialog, defaults: &serde_json::Map) -> bool { + defaults.iter().any(|(k, v)| match (d.fields.get(k), v.as_f64()) { + (Some(Value::Null), _) => true, + (_, Some(default)) => (d.f64(k, default) - default).abs() > 1e-6, + (field, None) => field.is_some_and(|f| f != v), + }) +} + +/// The Bevel heading with its Reset button, which puts every bevel setting back to its default and +/// leaves the other settings as they are. The button is off while every bevel setting is at its +/// default. +fn bevel_heading(ui: &mut egui::Ui, d: &mut Dialog) { + let defaults = bevel_defaults(); + let changed = differs_from(d, &defaults); + let mut reset = false; + ui.horizontal(|ui| { + heading(ui, c3("Bevel")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(changed, |ui| { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(56.0, 20.0), Sense::hover()); + let response = ui.interact(r, Id::unique("revolve-reset-bevel"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset"))); + if response.hovered() { + ui.painter().rect_filled(r, 3.0, t.hover); + } + let color = if ui.is_enabled() { t.text } else { t.text_disabled }; + ui.painter().text(r.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, tl!("Reset"), FontId::proportional(11.5), color); + reset = response.clicked(); + }); + }); + }); + if reset { + d.fields.extend(defaults); + } +} + /// 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) { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index f76a1dfaa1..223c617981 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:?}")) } @@ -343,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()); @@ -404,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"); @@ -442,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!( @@ -559,6 +578,42 @@ fn extrude_bevel_options_enable_with_a_bevel_shape() { assert_eq!(h.response(("revolve-reset", "bevelWidth")), width); } +#[test] +fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() { + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + let enabled = |h: &Harness| h.ctx.read_response(Id::unique("revolve-reset-bevel")).unwrap().enabled(); + assert!(!enabled(&h), "every bevel setting at its default: Reset is off"); + let changed = json!({"bevel": "step", "bevelWidth": 12.0, "bevelHeight": 3.0, "bevelRepeat": 4, "bevelSpace": 30.0, "bevelInside": true, "bevelBothSides": true, "depth": 90.0, "twist": 45.0, "rotationX": 10.0}); + h.app.ui.dialog.as_mut().unwrap().fields.extend(changed.as_object().unwrap().clone()); + h.settle(); + assert!(enabled(&h)); + h.click(h.response("revolve-reset-bevel").center()); + let defaults = vectorcraft_effects::default_params(vectorcraft_effects::EXTRUDE).unwrap(); + let dialog = h.app.ui.dialog.as_ref().unwrap(); + for key in ["bevel", "bevelWidth", "bevelHeight", "bevelRepeat", "bevelSpace", "bevelInside", "bevelBothSides"] { + assert_eq!(dialog.fields.get(key), defaults.get(key), "reset: {key}"); + } + for key in ["depth", "twist", "rotationX"] { + assert_eq!(dialog.fields.get(key), changed.get(key), "kept: {key}"); + } + assert!(!enabled(&h), "Reset turns itself off"); + // One bevel setting off its default is enough to turn Reset on again. + h.app.ui.dialog.as_mut().unwrap().fields.insert("bevelBothSides".into(), json!(true)); + h.settle(); + assert!(enabled(&h)); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let params = vectorcraft_effects::merged_params( + vectorcraft_effects::EXTRUDE, + &state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params, + ); + assert_eq!((params["depth"].clone(), params["bevelBothSides"].clone(), params["bevel"].clone()), (json!(90.0), json!(true), json!("none"))); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + #[test] fn cap_checkbox_previews_resets_and_respects_cancel_and_one_step_undo() { for confirm in [false, true] { 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/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 392c043f35..b807bc5274 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -306,6 +306,9 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { if d.kind == "roundedRectangle" { form::length_field(ui, d, "radius", &form::humanized("radius"), unit); } + if d.kind == "ellipse" { + form::field(ui, d, "anchors", "Anchors:"); + } }); let Some(rows) = rows else { return }; let on = d.bool(LINK); @@ -358,6 +361,13 @@ fn follow_link(d: &mut Dialog, typed: &str) { } } +/// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when +/// left empty or not a number). +fn ellipse_anchors(d: &Dialog) -> u64 { + let n = d.f64("anchors", 4.0); + if n.is_finite() { n.round().clamp(2.0, 1000.0) as u64 } else { 4 } +} + /// The top-left corner of a rectangle or ellipse: the click itself, or with Alt held (draw from centre) the click minus half the size. fn box_origin(d: &Dialog) -> (f64, f64) { let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); @@ -386,11 +396,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values[key] = json!(d.f64(key, default).clamp(min, 1000.0) as u64); values }) + .or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)}))) .or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d))); let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); let (bx, by) = box_origin(d); let (id, params) = match d.kind.as_str() { - "ellipse" => ("shape.ellipse", json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0)})), + "ellipse" => ( + "shape.ellipse", + json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "anchors": ellipse_anchors(d)}), + ), "polygon" => ("shape.polygon", json!({"cx": x, "cy": y, "radius": d.f64("radius", 50.0), "sides": d.f64("sides", 6.0) as u64})), "star" => ( "shape.star", @@ -649,6 +663,85 @@ mod tests { assert!((b.width() - 80.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "{b:?}"); } + /// The Ellipse dialog opens with Anchors 4, which draws a live ellipse; OK with 6 draws a plain + /// path of 6 anchors, and the next Ellipse dialog opens on 6. + #[test] + fn the_ellipse_dialog_draws_and_keeps_its_anchor_count() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + let last = |app: &VectorcraftApp| { + let doc = &app.session.doc().unwrap().doc; + doc.layers[0].children().unwrap().last().cloned().expect("an ellipse") + }; + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 4.0); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 150.0, "y": 150.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("anchors".into(), json!("6")); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}"); + + // Kept as the Ellipse tool's `anchors` option for the next click, after another tool too. + assert_eq!(app.session.tool_options_of("ellipse")["anchors"], json!(6)); + app.run("tool.select", json!({"tool": "rectangle"})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); + app.ui.dialog = None; + // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. + for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { + app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); + app.ui.dialog = None; + } + } + + /// The dialog's Anchors field is named, under Height, and typing into it sets the count. + #[test] + fn the_ellipse_dialog_shows_an_anchors_field() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h.check_accessibility(); + let height = h.get_by_role_and_label(Role::TextInput, "Height:").rect(); + let anchors = h.get_by_role_and_label(Role::TextInput, "Anchors:").rect(); + assert!(anchors.center().y > height.center().y, "Anchors is below Height: {anchors:?} {height:?}"); + assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4); + } + + #[test] + fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() { + let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v })); + for (v, want) in [(json!(6), 6), (json!("7"), 7), (json!(5.6), 6), (json!(1), 2), (json!(0), 2), (json!(-3), 2), (json!(5000), 1000)] { + assert_eq!(ellipse_anchors(&d(v.clone())), want, "{v}"); + } + assert_eq!(ellipse_anchors(&Dialog::new("ellipse", json!({}))), 4); + } + #[test] fn a_negative_line_length_draws_and_keeps_the_same_direction() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 9e6fa98f82..146e02c6eb 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -7,7 +7,8 @@ //! (percent of the symbol's size, -1600..1600: below 0 or above 100 for a guide outside the art), //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; -//! 4 = centre), `__edit` (true when editing an existing symbol). Help: +//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an +//! existing symbol). Help: //! . use serde_json::{Map, Value, json}; @@ -75,7 +76,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "__edit": false }); + let mut fields = + json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -107,6 +109,7 @@ pub fn open_edit(app: &mut VectorcraftApp, name: Option<&str>) -> Result bool { ui.end_row(); } } + label(ui, ""); + form::check(ui, d, "alignToPixelGrid", tl!("Align to Pixel Grid")); + ui.end_row(); }); false } @@ -175,16 +181,17 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let kind = d.str("type"); let registration = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4); let edit = d.fields.get("__edit").and_then(Value::as_bool).unwrap_or(false); + let pixel = d.bool("alignToPixelGrid"); let r = if edit { let from = d.fields.get("__from").and_then(Value::as_str).unwrap_or(name); - let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration }); + let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); if from != name { params["newName"] = json!(name); } app.run("symbol.options", params) } else { - let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration }); + let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); app.run("symbol.new", params) }; diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index ec3c3c766d..e8c0e5c122 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -1,7 +1,7 @@ //! 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 +//! (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}; @@ -42,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); diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 3a8cc570d7..bf65dd4894 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -13,7 +13,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { let y = p.get("y").and_then(Value::as_f64).unwrap_or(0.0); let alt = p.get("alt").and_then(Value::as_bool).unwrap_or(false); let d = match kind { - "rectangle" | "ellipse" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "rectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "ellipse" => Dialog::new( + kind, + json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}), + ), "roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})), "polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})), "star" => { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8a59c7e567..60518dcd2d 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -713,11 +713,64 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures message_at(lang, v, depth - 1) } }; - let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, nested(v))).collect(); + let liquify = liquify_skip_values(lang, s, &caps); + let values: Vec<(&str, String)> = caps + .into_iter() + .map(|(k, v)| match (&liquify, k) { + (Some((tool, _)), "_1") => (k, tool.clone()), + (Some((_, kinds)), "_2") => (k, kinds.clone()), + _ => (k, nested(v)), + }) + .collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); fill_once(template, &args) } +/// The tool labels in Liquify's warning about the objects under the brush that it left as they +/// were, each translated by its `liquify-tool` row. +const LIQUIFY_TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; + +/// The kinds of object that warning lists (the engine's `not_liquified` in +/// `crates/engine/src/cmd/distortcmds.rs`), each translated by its `liquify-kind` row. +const LIQUIFY_KINDS: [&str; 9] = ["graphs", "type", "symbols", "images", "meshes", "envelopes", "repeats", "placed documents", "blends"]; + +/// The tool and the list of kinds in `lang` when `s` is Liquify's warning about the objects under +/// the brush that it left as they were and `caps` are its captures. The kinds keep their order and +/// are joined with the `liquify-list-two` row for two, and the `liquify-list-middle` and +/// `liquify-list-end` rows for more; a missing row leaves its part in English. `None` for any +/// other message, or a tool or kind that is not one of Liquify's. +fn liquify_skip_values(lang: Lang, s: &str, caps: &[(&str, &str)]) -> Option<(String, String)> { + let cap = |name: &str| caps.iter().find(|(k, _)| *k == name).map(|(_, v)| *v); + let (tool, n, kinds) = (cap("_1")?, cap("n")?, cap("_2")?); + let english = if n == "1" { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + }; + if caps.len() != 3 || english != s || !LIQUIFY_TOOLS.contains(&tool) { + return None; + } + let catalog = lang.catalog(); + let words = kinds + .split(", ") + .map(|k| LIQUIFY_KINDS.contains(&k).then(|| catalog.contextual("liquify-kind", k).unwrap_or(k))) + .collect::>>()?; + let join = |context: &str, a: &str, b: &str| { + let pattern = "{0}, {1}"; + fill_once(catalog.contextual(context, pattern).unwrap_or(pattern), &[("0", a), ("1", b)]) + }; + let list = match words.as_slice() { + [] => return None, + [one] => (*one).to_string(), + [a, b] => join("liquify-list-two", a, b), + [first, middle @ .., last] => { + let head = middle.iter().fold((*first).to_string(), |acc, w| join("liquify-list-middle", &acc, w)); + join("liquify-list-end", &head, last) + } + }; + Some((catalog.contextual("liquify-tool", tool).unwrap_or(tool).to_string(), list)) +} + /// The translation of a message with an exact `@msg` row in `catalog`, its `{{` and `}}` shown as /// `{` and `}`. fn exact_translation(catalog: &Catalog, s: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d34abfa1f7..dbfb2f8944 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -639,6 +639,11 @@ font-technology Variable Променливи Copy Width Point Копиране на точка на ширина Copyright Авторско право Copyright Info URL: URL адрес с информация за авторското право: + Save Metadata Template… Запази шаблон за метаданни… + Import Options Опции за импортиране + Clear existing fields and use the template's Изчисти съществуващите полета и използвай тези от шаблона + Keep existing fields, but replace those the template has Запази съществуващите полета, но замени съдържащите се в шаблона + Keep existing fields, but append those the template has Запази съществуващите полета, но добави съдържащите се в шаблона Copyright Notice: Бележка за авторското право: Copyright Status: Статус на авторското право: Copyright Symbol Символ за авторско право @@ -1378,6 +1383,8 @@ font-technology Variable Променливи Graph Диаграма Graph Data Данни за диаграма Graph Type Тип диаграма + Graph Type… Тип диаграма… + Graph Data… Данни за диаграма… Graph Options Опции на диаграмата Left Axis Лява ос Right Axis Дясна ос @@ -3577,6 +3584,9 @@ digits Malayalam Малаялам Show Import Options Показване на опциите за импортиране Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Питане за опциите за импортиране на всеки PDF, DXF или текстов файл преди поставянето му; изключено: използват се последно избраните опции Stylistic Alternates Стилистични алтернативи + Ligatures Лигатури + Ornaments Орнаменти + Figures Цифри Set {n} Набор {n} Swash Декоративен елемент Swatch Conflict Конфликт на образци @@ -5156,6 +5166,7 @@ effect Soft Меко Change Panel Layout Промяна на оформлението на панела Close Panel Затваряне на панела Collapse Panel Group Свиване на групата панели + Cycle Display Sizes Превключване на размерите на показване Move Panel Преместване на панела Group with Групиране с Resize panels Преоразмеряване на панели diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 928f12cd94..6acb852c04 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 @@ -2035,6 +2036,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Odaberite tekst da postavite njegove OpenType mogućnosti. Standard Ligatures Standardne ligature Stylistic Alternates Stilske alternative + Ligatures Ligature + Ornaments Ornamenti + Figures Brojke Set {n} Skup {n} Swash Ukrasni potez Tabular Lining Tabelarne brojke @@ -2572,6 +2576,11 @@ digits Malayalam Malajalam Author Title: Titula autora: Author: Autor: Copyright Info URL: URL informacija o autorskim pravima: + Save Metadata Template… Sačuvaj predložak metapodataka… + Import Options Opcije uvoza + Clear existing fields and use the template's Obriši postojeća polja i koristi polja iz predloška + Keep existing fields, but replace those the template has Zadrži postojeća polja, ali zamijeni ona koja predložak sadrži + Keep existing fields, but append those the template has Zadrži postojeća polja, ali dodaj ona koja predložak sadrži Copyright Notice: Obavještenje o autorskim pravima: Copyright Status: Status autorskih prava: Created: Kreirano: @@ -3602,6 +3611,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 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d1d4372f3b..db482cb7de 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 @@ -946,6 +947,18 @@ antiAlias Sharp Nítid Copyright Copyright Copyright and Contact Info Informació de copyright i de contacte Copyright Info URL: URL de la informació de copyright: + Save Metadata Template… Desa la plantilla de metadades… + Import Options Opcions d’importació + Clear existing fields and use the template's Esborra els camps existents i fes servir els de la plantilla + Keep existing fields, but replace those the template has Conserva els camps existents, però substitueix els que tingui la plantilla + Keep existing fields, but append those the template has Conserva els camps existents, però afegeix els que tingui la plantilla +@msg the template name can't be empty el nom de la plantilla no pot estar buit +@msg the template name isn't usable as a file name el nom de la plantilla no es pot fer servir com a nom de fitxer +@msg no metadata templates folder here aquí no hi ha cap carpeta de plantilles de metadades +@msg give `name` or `path`, not both indiqueu `name` o `path`, no tots dos +@msg give one of `path`, `name` and `data` indiqueu un de `path`, `name` i `data` +@msg mode must be replace, keep or append el mode ha de ser replace, keep o append +@msg the file is not an XMP metadata template el fitxer no és una plantilla de metadades XMP Copyright Notice: Avís de copyright: Copyright Status: Estat del copyright: Copyright Symbol Símbol de copyright @@ -1910,6 +1923,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 @@ -2498,6 +2513,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 @@ -4670,6 +4686,9 @@ digits Malayalam Malaiàlam Show Import Options Mostra les opcions d’importació Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demana les opcions d’importació de cada fitxer PDF, DXF o de text abans de col·locar-lo; desactivat: s’usen les últimes opcions triades Stylistic Alternates Alternatives estilístiques + Ligatures Lligadures + Ornaments Ornaments + Figures Xifres Swash Volada Swatch Conflict Conflicte de mostres Swatch Conflicts Conflictes de mostres @@ -5713,6 +5732,27 @@ digits Malayalam Malaiàlam @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un quadre de diàleg no es pot obrir dins d'una crida de retorn d'una funció integrada, un getter, una conversió o un fitxer que executa $.evalFile; crideu-lo des del codi propi de l'script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la resposta següent d'`answers` és per a {_1}, no per a {name} @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no queden respostes per a aquest quadre de diàleg +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` conté {n} resposta que l'script no ha utilitzat|`answers` conté {n} respostes que l'script no ha utilitzat +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha deixat {n} objecte sota el pinzell sense canvis ({_2}): només remodela traçats|{_1} ha deixat {n} objectes sota el pinzell sense canvis ({_2}): només remodela traçats +liquify-tool Warp Deformació +liquify-tool Twirl Remolí +liquify-tool Pucker Arrufament +liquify-tool Bloat Inflament +liquify-tool Scallop Festonat +liquify-tool Crystallize Cristal·lització +liquify-tool Wrinkle Arruga +liquify-kind graphs gràfics +liquify-kind type text +liquify-kind symbols símbols +liquify-kind images imatges +liquify-kind meshes malles +liquify-kind envelopes embolcalls +liquify-kind repeats repeticions +liquify-kind placed documents documents col·locats +liquify-kind blends fusions +liquify-list-two {0}, {1} {0} i {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} i {1} @msg vc.document{place} is too large for a script vc.document{place} és massa gran per a un script @msg vc.log: the log of this run is full vc.log: el registre d'aquesta execució és ple @msg this function's script run has ended l'execució de l'script d'aquesta funció ha acabat @@ -6550,6 +6590,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 @@ -7566,6 +7608,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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ba95f3518a..8132a2a8b7 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ů @@ -2109,6 +2110,9 @@ digits Malayalam Malajálamské Select text to set its OpenType features. Vyberte text, abyste mohli nastavit jeho funkce OpenType. Standard Ligatures Standardní ligatury Stylistic Alternates Stylistické alternativy + Ligatures Ligatury + Ornaments Ornamenty + Figures Číslice Swash Ozdobné tvary Tabular Lining Tabulkové verzálkové Tabular Oldstyle Tabulkové minuskové @@ -2647,6 +2651,18 @@ digits Malayalam Malajálamské Author Title: Funkce autora: Author: Autor: Copyright Info URL: URL informací o autorských právech: + Save Metadata Template… Uložit šablonu metadat… + Import Options Možnosti importu + Clear existing fields and use the template's Vymazat stávající pole a použít pole ze šablony + Keep existing fields, but replace those the template has Zachovat stávající pole, ale nahradit ta, která šablona obsahuje + Keep existing fields, but append those the template has Zachovat stávající pole, ale připojit ta, která šablona obsahuje +@msg the template name can't be empty název šablony nesmí být prázdný +@msg the template name isn't usable as a file name název šablony nelze použít jako název souboru +@msg no metadata templates folder here zde není žádná složka šablon metadat +@msg give `name` or `path`, not both zadejte `name` nebo `path`, ne obojí +@msg give one of `path`, `name` and `data` zadejte jeden z parametrů `path`, `name` a `data` +@msg mode must be replace, keep or append režim musí být replace, keep nebo append +@msg the file is not an XMP metadata template soubor není šablona metadat XMP Copyright Notice: Upozornění o autorských právech: Copyright Status: Stav autorských práv: Created: Vytvořeno: @@ -3698,6 +3714,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 @@ -4802,6 +4820,27 @@ imageTrace Outline Obrys @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog se nemůže otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; zavolejte jej z vlastního kódu skriptu @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: další odpověď v `answers` je pro {_1}, ne pro {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` už nemá pro tento dialog žádnou odpověď +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use V `answers` je {n} odpověď, kterou skript nepoužil|V `answers` jsou {n} odpovědi, které skript nepoužil|V `answers` je {n} odpovědí, které skript nepoužil +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ponechal {n} objekt pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objekty pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objektů pod štětcem beze změny ({_2}): mění pouze cesty +liquify-tool Warp Nástroj Pokřivení +liquify-tool Twirl Nástroj Zatočení +liquify-tool Pucker Nástroj Smrštění +liquify-tool Bloat Nástroj Vyboulení +liquify-tool Scallop Nástroj Vroubkování +liquify-tool Crystallize Nástroj Krystalizace +liquify-tool Wrinkle Nástroj Zvrásnění +liquify-kind graphs grafy +liquify-kind type text +liquify-kind symbols symboly +liquify-kind images obrazy +liquify-kind meshes sítě +liquify-kind envelopes obálky +liquify-kind repeats opakování +liquify-kind placed documents umístěné dokumenty +liquify-kind blends prolnutí +liquify-list-two {0}, {1} {0} a {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} a {1} @msg vc.document{place} is too large for a script vc.document{place} je pro skript příliš velký @msg vc.log: the log of this run is full vc.log: protokol tohoto běhu je plný @msg this function's script run has ended běh skriptu této funkce skončil @@ -5442,6 +5481,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. @@ -6294,6 +6335,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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ffd29e4570..fa89abec4a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -131,6 +131,27 @@ @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialog kan ikke åbne i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: det næste svar i `answers` er til {_1}, ikke til {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har intet svar tilbage til denne dialog +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar, som scriptet ikke brugte|`answers` har {n} svar, som scriptet ikke brugte +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lod {n} objekt under penslen være uændret ({_2}): det omformer kun kurver|{_1} lod {n} objekter under penslen være uændrede ({_2}): det omformer kun kurver +liquify-tool Warp Vridning +liquify-tool Twirl Hvirvel +liquify-tool Pucker Krymp +liquify-tool Bloat Opsvulm +liquify-tool Scallop Muslingekant +liquify-tool Crystallize Krystallisering +liquify-tool Wrinkle Rynke +liquify-kind graphs diagrammer +liquify-kind type tekst +liquify-kind symbols symboler +liquify-kind images billeder +liquify-kind meshes net +liquify-kind envelopes konvolutter +liquify-kind repeats gentagelser +liquify-kind placed documents placerede dokumenter +liquify-kind blends blandinger +liquify-list-two {0}, {1} {0} og {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} og {1} @msg vc.document{place} is too large for a script vc.document{place} er for stort til et script @msg vc.log: the log of this run is full vc.log: loggen for denne kørsel er fuld @msg this function's script run has ended denne funktions scriptkørsel er afsluttet @@ -1581,6 +1602,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 @@ -2532,6 +2554,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Markér tekst for at angive dens OpenType-funktioner. Standard Ligatures Standardligaturer Stylistic Alternates Stilistiske alternativer + Ligatures Ligaturer + Ornaments Ornamenter + Figures Cifre Set {n} Sæt {n} Swash Sving Tabular Lining Tabulære versalcifre @@ -3056,6 +3081,18 @@ digits Malayalam Malayalam Author Title: Forfattertitel: Author: Forfatter: Copyright Info URL: URL til ophavsretinfo: + Save Metadata Template… Gem metadataskabelon… + Import Options Importindstillinger + Clear existing fields and use the template's Ryd eksisterende felter, og brug skabelonens + Keep existing fields, but replace those the template has Behold eksisterende felter, men erstat dem, skabelonen har + Keep existing fields, but append those the template has Behold eksisterende felter, men tilføj dem, skabelonen har +@msg the template name can't be empty skabelonnavnet må ikke være tomt +@msg the template name isn't usable as a file name skabelonnavnet kan ikke bruges som filnavn +@msg no metadata templates folder here der er ingen mappe til metadataskabeloner her +@msg give `name` or `path`, not both angiv `name` eller `path`, ikke begge +@msg give one of `path`, `name` and `data` angiv én af `path`, `name` og `data` +@msg mode must be replace, keep or append tilstanden skal være replace, keep eller append +@msg the file is not an XMP metadata template filen er ikke en XMP-metadataskabelon Copyright Notice: Ophavsretserklæring: Copyright Status: Ophavsretstatus: Created: Oprettet: @@ -4045,6 +4082,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 @@ -5557,6 +5596,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} @@ -6331,6 +6372,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 @@ -7603,6 +7645,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 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4fd5ddd75b..a187dd41de 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -632,6 +632,18 @@ font-technology Variable Variabel Copy Width Point Breitenpunkt kopieren Copyright Copyright Copyright Info URL: URL für Copyright-Informationen: + Save Metadata Template… Metadatenvorlage speichern… + Import Options Importoptionen + Clear existing fields and use the template's Vorhandene Felder löschen und die der Vorlage verwenden + Keep existing fields, but replace those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen ersetzen + Keep existing fields, but append those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen anfügen +@msg the template name can't be empty der Vorlagenname darf nicht leer sein +@msg the template name isn't usable as a file name der Vorlagenname ist als Dateiname nicht verwendbar +@msg no metadata templates folder here hier gibt es keinen Ordner für Metadatenvorlagen +@msg give `name` or `path`, not both geben Sie `name` oder `path` an, nicht beides +@msg give one of `path`, `name` and `data` geben Sie einen der Parameter `path`, `name` und `data` an +@msg mode must be replace, keep or append der Modus muss replace, keep oder append sein +@msg the file is not an XMP metadata template die Datei ist keine XMP-Metadatenvorlage Copyright Notice: Copyright-Vermerk: Copyright Status: Copyright-Status: Copyright Symbol Copyright-Symbol @@ -1421,6 +1433,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 @@ -3639,6 +3653,9 @@ effect Points Punkte Show Import Options Importoptionen anzeigen Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Vor dem Platzieren nach den Importoptionen jeder PDF-, DXF- oder Textdatei fragen; aus: die zuletzt gewählten Optionen verwenden Stylistic Alternates Stilistische Varianten + Ligatures Ligaturen + Ornaments Ornamente + Figures Ziffern Swash Schwungschrift Swatch Conflict Farbfeldkonflikt Swatch Conflicts Farbfeldkonflikte @@ -4406,6 +4423,27 @@ theme Appearance Erscheinungsbild @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: Ein Dialog kann sich nicht in einem Callback einer integrierten Funktion, einem Getter, einer Umwandlung oder einer Datei öffnen, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: Die nächste Antwort in `answers` ist für {_1}, nicht für {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` hat keine Antwort mehr für diesen Dialog +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` enthält {n} Antwort, die das Skript nicht verwendet hat|`answers` enthält {n} Antworten, die das Skript nicht verwendet hat +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ließ {n} Objekt unter dem Pinsel unverändert ({_2}): es formt nur Pfade um|{_1} ließ {n} Objekte unter dem Pinsel unverändert ({_2}): es formt nur Pfade um +liquify-tool Warp Verkrümmung +liquify-tool Twirl Strudel +liquify-tool Pucker Zusammenziehen +liquify-tool Bloat Aufblasen +liquify-tool Scallop Ausbuchten +liquify-tool Crystallize Kristallisieren +liquify-tool Wrinkle Zerknittern +liquify-kind graphs Diagramme +liquify-kind type Text +liquify-kind symbols Symbole +liquify-kind images Bilder +liquify-kind meshes Gitter +liquify-kind envelopes Hüllen +liquify-kind repeats Wiederholungen +liquify-kind placed documents platzierte Dokumente +liquify-kind blends Angleichungen +liquify-list-two {0}, {1} {0} und {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} und {1} @msg vc.document{place} is too large for a script vc.document{place} ist zu groß für ein Skript @msg vc.log: the log of this run is full vc.log: Das Protokoll dieses Laufs ist voll @msg this function's script run has ended der Skriptlauf dieser Funktion ist beendet @@ -5048,6 +5086,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. @@ -5507,6 +5547,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 @@ -5876,6 +5917,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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e1cd94ab80..9d2ecb78fa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -613,6 +613,18 @@ font-technology Variable Μεταβλητές Copy Width Point Αντιγραφή σημείου πλάτους Copyright Πνευματικά δικαιώματα Copyright Info URL: URL πληροφοριών πνευματικών δικαιωμάτων: + Save Metadata Template… Αποθήκευση προτύπου μεταδεδομένων… + Import Options Επιλογές εισαγωγής + Clear existing fields and use the template's Απαλοιφή των υπαρχόντων πεδίων και χρήση εκείνων του προτύπου + Keep existing fields, but replace those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά αντικατάσταση όσων έχει το πρότυπο + Keep existing fields, but append those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά προσθήκη όσων έχει το πρότυπο +@msg the template name can't be empty το όνομα του προτύπου δεν μπορεί να είναι κενό +@msg the template name isn't usable as a file name το όνομα του προτύπου δεν μπορεί να χρησιμοποιηθεί ως όνομα αρχείου +@msg no metadata templates folder here δεν υπάρχει φάκελος προτύπων μεταδεδομένων εδώ +@msg give `name` or `path`, not both δώστε `name` ή `path`, όχι και τα δύο +@msg give one of `path`, `name` and `data` δώστε ένα από τα `path`, `name` και `data` +@msg mode must be replace, keep or append η λειτουργία πρέπει να είναι replace, keep ή append +@msg the file is not an XMP metadata template το αρχείο δεν είναι πρότυπο μεταδεδομένων XMP Copyright Notice: Σημείωση πνευματικών δικαιωμάτων: Copyright Status: Κατάσταση πνευματικών δικαιωμάτων: Copyright Symbol Σύμβολο πνευματικών δικαιωμάτων @@ -1353,6 +1365,8 @@ font-technology Variable Μεταβλητές Graph Γράφημα Graph Data Δεδομένα γραφήματος Graph Type Τύπος γραφήματος + Graph Type… Τύπος γραφήματος… + Graph Data… Δεδομένα γραφήματος… Graph Options Επιλογές γραφήματος Left Axis Αριστερός άξονας Right Axis Δεξιός άξονας @@ -2212,6 +2226,9 @@ font-technology Variable Μεταβλητές Superscript Εκθέτης Superscript: Εκθέτης: Stylistic Alternates Εναλλακτικοί χαρακτήρες στυλ + Ligatures Συμπλέγματα χαρακτήρων + Ornaments Κοσμήματα + Figures Αριθμοί Swash Διακοσμητικά τελειώματα Swatches Δείγματα χρωμάτων New Group Νέα ομάδα @@ -2486,6 +2503,27 @@ axis Both Και τα δύο @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου δεν μπορεί να ανοίξει μέσα σε επανάκληση ενσωματωμένης συνάρτησης, getter, μετατροπή ή αρχείο που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: η επόμενη απάντηση στο `answers` είναι για το {_1}, όχι για το {name} @msg {name}: `answers` has no answer left for this dialog {name}: το `answers` δεν έχει άλλη απάντηση για αυτό το παράθυρο διαλόγου +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Το `answers` περιέχει {n} απάντηση που δεν χρησιμοποίησε το σενάριο|Το `answers` περιέχει {n} απαντήσεις που δεν χρησιμοποίησε το σενάριο +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only Το {_1} άφησε {n} αντικείμενο κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές|Το {_1} άφησε {n} αντικείμενα κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές +liquify-tool Warp εργαλείο Παραμόρφωση +liquify-tool Twirl εργαλείο Στροβιλισμός +liquify-tool Pucker εργαλείο Συρρίκνωση +liquify-tool Bloat εργαλείο Διόγκωση +liquify-tool Scallop εργαλείο Κυματιστά άκρα +liquify-tool Crystallize εργαλείο Κρυσταλλοποίηση +liquify-tool Wrinkle εργαλείο Πτυχώσεις +liquify-kind graphs γραφήματα +liquify-kind type κείμενο +liquify-kind symbols σύμβολα +liquify-kind images εικόνες +liquify-kind meshes πλέγματα +liquify-kind envelopes περιβλήματα +liquify-kind repeats επαναλήψεις +liquify-kind placed documents τοποθετημένα έγγραφα +liquify-kind blends αναμείξεις +liquify-list-two {0}, {1} {0} και {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} και {1} @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 η εκτέλεση σεναρίου αυτής της συνάρτησης έχει τελειώσει @@ -2730,6 +2768,7 @@ effect Soft Απαλό Change Panel Layout Αλλαγή διάταξης πάνελ Close Panel Κλείσιμο πάνελ Collapse Panel Group Σύμπτυξη ομάδας πάνελ + Cycle Display Sizes Εναλλαγή μεγεθών εμφάνισης Move Panel Μετακίνηση πάνελ Group with Ομαδοποίηση με Resize panels Αλλαγή μεγέθους πάνελ @@ -5088,6 +5127,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. Οι προτιμήσεις εισήχθησαν. @@ -6162,6 +6203,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} περιέχει χαρακτήρες ελέγχου @@ -7539,6 +7581,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 Καμία πρόταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f920bdf877..fde6ff74ee 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -654,6 +654,18 @@ font-technology Variable Variables Copy Width Point Copiar punto de anchura Copyright Copyright Copyright Info URL: URL de información de copyright: + Save Metadata Template… Guardar plantilla de metadatos… + Import Options Opciones de importación + Clear existing fields and use the template's Borrar los campos existentes y usar los de la plantilla + Keep existing fields, but replace those the template has Conservar los campos existentes, pero reemplazar los que tenga la plantilla + Keep existing fields, but append those the template has Conservar los campos existentes, pero añadir los que tenga la plantilla +@msg the template name can't be empty el nombre de la plantilla no puede estar vacío +@msg the template name isn't usable as a file name el nombre de la plantilla no se puede usar como nombre de archivo +@msg no metadata templates folder here aquí no hay ninguna carpeta de plantillas de metadatos +@msg give `name` or `path`, not both indique `name` o `path`, no ambos +@msg give one of `path`, `name` and `data` indique uno de `path`, `name` y `data` +@msg mode must be replace, keep or append el modo debe ser replace, keep o append +@msg the file is not an XMP metadata template el archivo no es una plantilla de metadatos XMP Copyright Notice: Aviso de copyright: Copyright Status: Estado de copyright: Copyright Symbol Símbolo de copyright @@ -1432,6 +1444,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 @@ -3669,6 +3683,9 @@ digits Malayalam Malayálam Show Import Options Mostrar opciones de importación Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Preguntar las opciones de importación de cada archivo PDF, DXF o de texto antes de colocarlo; desactivado: usar las últimas opciones elegidas Stylistic Alternates Alternativas estilísticas + Ligatures Ligaduras + Ornaments Ornamentos + Figures Cifras Swash Decorativa Swatch Conflict Conflicto de muestras Swatch Conflicts Conflictos de muestras @@ -4484,6 +4501,27 @@ axis Both Ambos @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo no puede abrirse dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la siguiente respuesta de `answers` es para {_1}, no para {name} @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no le quedan respuestas para este cuadro de diálogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} respuesta que el script no usó|`answers` contiene {n} respuestas que el script no usó +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} dejó {n} objeto bajo el pincel sin cambios ({_2}): solo modifica trazados|{_1} dejó {n} objetos bajo el pincel sin cambios ({_2}): solo modifica trazados +liquify-tool Warp Deformar +liquify-tool Twirl Molinete +liquify-tool Pucker Fruncir +liquify-tool Bloat Engordar +liquify-tool Scallop Festonear +liquify-tool Crystallize Cristalizar +liquify-tool Wrinkle Arrugar +liquify-kind graphs gráficos +liquify-kind type texto +liquify-kind symbols símbolos +liquify-kind images imágenes +liquify-kind meshes mallas +liquify-kind envelopes envolventes +liquify-kind repeats repeticiones +liquify-kind placed documents documentos colocados +liquify-kind blends fusiones +liquify-list-two {0}, {1} {0}, {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0}, {1} @msg vc.document{place} is too large for a script vc.document{place} es demasiado grande para un script @msg vc.log: the log of this run is full vc.log: el registro de esta ejecución está lleno @msg this function's script run has ended la ejecución del script de esta función ha terminado @@ -5138,6 +5176,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. @@ -5513,6 +5553,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 @@ -6249,6 +6290,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 @@ -7643,6 +7685,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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1096d83057..fedfd1479d 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 @@ -2070,6 +2071,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Valitse teksti, jonka OpenType-ominaisuudet haluat asettaa. Standard Ligatures Vakioligatuurit Stylistic Alternates Tyylivaihtoehdot + Ligatures Ligatuurit + Ornaments Ornamentit + Figures Numerot Swash Koukerot Tabular Lining Taulukkonumerot Tabular Oldstyle Vanhanaikaiset taulukkonumerot @@ -2602,6 +2606,18 @@ digits Malayalam Malajalam Author Title: Tekijän titteli: Author: Tekijä: Copyright Info URL: Tekijänoikeustietojen URL: + Save Metadata Template… Tallenna metatietomallipohja… + Import Options Tuontiasetukset + Clear existing fields and use the template's Tyhjennä nykyiset kentät ja käytä mallipohjan kenttiä + Keep existing fields, but replace those the template has Säilytä nykyiset kentät, mutta korvaa mallipohjassa olevat + Keep existing fields, but append those the template has Säilytä nykyiset kentät, mutta lisää mallipohjassa olevat +@msg the template name can't be empty mallipohjan nimi ei voi olla tyhjä +@msg the template name isn't usable as a file name mallipohjan nimeä ei voi käyttää tiedostonimenä +@msg no metadata templates folder here täällä ei ole metatietomallipohjien kansiota +@msg give `name` or `path`, not both anna `name` tai `path`, ei molempia +@msg give one of `path`, `name` and `data` anna yksi seuraavista: `path`, `name` ja `data` +@msg mode must be replace, keep or append tilan on oltava replace, keep tai append +@msg the file is not an XMP metadata template tiedosto ei ole XMP-metatietomallipohja Copyright Notice: Tekijänoikeusilmoitus: Copyright Status: Tekijänoikeuden tila: Created: Luotu: @@ -3636,6 +3652,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 @@ -4716,6 +4734,27 @@ imageTrace Outline Ääriviiva @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: valintaikkuna ei voi avautua sisäänrakennetun funktion takaisinkutsussa, getterissä, muunnoksessa tai tiedostossa, jonka $.evalFile ajaa; kutsu sitä skriptin omasta koodista @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: seuraava vastaus kohteessa `answers` on kohteelle {_1}, ei kohteelle {name} @msg {name}: `answers` has no answer left for this dialog {name}: kohteessa `answers` ei ole enää vastausta tälle valintaikkunalle +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` sisältää {n} vastauksen, jota komentosarja ei käyttänyt|`answers` sisältää {n} vastausta, joita komentosarja ei käyttänyt +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} jätti {n} objektin siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja|{_1} jätti {n} objektia siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja +liquify-tool Warp Vääristys +liquify-tool Twirl Pyöritys +liquify-tool Pucker Rypistys +liquify-tool Bloat Pullistus +liquify-tool Scallop Simpukointi +liquify-tool Crystallize Kiteytys +liquify-tool Wrinkle Ryppyistys +liquify-kind graphs kaaviot +liquify-kind type teksti +liquify-kind symbols symbolit +liquify-kind images kuvat +liquify-kind meshes verkot +liquify-kind envelopes vääristyskuoret +liquify-kind repeats toistot +liquify-kind placed documents sijoitetut asiakirjat +liquify-kind blends sulautukset +liquify-list-two {0}, {1} {0} ja {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} ja {1} @msg vc.document{place} is too large for a script vc.document{place} on liian suuri skriptille @msg vc.log: the log of this run is full vc.log: tämän ajon loki on täynnä @msg this function's script run has ended tämän funktion skriptiajo on päättynyt @@ -5353,6 +5392,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. @@ -6172,6 +6213,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ä @@ -7620,6 +7662,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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c68bc7049e..f3a2fc34c3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -654,6 +654,18 @@ font-technology Variable Variables Copy to User Defined Copier dans Défini par l’utilisateur Copy Width Point Copier le point de largeur Copyright Copyright + Save Metadata Template… Enregistrer le modèle de métadonnées… + Import Options Options d’importation + Clear existing fields and use the template's Effacer les champs existants et utiliser ceux du modèle + Keep existing fields, but replace those the template has Conserver les champs existants, mais remplacer ceux que contient le modèle + Keep existing fields, but append those the template has Conserver les champs existants, mais ajouter ceux que contient le modèle +@msg the template name can't be empty le nom du modèle ne peut pas être vide +@msg the template name isn't usable as a file name le nom du modèle n'est pas utilisable comme nom de fichier +@msg no metadata templates folder here aucun dossier de modèles de métadonnées ici +@msg give `name` or `path`, not both indiquez `name` ou `path`, pas les deux +@msg give one of `path`, `name` and `data` indiquez un seul des paramètres `path`, `name` et `data` +@msg mode must be replace, keep or append le mode doit être replace, keep ou append +@msg the file is not an XMP metadata template le fichier n’est pas un modèle de métadonnées XMP Copyright Info URL: URL des informations de copyright : Copyright Notice: Mention de copyright : Copyright Status: État du copyright : @@ -1426,6 +1438,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 @@ -3661,6 +3675,9 @@ digits Malayalam Malayalam Show Import Options Afficher les options d’importation Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demander les options d’importation de chaque fichier PDF, DXF ou texte avant de le placer, sinon utiliser les dernières options choisies Stylistic Alternates Variantes stylistiques + Ligatures Ligatures + Ornaments Ornements + Figures Chiffres Swash Lettres ornées Swatch Conflict Conflit de nuances Swatch Conflicts Conflits de nuances @@ -4473,6 +4490,27 @@ axis Both Les deux @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue ne peut pas s'ouvrir dans un rappel d'une fonction intégrée, un accesseur, une conversion ou un fichier que $.evalFile exécute ; appelez-la depuis le code du script lui-même @msg {name}: the next answer in `answers` is for {_1}, not {name} {name} : la réponse suivante de `answers` est pour {_1}, pas pour {name} @msg {name}: `answers` has no answer left for this dialog {name} : `answers` n'a plus de réponse pour cette boîte de dialogue +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contient {n} réponse que le script n'a pas utilisée|`answers` contient {n} réponses que le script n'a pas utilisées +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} a laissé {n} objet sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés|{_1} a laissé {n} objets sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés +liquify-tool Warp Déformation +liquify-tool Twirl Tourbillon +liquify-tool Pucker Contraction +liquify-tool Bloat Dilatation +liquify-tool Scallop Feston +liquify-tool Crystallize Cristallisation +liquify-tool Wrinkle Fronces +liquify-kind graphs graphes +liquify-kind type texte +liquify-kind symbols symboles +liquify-kind images images +liquify-kind meshes filets +liquify-kind envelopes enveloppes +liquify-kind repeats répétitions +liquify-kind placed documents documents importés +liquify-kind blends dégradés de formes +liquify-list-two {0}, {1} {0} et {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} et {1} @msg vc.document{place} is too large for a script vc.document{place} est trop volumineux pour un script @msg vc.log: the log of this run is full vc.log : le journal de cette exécution est plein @msg this function's script run has ended l'exécution du script de cette fonction est terminée @@ -5115,6 +5153,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. @@ -5509,6 +5549,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 @@ -6289,6 +6330,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 diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index e7f1db32f0..19ba3fb7d2 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 ક્રમમાં ગોઠવો @@ -761,6 +762,12 @@ Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: + Templates ટેમ્પલેટ + Save Metadata Template… મેટાડેટા ટેમ્પલેટ સાચવો… + Import Options આયાત વિકલ્પો + Clear existing fields and use the template's હાલના ફીલ્ડ સાફ કરો અને ટેમ્પલેટના ફીલ્ડ વાપરો + Keep existing fields, but replace those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે બદલો + Keep existing fields, but append those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે ઉમેરો Copyright Notice: કૉપીરાઇટ સૂચના: Copyright Status: કૉપીરાઇટ સ્થિતિ: Copyright Symbol કૉપીરાઇટ ચિહ્ન @@ -1548,6 +1555,8 @@ Graph Design ગ્રાફ ડિઝાઇન Graph Marker ગ્રાફ માર્કર Graph Type ગ્રાફ પ્રકાર + Graph Type… ગ્રાફ પ્રકાર… + Graph Data… ગ્રાફ ડેટા… Graph Options ગ્રાફ વિકલ્પો Left Axis ડાબી અક્ષ Right Axis જમણી અક્ષ @@ -3771,6 +3780,9 @@ Styling: સ્ટાઇલિંગ: Stylistic સ્ટાઇલિસ્ટિક Stylistic Alternates સ્ટાઇલિસ્ટિક વિકલ્પી + Ligatures લિગેચર્સ + Ornaments અલંકારો + Figures અંકો Stylistic Sets સ્ટાઇલિસ્ટિક સેટ Stylize સ્ટાઇલાઇઝ Subdivisions ઉપવિભાગો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index f104f2f1f7..37ce1144c9 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 कोलेट @@ -1084,6 +1085,18 @@ antiAlias Sharp शार्प Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: + Save Metadata Template… मेटाडेटा टेम्पलेट सेव करें… + Import Options इम्पोर्ट विकल्प + Clear existing fields and use the template's मौजूदा फ़ील्ड साफ़ करें और टेम्पलेट के फ़ील्ड उपयोग करें + Keep existing fields, but replace those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड बदलें + Keep existing fields, but append those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड जोड़ें +@msg the template name can't be empty टेम्पलेट का नाम खाली नहीं हो सकता +@msg the template name isn't usable as a file name टेम्पलेट का नाम फ़ाइल नाम के रूप में उपयोग नहीं किया जा सकता +@msg no metadata templates folder here यहाँ कोई मेटाडेटा टेम्पलेट फ़ोल्डर नहीं है +@msg give `name` or `path`, not both `name` या `path` दें, दोनों नहीं +@msg give one of `path`, `name` and `data` `path`, `name` और `data` में से एक दें +@msg mode must be replace, keep or append मोड replace, keep या append होना चाहिए +@msg the file is not an XMP metadata template फ़ाइल XMP मेटाडेटा टेम्पलेट नहीं है Copyright Notice: कॉपीराइट सूचना: Copyright Status: कॉपीराइट स्थिति: Copyright Symbol कॉपीराइट सिंबल @@ -2125,6 +2138,8 @@ antiAlias Sharp शार्प Graph Design ग्राफ़ डिजाइन Graph Marker ग्राफ़ मार्कर Graph Type ग्राफ़ टाइप + Graph Type… ग्राफ़ टाइप… + Graph Data… ग्राफ़ डेटा… Graph Options ग्राफ़ विकल्प Left Axis बायाँ एक्सिस Right Axis दायाँ एक्सिस @@ -4318,6 +4333,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 सेव किए गए @@ -5016,6 +5032,9 @@ antiAlias Sharp शार्प Styling: स्टाइल: Stylistic स्टाइलिस्ट Stylistic Alternates शैलीगत ऑप्शन + Ligatures लिगेचर + Ornaments अलंकरण + Figures अंक Stylistic Sets स्टाइलिस्टिक सेट्स Stylize शैलीबद्ध करें Subdivisions उप-विभाजन @@ -6826,6 +6845,27 @@ antiAlias Sharp शार्प @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: कोई डायलॉग किसी बिल्ट-इन फ़ंक्शन के कॉलबैक, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` में अगला उत्तर {_1} के लिए है, {name} के लिए नहीं @msg {name}: `answers` has no answer left for this dialog {name}: `answers` में इस डायलॉग के लिए कोई उत्तर नहीं बचा है +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` में {n} उत्तर है जिसका स्क्रिप्ट ने उपयोग नहीं किया|`answers` में {n} उत्तर हैं जिनका स्क्रिप्ट ने उपयोग नहीं किया +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ने ब्रश के नीचे {n} ऑब्जेक्ट को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ को नया आकार देता है|{_1} ने ब्रश के नीचे {n} ऑब्जेक्ट्स को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ्स को नया आकार देता है +liquify-tool Warp वार्प टूल +liquify-tool Twirl ट्वर्ल टूल +liquify-tool Pucker सिकोड़ें टूल +liquify-tool Bloat फुलाएँ टूल +liquify-tool Scallop स्कैलप टूल +liquify-tool Crystallize क्रिस्टलीकरण टूल +liquify-tool Wrinkle शिकन टूल +liquify-kind graphs ग्राफ़ +liquify-kind type टाइप +liquify-kind symbols सिंबल्स +liquify-kind images चित्र +liquify-kind meshes मेश +liquify-kind envelopes एन्वेलप्स +liquify-kind repeats दोहराव +liquify-kind placed documents प्लेस्ड डॉक्यूमेंट्स +liquify-kind blends ब्लेंड्स +liquify-list-two {0}, {1} {0} और {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} और {1} @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 इस फ़ंक्शन का स्क्रिप्ट रन समाप्त हो गया है @@ -8628,6 +8668,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}`; कमांड कोई पैरामीटर नहीं लेता है @@ -8977,6 +9019,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 कोई सुझाव नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index b8c39afb5f..02768350c5 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 @@ -853,6 +854,18 @@ font-technology Variable Változó Copyright Szerzői jog Copyright and Contact Info Szerzői jogi és kapcsolati adatok Copyright Info URL: Szerzői jogi információ URL-je: + Save Metadata Template… Metaadatsablon mentése… + Import Options Importálási beállítások + Clear existing fields and use the template's Meglévő mezők törlése és a sablon mezőinek használata + Keep existing fields, but replace those the template has Meglévő mezők megtartása, de a sablonban szereplők cseréje + Keep existing fields, but append those the template has Meglévő mezők megtartása, de a sablonban szereplők hozzáfűzése +@msg the template name can't be empty a sablon neve nem lehet üres +@msg the template name isn't usable as a file name a sablon neve nem használható fájlnévként +@msg no metadata templates folder here itt nincs metaadatsablon-mappa +@msg give `name` or `path`, not both adja meg a `name` vagy a `path` paramétert, de ne mindkettőt +@msg give one of `path`, `name` and `data` adja meg a `path`, a `name` és a `data` paraméterek egyikét +@msg mode must be replace, keep or append a mód értéke replace, keep vagy append lehet +@msg the file is not an XMP metadata template a fájl nem XMP-metaadatsablon Copyright Notice: Szerzői jogi közlemény: Copyright Status: Szerzői jogi állapot: Copyright Symbol Szerzői jogi jel @@ -1784,6 +1797,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 @@ -4364,6 +4379,9 @@ mark-style Japanese Japán Show Import Options Importálási beállítások megjelenítése Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Elhelyezés előtt rákérdez minden PDF-, DXF- vagy szövegfájl importálási beállításaira; kikapcsolva a legutóbb választott beállításokat használja Stylistic Alternates Stilisztikai változatok + Ligatures Ligatúrák + Ornaments Díszek + Figures Számjegyek Swash Cifra változatok Swatch Conflict Színminta-ütközés Swatch Conflicts Színminta-ütközések @@ -5304,6 +5322,27 @@ imageTrace Outline Körvonal @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: párbeszédpanel nem nyílhat meg beépített függvény visszahívásában, getterben, átalakításban vagy a $.evalFile által futtatott fájlban; hívja a parancsfájl saját kódjából @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a következő válasz az `answers` listában ehhez tartozik: {_1}, nem ehhez: {name} @msg {name}: `answers` has no answer left for this dialog {name}: az `answers` listában nem maradt válasz ehhez a párbeszédpanelhez +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Az `answers` listában {n} válasz maradt, amelyet a parancsfájl nem használt fel +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}: az ecset alatt {n} objektum változatlan maradt ({_2}); csak útvonalakat alakít át +liquify-tool Warp Hajlítás +liquify-tool Twirl Örvénylés +liquify-tool Pucker Összehúzás +liquify-tool Bloat Felfújás +liquify-tool Scallop Csipkézés +liquify-tool Crystallize Kristályosítás +liquify-tool Wrinkle Gyűrés +liquify-kind graphs grafikonok +liquify-kind type szöveg +liquify-kind symbols szimbólumok +liquify-kind images képek +liquify-kind meshes rácsok +liquify-kind envelopes burkolók +liquify-kind repeats ismétlések +liquify-kind placed documents elhelyezett dokumentumok +liquify-kind blends összemosások +liquify-list-two {0}, {1} {0} és {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} és {1} @msg vc.document{place} is too large for a script a vc.document{place} túl nagy egy parancsfájlhoz @msg vc.log: the log of this run is full vc.log: ennek a futásnak a naplója megtelt @msg this function's script run has ended ennek a függvénynek a parancsfájl-futása véget ért @@ -5957,6 +5996,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. @@ -6278,6 +6319,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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 77fa1558b6..c713ebf880 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 @@ -1866,6 +1867,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Pilih teks untuk mengatur fitur OpenType-nya. Standard Ligatures Ligatur standar Stylistic Alternates Alternatif gaya + Ligatures Ligatur + Ornaments Ornamen + Figures Angka Set {n} Set {n} Swash Swash Tabular Lining Lining tabular @@ -2390,6 +2394,11 @@ digits Malayalam Malayalam Author Title: Judul penulis: Author: Penulis: Copyright Info URL: URL info hak cipta: + Save Metadata Template… Simpan templat metadata… + Import Options Opsi impor + Clear existing fields and use the template's Hapus bidang yang ada dan gunakan bidang templat + Keep existing fields, but replace those the template has Pertahankan bidang yang ada, tetapi ganti bidang yang dimiliki templat + Keep existing fields, but append those the template has Pertahankan bidang yang ada, tetapi tambahkan bidang yang dimiliki templat Copyright Notice: Pemberitahuan hak cipta: Copyright Status: Status hak cipta: Created: Dibuat: @@ -3379,6 +3388,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 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ee3608f57d..cb506f22dd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -654,6 +654,18 @@ font-technology Variable Variabili Copy Width Point Copia punto di larghezza Copyright Copyright Copyright Info URL: URL informazioni copyright: + Save Metadata Template… Salva modello di metadati… + Import Options Opzioni di importazione + Clear existing fields and use the template's Cancella i campi esistenti e usa quelli del modello + Keep existing fields, but replace those the template has Mantieni i campi esistenti, ma sostituisci quelli presenti nel modello + Keep existing fields, but append those the template has Mantieni i campi esistenti, ma aggiungi quelli presenti nel modello +@msg the template name can't be empty il nome del modello non può essere vuoto +@msg the template name isn't usable as a file name il nome del modello non è utilizzabile come nome di file +@msg no metadata templates folder here qui non c'è una cartella dei modelli di metadati +@msg give `name` or `path`, not both indica `name` o `path`, non entrambi +@msg give one of `path`, `name` and `data` indica uno tra `path`, `name` e `data` +@msg mode must be replace, keep or append la modalità deve essere replace, keep o append +@msg the file is not an XMP metadata template il file non è un modello di metadati XMP Copyright Notice: Nota sul copyright: Copyright Status: Stato copyright: Copyright Symbol Simbolo di copyright @@ -1451,6 +1463,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 @@ -3715,6 +3729,9 @@ digits Malayalam Malayalam Show Import Options Mostra opzioni di importazione Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Chiedi le opzioni di importazione di ogni file PDF, DXF o di testo prima di inserirlo; disattivato: usa le ultime opzioni scelte Stylistic Alternates Alternative stilistiche + Ligatures Legature + Ornaments Ornamenti + Figures Cifre Swash Ornamentale Swatch Conflict Conflitto campioni Swatch Conflicts Conflitti campioni @@ -4536,6 +4553,27 @@ axis Both Entrambi @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo non può aprirsi dentro un callback di una funzione integrata, un getter, una conversione o un file eseguito da $.evalFile; chiamala dal codice dello script stesso @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la prossima risposta in `answers` è per {_1}, non per {name} @msg {name}: `answers` has no answer left for this dialog {name}: in `answers` non rimangono risposte per questa finestra di dialogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} risposta che lo script non ha usato|`answers` contiene {n} risposte che lo script non ha usato +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha lasciato {n} oggetto sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati|{_1} ha lasciato {n} oggetti sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati +liquify-tool Warp Altera +liquify-tool Twirl Vortice +liquify-tool Pucker Contrai +liquify-tool Bloat Gonfia +liquify-tool Scallop Smerla +liquify-tool Crystallize Cristallizza +liquify-tool Wrinkle Grinza +liquify-kind graphs grafici +liquify-kind type testo +liquify-kind symbols simboli +liquify-kind images immagini +liquify-kind meshes trame +liquify-kind envelopes involucri +liquify-kind repeats ripetizioni +liquify-kind placed documents documenti inseriti +liquify-kind blends fusioni +liquify-list-two {0}, {1} {0} e {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} e {1} @msg vc.document{place} is too large for a script vc.document{place} è troppo grande per uno script @msg vc.log: the log of this run is full vc.log: il registro di questa esecuzione è pieno @msg this function's script run has ended l'esecuzione dello script di questa funzione è terminata @@ -5177,6 +5215,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. @@ -5554,6 +5594,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 @@ -5913,6 +5954,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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 64975404a7..f7cc60779b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1386,6 +1386,18 @@ antiAlias Sharp シャープ Copy Width Point 幅ポイントをコピー Copyright 著作権 Copyright Info URL: 著作権情報の URL: + Save Metadata Template… メタデータテンプレートを保存… + Import Options 読み込みオプション + Clear existing fields and use the template's 既存のフィールドを消去してテンプレートのフィールドを使用 + Keep existing fields, but replace those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを置換 + Keep existing fields, but append those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを追加 +@msg the template name can't be empty テンプレート名は空にできません +@msg the template name isn't usable as a file name テンプレート名はファイル名として使用できません +@msg no metadata templates folder here ここにはメタデータテンプレートのフォルダーがありません +@msg give `name` or `path`, not both `name` と `path` のどちらか一方を指定してください +@msg give one of `path`, `name` and `data` `path`、`name`、`data` のいずれか 1 つを指定してください +@msg mode must be replace, keep or append モードは replace、keep、append のいずれかにしてください +@msg the file is not an XMP metadata template このファイルは XMP メタデータテンプレートではありません Copyright Notice: 著作権表示: Copyright Status: 著作権の状態: Corner Point Angle Threshold: コーナーポイントの角度のしきい値: @@ -3415,6 +3427,9 @@ mark-style Japanese 日本式 Swap Fill and Stroke 塗りと線を入れ替え Swap start and end arrowheads 始点と終点の矢印を入れ替え Stylistic Alternates スタイル代替字 + Ligatures 合字 + Ornaments 装飾 + Figures 数字 Swash スワッシュ Swatch Conflict スウォッチの競合 Swatch Conflicts スウォッチの競合 @@ -3877,6 +3892,8 @@ file-filter Templates テンプレート Gradient (. or Shift+.) グラデーション (. または Shift+.) Graph Data グラフデータ Graph Type グラフの種類 + Graph Type… グラフの種類… + Graph Data… グラフデータ… Graph Options グラフオプション Left Axis 左軸 Right Axis 右軸 @@ -5114,6 +5131,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} をダウンロードしました @@ -5301,6 +5320,27 @@ swatch Bright Violet ビビッドバイオレット @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数のコールバック、getter、変換、または $.evalFile が実行するファイルの中ではダイアログを開けません。スクリプト自身のコードから呼び出してください @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` の次の回答は {name} ではなく {_1} のものです @msg {name}: `answers` has no answer left for this dialog {name}: `answers` にこのダイアログの回答が残っていません +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` にスクリプトが使用しなかった回答が {n} 件あります +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} はブラシの下にある {n} 個のオブジェクトを変更せずに残しました({_2})。パスのみを変形します +liquify-tool Warp ワープ +liquify-tool Twirl 旋回 +liquify-tool Pucker 収縮 +liquify-tool Bloat 膨張 +liquify-tool Scallop ギザギザ +liquify-tool Crystallize 結晶化 +liquify-tool Wrinkle しわ +liquify-kind graphs グラフ +liquify-kind type テキスト +liquify-kind symbols シンボル +liquify-kind images 画像 +liquify-kind meshes メッシュ +liquify-kind envelopes エンベロープ +liquify-kind repeats リピート +liquify-kind placed documents 配置ドキュメント +liquify-kind blends ブレンド +liquify-list-two {0}, {1} {0}、{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}、{1} @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 この関数のスクリプトの実行は終了しています @@ -5597,6 +5637,7 @@ effect Vertical 垂直 Change Panel Layout パネルの配置を変更 Close Panel パネルを閉じる Collapse Panel Group パネルグループを折りたたむ + Cycle Display Sizes 表示サイズを切り替え Move Panel パネルを移動 Group with グループ化先 Resize panels パネルのサイズを変更 @@ -5958,6 +5999,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} に制御文字が含まれています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cd1917e66..5f67f5e862 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3008,6 +3008,7 @@ Change Panel Layout პანელების განლაგების შეცვლა Close Panel პანელის დახურვა Collapse Panel Group პანელების ჯგუფის აკეცვა + Cycle Display Sizes ჩვენების ზომების გადართვა Move Panel პანელის გადაადგილება Group with ერთად დაჯგუფება Resize panels პანელების ზომის შეცვლა @@ -3923,6 +3924,9 @@ digits Malayalam მალაიალამური Select text to set its OpenType features. OpenType შესაძლებლობების დასაყენებლად მონიშნეთ ტექსტი. Standard Ligatures სტანდარტული ლიგატურები Stylistic Alternates სტილისტური ალტერნატივები + Ligatures ლიგატურები + Ornaments ორნამენტები + Figures ციფრები Swash მოხატული ასოები (swash) Tabular Lining ცხრილური ხაზოვანი Tabular Oldstyle ცხრილური ძველებური @@ -4443,6 +4447,18 @@ digits Malayalam მალაიალამური Author Title: ავტორის თანამდებობა: Author: ავტორი: Copyright Info URL: საავტორო უფლების ინფორმაციის URL: + Save Metadata Template… მეტამონაცემების შაბლონის შენახვა… + Import Options იმპორტის პარამეტრები + Clear existing fields and use the template's არსებული ველების გასუფთავება და შაბლონის ველების გამოყენება + Keep existing fields, but replace those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების ჩანაცვლება + Keep existing fields, but append those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების დამატება +@msg the template name can't be empty შაბლონის სახელი ცარიელი ვერ იქნება +@msg the template name isn't usable as a file name შაბლონის სახელი ფაილის სახელად ვერ გამოდგება +@msg no metadata templates folder here აქ მეტამონაცემების შაბლონების საქაღალდე არ არის +@msg give `name` or `path`, not both მიუთითეთ `name` ან `path`, არა ორივე +@msg give one of `path`, `name` and `data` მიუთითეთ ერთ-ერთი: `path`, `name` და `data` +@msg mode must be replace, keep or append რეჟიმი უნდა იყოს replace, keep ან append +@msg the file is not an XMP metadata template ფაილი არ არის XMP მეტამონაცემების შაბლონი Copyright Notice: საავტორო უფლების შენიშვნა: Copyright Status: საავტორო უფლების სტატუსი: Created: შექმნილია: @@ -5352,6 +5368,8 @@ theme Appearance იერსახე Create Graph დიაგრამის შექმნა Graph Data დიაგრამის მონაცემები Graph Type დიაგრამის ტიპი + Graph Type… გრაფიკის ტიპი… + Graph Data… გრაფიკის მონაცემები… Graph Options გრაფიკის პარამეტრები Left Axis მარცხენა ღერძი Right Axis მარჯვენა ღერძი @@ -6866,6 +6884,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. პარამეტრები იმპორტირებულია. @@ -7797,6 +7817,27 @@ imageTrace Outline კონტური @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის უკუძახილში, getter-ში, გარდაქმნაში ან ფაილში, რომელსაც $.evalFile უშვებს; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: შემდეგი პასუხი `answers`-ში არის {_1}-ისთვის და არა {name}-ისთვის @msg {name}: `answers` has no answer left for this dialog {name}: `answers`-ში ამ დიალოგისთვის პასუხი აღარ დარჩა +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`-ში დარჩა {n} პასუხი, რომელიც სკრიპტს არ გამოუყენებია +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}-მა ფუნჯის ქვეშ უცვლელი დატოვა {n} ობიექტი ({_2}): ის მხოლოდ ტრაექტორიებს ცვლის +liquify-tool Warp გაღუნვა +liquify-tool Twirl დახვევა +liquify-tool Pucker შეკუმშვა +liquify-tool Bloat გაბერვა +liquify-tool Scallop დაკბილვა +liquify-tool Crystallize კრისტალიზაცია +liquify-tool Wrinkle დანაოჭება +liquify-kind graphs დიაგრამები +liquify-kind type ტექსტი +liquify-kind symbols სიმბოლოები +liquify-kind images გამოსახულებები +liquify-kind meshes ბადეები +liquify-kind envelopes გარსები +liquify-kind repeats გამეორებები +liquify-kind placed documents განთავსებული დოკუმენტები +liquify-kind blends გადასვლები +liquify-list-two {0}, {1} {0} და {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} და {1} @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 ამ ფუნქციის სკრიპტის გაშვება დასრულდა @@ -8033,6 +8074,7 @@ imageTrace Outline კონტური 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} შეიცავს მმართველ სიმბოლოებს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9f843f2102..a481813b0e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1376,6 +1376,18 @@ antiAlias Sharp 날카롭게 Copy Width Point 너비 점 복사 Copyright 저작권 Copyright Info URL: 저작권 정보 URL: + Save Metadata Template… 메타데이터 템플릿 저장… + Import Options 가져오기 옵션 + Clear existing fields and use the template's 기존 필드를 지우고 템플릿의 필드 사용 + Keep existing fields, but replace those the template has 기존 필드를 유지하되 템플릿에 있는 필드 바꾸기 + Keep existing fields, but append those the template has 기존 필드를 유지하되 템플릿에 있는 필드 추가 +@msg the template name can't be empty 템플릿 이름은 비워 둘 수 없습니다 +@msg the template name isn't usable as a file name 템플릿 이름은 파일 이름으로 사용할 수 없습니다 +@msg no metadata templates folder here 여기에는 메타데이터 템플릿 폴더가 없습니다 +@msg give `name` or `path`, not both `name` 또는 `path` 중 하나만 지정하세요 +@msg give one of `path`, `name` and `data` `path`, `name`, `data` 중 하나를 지정하세요 +@msg mode must be replace, keep or append 모드는 replace, keep 또는 append여야 합니다 +@msg the file is not an XMP metadata template 파일이 XMP 메타데이터 템플릿이 아닙니다 Copyright Notice: 저작권 고지: Copyright Status: 저작권 상태: Corner Point Angle Threshold: 모퉁이 포인트 각도 임계값: @@ -3404,6 +3416,9 @@ mark-style Japanese 일본식 Swap Fill and Stroke 칠과 선 바꾸기 Swap start and end arrowheads 시작과 끝 화살촉 바꾸기 Stylistic Alternates 스타일 대체 글자 + Ligatures 합자 + Ornaments 장식 + Figures 숫자 Swash 스워시 Swatch Conflict 견본 충돌 Swatch Conflicts 견본 충돌 @@ -3865,6 +3880,8 @@ file-filter Templates 템플릿 Gradient (. or Shift+.) 그레이디언트 (. 또는 Shift+.) Graph Data 그래프 데이터 Graph Type 그래프 유형 + Graph Type… 그래프 유형… + Graph Data… 그래프 데이터… Graph Options 그래프 옵션 Left Axis 왼쪽 축 Right Axis 오른쪽 축 @@ -5041,6 +5058,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}을(를) 다운로드했습니다 @@ -5228,6 +5247,27 @@ theme Appearance 외관 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수의 콜백, getter, 변환 또는 $.evalFile이 실행하는 파일 안에서는 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers`의 다음 답은 {name}이(가) 아니라 {_1}에 대한 것입니다 @msg {name}: `answers` has no answer left for this dialog {name}: `answers`에 이 대화 상자에 대한 답이 남아 있지 않습니다 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`에 스크립트가 사용하지 않은 답이 {n}개 있습니다 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}은(는) 브러시 아래의 개체 {n}개를 변경하지 않았습니다({_2}). 패스만 변형합니다 +liquify-tool Warp 왜곡 +liquify-tool Twirl 돌리기 +liquify-tool Pucker 오므리기 +liquify-tool Bloat 부풀리기 +liquify-tool Scallop 스캘럽 +liquify-tool Crystallize 결정화 +liquify-tool Wrinkle 주름 +liquify-kind graphs 그래프 +liquify-kind type 문자 +liquify-kind symbols 심볼 +liquify-kind images 이미지 +liquify-kind meshes 메시 +liquify-kind envelopes 엔벨로프 +liquify-kind repeats 반복 +liquify-kind placed documents 가져온 문서 +liquify-kind blends 블렌드 +liquify-list-two {0}, {1} {0} 및 {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} 및 {1} @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 이 함수의 스크립트 실행이 끝났습니다 @@ -5522,6 +5562,7 @@ effect Vertical 세로 Change Panel Layout 패널 레이아웃 변경 Close Panel 패널 닫기 Collapse Panel Group 패널 그룹 접기 + Cycle Display Sizes 표시 크기 전환 Move Panel 패널 이동 Group with 함께 그룹화 Resize panels 패널 크기 조절 @@ -5875,6 +5916,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}에 제어 문자가 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5bb55937f8..7db87fef24 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -131,6 +131,27 @@ @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: een dialoogvenster kan niet openen binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat $.evalFile uitvoert; roep het aan vanuit de eigen code van het script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: het volgende antwoord in `answers` is voor {_1}, niet voor {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` heeft geen antwoord meer voor dit dialoogvenster +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` bevat {n} antwoord dat het script niet heeft gebruikt|`answers` bevat {n} antwoorden die het script niet heeft gebruikt +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} liet {n} object onder het penseel ongewijzigd ({_2}): het vervormt alleen paden|{_1} liet {n} objecten onder het penseel ongewijzigd ({_2}): het vervormt alleen paden +liquify-tool Warp Vervormen +liquify-tool Twirl Draaien +liquify-tool Pucker Krimpen +liquify-tool Bloat Opblazen +liquify-tool Scallop Schulpen +liquify-tool Crystallize Kristalliseren +liquify-tool Wrinkle Rimpelen +liquify-kind graphs grafieken +liquify-kind type tekst +liquify-kind symbols symbolen +liquify-kind images afbeeldingen +liquify-kind meshes rasters +liquify-kind envelopes omvormingen +liquify-kind repeats herhalingen +liquify-kind placed documents geplaatste documenten +liquify-kind blends vermengingen +liquify-list-two {0}, {1} {0} en {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} en {1} @msg vc.document{place} is too large for a script vc.document{place} is te groot voor een script @msg vc.log: the log of this run is full vc.log: het logboek van deze uitvoering is vol @msg this function's script run has ended de scriptuitvoering van deze functie is beëindigd @@ -1477,6 +1498,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 @@ -2428,6 +2450,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Selecteer tekst om de OpenType-functies in te stellen. Standard Ligatures Standaardligaturen Stylistic Alternates Stilistische alternatieven + Ligatures Ligaturen + Ornaments Ornamenten + Figures Cijfers Set {n} Set {n} Swash Swash Tabular Lining Tabulaire lining @@ -2952,6 +2977,18 @@ digits Malayalam Malayalam Author Title: Auteurstitel: Author: Auteur: Copyright Info URL: URL voor copyrightinfo: + Save Metadata Template… Metagegevenssjabloon opslaan… + Import Options Importopties + Clear existing fields and use the template's Bestaande velden wissen en die van het sjabloon gebruiken + Keep existing fields, but replace those the template has Bestaande velden behouden, maar die in het sjabloon vervangen + Keep existing fields, but append those the template has Bestaande velden behouden, maar die in het sjabloon toevoegen +@msg the template name can't be empty de sjabloonnaam mag niet leeg zijn +@msg the template name isn't usable as a file name de sjabloonnaam is niet bruikbaar als bestandsnaam +@msg no metadata templates folder here hier is geen map voor metagegevenssjablonen +@msg give `name` or `path`, not both geef `name` of `path` op, niet allebei +@msg give one of `path`, `name` and `data` geef één van `path`, `name` en `data` op +@msg mode must be replace, keep or append de modus moet replace, keep of append zijn +@msg the file is not an XMP metadata template het bestand is geen XMP-metagegevenssjabloon Copyright Notice: Copyrightvermelding: Copyright Status: Copyrightstatus: Created: Aangemaakt: @@ -3941,6 +3978,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 @@ -5453,6 +5492,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} @@ -8114,6 +8155,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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f49e7e9830..c771824932 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 @@ -2027,6 +2028,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Zaznacz tekst, aby ustawić jego funkcje OpenType. Standard Ligatures Ligatury standardowe Stylistic Alternates Alternatywy stylistyczne + Ligatures Ligatury + Ornaments Ornamenty + Figures Cyfry Swash Ozdobniki Tabular Lining Tabelaryczne nowoczesne Tabular Oldstyle Tabelaryczne nautyczne @@ -2562,6 +2566,18 @@ digits Malayalam Malajalam Author Title: Stanowisko autora: Author: Autor: Copyright Info URL: URL informacji o prawach autorskich: + Save Metadata Template… Zapisz szablon metadanych… + Import Options Opcje importu + Clear existing fields and use the template's Wyczyść istniejące pola i użyj pól z szablonu + Keep existing fields, but replace those the template has Zachowaj istniejące pola, ale zastąp te, które zawiera szablon + Keep existing fields, but append those the template has Zachowaj istniejące pola, ale dołącz te, które zawiera szablon +@msg the template name can't be empty nazwa szablonu nie może być pusta +@msg the template name isn't usable as a file name nazwy szablonu nie można użyć jako nazwy pliku +@msg no metadata templates folder here brak tu folderu szablonów metadanych +@msg give `name` or `path`, not both podaj `name` albo `path`, nie oba +@msg give one of `path`, `name` and `data` podaj jeden z parametrów `path`, `name` i `data` +@msg mode must be replace, keep or append tryb musi mieć wartość replace, keep lub append +@msg the file is not an XMP metadata template plik nie jest szablonem metadanych XMP Copyright Notice: Informacja o prawach autorskich: Copyright Status: Status praw autorskich: Created: Utworzono: @@ -3577,6 +3593,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ś @@ -4626,6 +4644,27 @@ imageTrace Outline Kontur @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okno dialogowe nie może się otworzyć w wywołaniu zwrotnym funkcji wbudowanej, getterze, konwersji ani pliku uruchamianym przez $.evalFile; wywołaj je z własnego kodu skryptu @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: następna odpowiedź w `answers` jest dla {_1}, nie dla {name} @msg {name}: `answers` has no answer left for this dialog {name}: w `answers` nie została żadna odpowiedź dla tego okna dialogowego +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` zawiera {n} odpowiedź, której skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} pozostawił {n} obiekt pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiekty pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiektów pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki +liquify-tool Warp Wypaczenie +liquify-tool Twirl Wir +liquify-tool Pucker Ściągnięcie +liquify-tool Bloat Nadmuchanie +liquify-tool Scallop Ząbkowanie +liquify-tool Crystallize Krystalizacja +liquify-tool Wrinkle Marszczenie +liquify-kind graphs wykresy +liquify-kind type tekst +liquify-kind symbols symbole +liquify-kind images obrazy +liquify-kind meshes siatki +liquify-kind envelopes koperty +liquify-kind repeats powtórzenia +liquify-kind placed documents umieszczone dokumenty +liquify-kind blends przejścia +liquify-list-two {0}, {1} {0} i {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} i {1} @msg vc.document{place} is too large for a script vc.document{place} jest za duży dla skryptu @msg vc.log: the log of this run is full vc.log: dziennik tego uruchomienia jest pełny @msg this function's script run has ended uruchomienie skryptu tej funkcji zakończyło się @@ -5268,6 +5307,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. @@ -6147,6 +6188,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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 515764268a..e1dc9ed083 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -590,6 +590,18 @@ antiAlias Sharp Nítido Copy to User Defined Copiar para Definido pelo Usuário Copyright Direitos Autorais Copyright Info URL: URL de Informações de Direitos Autorais: + Save Metadata Template… Salvar Modelo de Metadados… + Import Options Opções de Importação + Clear existing fields and use the template's Limpar os campos existentes e usar os do modelo + Keep existing fields, but replace those the template has Manter os campos existentes, mas substituir os que o modelo tiver + Keep existing fields, but append those the template has Manter os campos existentes, mas acrescentar os que o modelo tiver +@msg the template name can't be empty o nome do modelo não pode ficar vazio +@msg the template name isn't usable as a file name o nome do modelo não pode ser usado como nome de arquivo +@msg no metadata templates folder here não há pasta de modelos de metadados aqui +@msg give `name` or `path`, not both informe `name` ou `path`, não ambos +@msg give one of `path`, `name` and `data` informe um de `path`, `name` e `data` +@msg mode must be replace, keep or append o modo deve ser replace, keep ou append +@msg the file is not an XMP metadata template o arquivo não é um modelo de metadados XMP Copyright Notice: Aviso de Direitos Autorais: Copyright Status: Status de Direitos Autorais: Copyright Symbol Símbolo de Direitos Autorais @@ -1042,6 +1054,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 @@ -3053,6 +3066,9 @@ digits Malayalam Malaiala Swap Fill and Stroke Trocar Preenchimento e Traçado Swap start and end arrowheads Trocar pontas de seta inicial e final Stylistic Alternates Variantes Estilísticas + Ligatures Ligações + Ornaments Ornamentos + Figures Algarismos Swash Ornamento Swatch Conflict Conflito de Amostra Swatch Conflicts Conflitos de Amostra @@ -3550,6 +3566,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 @@ -4498,6 +4515,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. @@ -4996,6 +5015,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 @@ -5528,6 +5549,27 @@ axis Both Ambos @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo não pode abrir dentro de um callback de uma função interna, um getter, uma conversão ou um arquivo que $.evalFile executa; chame-a a partir do próprio código do script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a próxima resposta em `answers` é para {_1}, não para {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` não tem mais respostas para esta caixa de diálogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contém {n} resposta que o script não usou|`answers` contém {n} respostas que o script não usou +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} deixou {n} objeto sob o pincel sem alteração ({_2}): remodela apenas caminhos|{_1} deixou {n} objetos sob o pincel sem alteração ({_2}): remodela apenas caminhos +liquify-tool Warp Distorcer +liquify-tool Twirl Redemoinho +liquify-tool Pucker Encolher +liquify-tool Bloat Estufar +liquify-tool Scallop Vieira +liquify-tool Crystallize Cristalizar +liquify-tool Wrinkle Rugas +liquify-kind graphs gráficos +liquify-kind type texto +liquify-kind symbols símbolos +liquify-kind images imagens +liquify-kind meshes malhas +liquify-kind envelopes envelopes +liquify-kind repeats repetições +liquify-kind placed documents documentos colocados +liquify-kind blends mesclagens +liquify-list-two {0}, {1} {0} e {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} e {1} @msg vc.document{place} is too large for a script vc.document{place} é grande demais para um script @msg vc.log: the log of this run is full vc.log: o registro desta execução está cheio @msg this function's script run has ended a execução do script desta função terminou diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 42649fb68f..3b12638a38 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -652,6 +652,18 @@ font-technology Variable Вариативные Copy Width Point Копировать точку ширины Copyright Copyright Copyright Info URL: URL информации об авторских правах: + Save Metadata Template… Сохранить шаблон метаданных… + Import Options Параметры импорта + Clear existing fields and use the template's Очистить существующие поля и использовать поля шаблона + Keep existing fields, but replace those the template has Сохранить существующие поля, но заменить те, что есть в шаблоне + Keep existing fields, but append those the template has Сохранить существующие поля, но добавить те, что есть в шаблоне +@msg the template name can't be empty имя шаблона не может быть пустым +@msg the template name isn't usable as a file name имя шаблона нельзя использовать как имя файла +@msg no metadata templates folder here здесь нет папки шаблонов метаданных +@msg give `name` or `path`, not both укажите `name` или `path`, но не оба +@msg give one of `path`, `name` and `data` укажите один из параметров `path`, `name` и `data` +@msg mode must be replace, keep or append режим должен быть replace, keep или append +@msg the file is not an XMP metadata template файл не является шаблоном метаданных XMP Copyright Notice: Уведомление об авторских правах: Copyright Status: Статус авторских прав: Copyright Symbol Символ авторского права @@ -1442,6 +1454,8 @@ file-filter Templates Шаблоны Graph Диаграмма Graph Data Данные диаграммы Graph Type Тип диаграммы + Graph Type… Тип диаграммы… + Graph Data… Данные диаграммы… Graph Options Параметры диаграммы Left Axis Левая ось Right Axis Правая ось @@ -3701,6 +3715,9 @@ digits Malayalam Малаялам Show Import Options Показывать параметры импорта Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запрашивать параметры импорта каждого файла PDF, DXF или текстового файла перед помещением; если выключено, используются последние выбранные параметры Stylistic Alternates Стилистические альтернативы + Ligatures Лигатуры + Ornaments Орнаменты + Figures Цифры Swash Росчерк Swatch Conflict Конфликт образцов Swatch Conflicts Конфликты образцов @@ -4521,6 +4538,27 @@ axis Both Оба @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: диалоговое окно не может открыться внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: следующий ответ в `answers` предназначен для {_1}, а не для {name} @msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не осталось ответа для этого диалогового окна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use В `answers` остался {n} ответ, который скрипт не использовал|В `answers` осталось {n} ответа, которые скрипт не использовал|В `answers` осталось {n} ответов, которые скрипт не использовал +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} оставил без изменений {n} объект под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объекта под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объектов под кистью ({_2}): он изменяет только контуры +liquify-tool Warp Инструмент «Деформация» +liquify-tool Twirl Инструмент «Закручивание» +liquify-tool Pucker Инструмент «Сморщивание» +liquify-tool Bloat Инструмент «Раздувание» +liquify-tool Scallop Инструмент «Фестоны» +liquify-tool Crystallize Инструмент «Кристаллизация» +liquify-tool Wrinkle Инструмент «Морщины» +liquify-kind graphs диаграммы +liquify-kind type текст +liquify-kind symbols символы +liquify-kind images изображения +liquify-kind meshes сетки +liquify-kind envelopes оболочки +liquify-kind repeats повторы +liquify-kind placed documents размещённые документы +liquify-kind blends переходы +liquify-list-two {0}, {1} {0} и {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} и {1} @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 запуск скрипта этой функции завершён @@ -5175,6 +5213,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. Настройки импортированы. @@ -5552,6 +5592,7 @@ axis Both Оба Change Panel Layout Изменить расположение панелей Close Panel Закрыть панель Collapse Panel Group Свернуть группу панелей + Cycle Display Sizes Переключить размеры отображения Move Panel Переместить панель Group with Сгруппировать с Resize panels Изменить размер панелей @@ -5911,6 +5952,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} содержит управляющие символы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ab44904c63..aa31c6eb2c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -641,6 +641,18 @@ font-technology Variable Variabla Copy Width Point Kopiera breddpunkt Copyright Upphovsrätt Copyright Info URL: URL för upphovsrättsinformation: + Save Metadata Template… Spara metadatamall… + Import Options Importalternativ + Clear existing fields and use the template's Rensa befintliga fält och använd mallens + Keep existing fields, but replace those the template has Behåll befintliga fält, men ersätt dem som mallen har + Keep existing fields, but append those the template has Behåll befintliga fält, men lägg till dem som mallen har +@msg the template name can't be empty mallnamnet får inte vara tomt +@msg the template name isn't usable as a file name mallnamnet kan inte användas som filnamn +@msg no metadata templates folder here det finns ingen mapp för metadatamallar här +@msg give `name` or `path`, not both ange `name` eller `path`, inte båda +@msg give one of `path`, `name` and `data` ange en av `path`, `name` och `data` +@msg mode must be replace, keep or append läget måste vara replace, keep eller append +@msg the file is not an XMP metadata template filen är inte en XMP-metadatamall Copyright Notice: Upphovsrättsmeddelande: Copyright Status: Upphovsrättsstatus: Copyright Symbol Upphovsrättssymbol @@ -1389,6 +1401,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 @@ -3591,6 +3605,9 @@ digits Malayalam Malayalam Show Import Options Visa importalternativ Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Fråga efter importalternativ för varje PDF-, DXF- eller textfil innan den placeras; av: använd de senast valda alternativen Stylistic Alternates Stilistiska alternativ + Ligatures Ligaturer + Ornaments Ornament + Figures Siffror Swash Swash Swatch Conflict Färgrutekonflikt Swatch Conflicts Färgrutekonflikter @@ -4394,6 +4411,27 @@ axis Both Båda @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialogruta kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: nästa svar i `answers` gäller {_1}, inte {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har inget svar kvar för den här dialogrutan +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar som skriptet inte använde|`answers` har {n} svar som skriptet inte använde +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om|{_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om +liquify-tool Warp Förvräng +liquify-tool Twirl Virvel +liquify-tool Pucker Dra ihop +liquify-tool Bloat Svullnad +liquify-tool Scallop Bågkant +liquify-tool Crystallize Kristallisera +liquify-tool Wrinkle Skrynkla +liquify-kind graphs diagram +liquify-kind type text +liquify-kind symbols symboler +liquify-kind images bilder +liquify-kind meshes nät +liquify-kind envelopes kuvert +liquify-kind repeats upprepningar +liquify-kind placed documents placerade dokument +liquify-kind blends blandningar +liquify-list-two {0}, {1} {0} och {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} och {1} @msg vc.document{place} is too large for a script vc.document{place} är för stort för ett skript @msg vc.log: the log of this run is full vc.log: loggen för den här körningen är full @msg this function's script run has ended skriptkörningen för den här funktionen har avslutats @@ -5030,6 +5068,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. @@ -5421,6 +5461,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 @@ -6157,6 +6198,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 @@ -9020,6 +9062,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 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b632e5cac3..47fbf5f2c7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2194,6 +2194,124 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// A script's error about unused `answers` and Liquify's note on the objects it left as they were +/// are translated whole for one object as well as for several, in every complete-message language, +/// and keep their counts. +#[test] +fn messages_with_one_or_several_items_translate_in_every_complete_catalog() { + let notes = [ + ("`answers` has 1 answer the script did not use", "1"), + ("`answers` has 2 answers the script did not use", "2"), + ("`answers` has 5 answers the script did not use", "5"), + ("Warp left 1 object under the brush as it was (type): it reshapes paths only", "1"), + ("Twirl left 2 objects under the brush as they were (type, images): it reshapes paths only", "2"), + ("Pucker left 5 objects under the brush as they were (symbols): it reshapes paths only", "5"), + ]; + // Whole words, so that a word such as Swedish "under" or Dutch "object" is not read as English. + let english = ["answer", "did", "use", "left", "brush", "was", "they", "were", "reshapes", "paths", "only"]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (note, count) in notes { + let shown = message(lang, note); + assert_ne!(shown, note, "{code}"); + assert!(shown.split(|c: char| !c.is_alphabetic()).all(|w| !english.contains(&w)), "{code}: {shown}"); + assert!(shown.contains(count) && (!note.starts_with('`') || shown.contains("`answers`")), "{code}: {shown}"); + } + } + // The count picks the language's form. + let cs = cs(); + assert!(message(cs, "`answers` has 1 answer the script did not use").contains("1 odpověď,")); + assert!(message(cs, "`answers` has 2 answers the script did not use").contains("2 odpovědi,")); + assert!(message(cs, "`answers` has 5 answers the script did not use").contains("5 odpovědí,")); +} + +/// Liquify's warning about the objects under the brush that it left as they were shows its tool +/// and each kind of object in the interface language, the kinds in their order and joined as the +/// language joins a list, in every complete-message language; the count stays. +#[test] +fn liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog() { + const TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; + const KINDS: [&str; 9] = ["graphs", "type", "symbols", "images", "meshes", "envelopes", "repeats", "placed documents", "blends"]; + let warning = |tool: &str, n: usize, kinds: &str| { + if n == 1 { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + } + }; + let words = |s: &str| s.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()).map(str::to_string).collect::>(); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let cat = lang.catalog(); + for ctx in ["liquify-list-two", "liquify-list-middle", "liquify-list-end"] { + assert!(cat.contextual(ctx, "{0}, {1}").is_some(), "{code} has no {ctx} row"); + } + let kind = |k: &str| cat.contextual("liquify-kind", k).unwrap_or_else(|| panic!("{code} has no liquify-kind row for {k}")); + // No English word of `sources` is left in `shown`, unless a translation uses it too. + let english_left = |shown: &str, sources: &[&str], translated: &[&str]| { + let shown = words(shown); + for source in sources { + let kept = translated.iter().any(|t| words(t).iter().any(|w| words(source).contains(w))); + assert!(kept || words(source).iter().all(|w| !shown.contains(w)), "{code}: {source} stays English in {shown:?}"); + } + }; + for tool in TOOLS { + let label = cat.contextual("liquify-tool", tool).unwrap_or_else(|| panic!("{code} has no liquify-tool row for {tool}")); + // All nine kinds, in the engine's order and in reverse. + for kinds in [KINDS.to_vec(), KINDS.iter().rev().copied().collect()] { + let shown = message(lang, &warning(tool, kinds.len(), &kinds.join(", "))); + assert!(shown.contains(label) && shown.contains('9'), "{code}: {shown}"); + let translated: Vec<&str> = kinds.iter().map(|k| kind(k)).collect(); + let mut from = 0; + for t in &translated { + let at = shown[from..].find(t).unwrap_or_else(|| panic!("{code}: {t} missing or out of order in {shown}")); + from += at + t.len(); + } + english_left(&shown, &kinds, &translated); + english_left(&shown, &[tool], &[label]); + } + } + // One kind, for one object and for several. + for k in KINDS { + for n in [1, 2, 5] { + let shown = message(lang, &warning("Bloat", n, k)); + assert!(shown.contains(kind(k)) && shown.contains(&n.to_string()), "{code}: {shown}"); + english_left(&shown, &[k], &[kind(k)]); + } + } + } + let de = Lang::from_code("de").expect("registered"); + assert_eq!( + message(de, &warning("Warp", 1, "symbols")), + "Verkrümmung ließ 1 Objekt unter dem Pinsel unverändert (Symbole): es formt nur Pfade um" + ); + assert_eq!( + message(de, &warning("Twirl", 2, "type, images")), + "Strudel ließ 2 Objekte unter dem Pinsel unverändert (Text und Bilder): es formt nur Pfade um" + ); + assert_eq!( + message(de, &warning("Pucker", 4, "graphs, type, symbols, images")), + "Zusammenziehen ließ 4 Objekte unter dem Pinsel unverändert (Diagramme, Text, Symbole und Bilder): es formt nur Pfade um" + ); + // The count picks the language's form. + assert_eq!( + message(cs(), &warning("Crystallize", 5, "meshes, placed documents")), + "Nástroj Krystalizace ponechal 5 objektů pod štětcem beze změny (sítě a umístěné dokumenty): mění pouze cesty" + ); + let ja = Lang::from_code("ja").expect("registered"); + assert_eq!( + message(ja, &warning("Wrinkle", 3, "blends, repeats, envelopes")), + "しわ はブラシの下にある 3 個のオブジェクトを変更せずに残しました(ブレンド、リピート、エンベロープ)。パスのみを変形します" + ); + // A kind Liquify does not list leaves the tool and the list as they are. + assert_eq!( + message(de, &warning("Warp", 2, "type, widgets")), + "Warp ließ 2 Objekte unter dem Pinsel unverändert (type, widgets): es formt nur Pfade um" + ); + // English shows the warning as the engine wrote it. + assert_eq!(message(Lang::EN, &warning("Warp", 2, "type, images")), warning("Warp", 2, "type, images")); +} + /// `file.info`'s refusal of a value with control characters is two whole messages, one for the /// fields that take line breaks and one for the fields that don't, and each is translated in every /// complete-message language with the field's key kept as written. @@ -3702,6 +3820,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] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5931c402c0..379824e2f5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -633,6 +633,18 @@ font-technology Variable Değişken Copy Width Point Genişlik Noktasını Kopyala Copyright Telif hakkı Copyright Info URL: Telif Hakkı Bilgisi URL'si: + Save Metadata Template… Meta Veri Şablonunu Kaydet… + Import Options İçe Aktarma Seçenekleri + Clear existing fields and use the template's Mevcut alanları temizle ve şablonunkileri kullan + Keep existing fields, but replace those the template has Mevcut alanları koru, ancak şablonda olanları değiştir + Keep existing fields, but append those the template has Mevcut alanları koru, ancak şablonda olanları ekle +@msg the template name can't be empty şablon adı boş olamaz +@msg the template name isn't usable as a file name şablon adı dosya adı olarak kullanılamaz +@msg no metadata templates folder here burada meta veri şablonları klasörü yok +@msg give `name` or `path`, not both `name` veya `path` verin, ikisini birden değil +@msg give one of `path`, `name` and `data` `path`, `name` ve `data` değerlerinden birini verin +@msg mode must be replace, keep or append mod replace, keep veya append olmalıdır +@msg the file is not an XMP metadata template dosya bir XMP meta veri şablonu değil Copyright Notice: Telif Hakkı Bildirimi: Copyright Status: Telif Hakkı Durumu: Copyright Symbol Telif Hakkı Sembolü @@ -1357,6 +1369,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 @@ -3447,6 +3461,9 @@ digits Malayalam Malayalam Show Import Options İçe Aktarma Seçeneklerini Göster Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Her PDF, DXF veya metin dosyasını yerleştirmeden önce içe aktarma seçeneklerini sor; kapalıyken son seçilen seçenekleri kullan Stylistic Alternates Stilistik Alternatifler + Ligatures Bitişik Harfler + Ornaments Süslemeler + Figures Rakamlar Swash çalkalama Swatch Conflict Renk Örneği Çatışması Swatch Conflicts Renk Örneği Çatışmaları @@ -4249,6 +4266,27 @@ axis Both Her İkisi @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: bir iletişim kutusu yerleşik bir işlevin geri çağrısında, bir getter içinde, bir dönüştürmede veya $.evalFile'ın çalıştırdığı bir dosyada açılamaz; bunu betiğin kendi kodundan çağırın @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` içindeki sonraki yanıt {name} için değil, {_1} için @msg {name}: `answers` has no answer left for this dialog {name}: `answers` içinde bu iletişim kutusu için yanıt kalmadı +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` içinde betiğin kullanmadığı {n} yanıt var +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}, fırçanın altındaki {n} nesneyi değiştirmeden bıraktı ({_2}): yalnızca yolları yeniden şekillendirir +liquify-tool Warp Çarpıtma +liquify-tool Twirl Burgu +liquify-tool Pucker Büzülme +liquify-tool Bloat Şişkinlik +liquify-tool Scallop Tarak +liquify-tool Crystallize Kristalleştirme +liquify-tool Wrinkle Kırışıklık +liquify-kind graphs grafikler +liquify-kind type yazı +liquify-kind symbols semboller +liquify-kind images görseller +liquify-kind meshes ağlar +liquify-kind envelopes zarflar +liquify-kind repeats tekrarlar +liquify-kind placed documents yerleştirilen belgeler +liquify-kind blends karışımlar +liquify-list-two {0}, {1} {0} ve {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} ve {1} @msg vc.document{place} is too large for a script vc.document{place} bir betik için çok büyük @msg vc.log: the log of this run is full vc.log: bu çalıştırmanın günlüğü dolu @msg this function's script run has ended bu işlevin betik çalıştırması sona erdi @@ -4882,6 +4920,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ı. @@ -6399,6 +6439,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 @@ -6495,6 +6536,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ı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index aad7452316..0fc5e80443 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -648,6 +648,18 @@ font-technology Variable Варіативні Copy Width Point Копіювати точку ширини Copyright Авторські права Copyright Info URL: URL інформації про авторські права: + Save Metadata Template… Зберегти шаблон метаданих… + Import Options Параметри імпорту + Clear existing fields and use the template's Очистити наявні поля й використати поля шаблону + Keep existing fields, but replace those the template has Зберегти наявні поля, але замінити ті, що є в шаблоні + Keep existing fields, but append those the template has Зберегти наявні поля, але додати ті, що є в шаблоні +@msg the template name can't be empty назва шаблону не може бути порожньою +@msg the template name isn't usable as a file name назву шаблону не можна використати як назву файлу +@msg no metadata templates folder here тут немає папки шаблонів метаданих +@msg give `name` or `path`, not both укажіть `name` або `path`, але не обидва +@msg give one of `path`, `name` and `data` укажіть один із параметрів `path`, `name` і `data` +@msg mode must be replace, keep or append режим має бути replace, keep або append +@msg the file is not an XMP metadata template файл не є шаблоном метаданих XMP Copyright Notice: Повідомлення про авторські права: Copyright Status: Статус авторських прав: Copyright Symbol Символ авторського права @@ -1445,6 +1457,8 @@ file-filter Templates Шаблони Graph Діаграма Graph Data Дані діаграми Graph Type Тип діаграми + Graph Type… Тип діаграми… + Graph Data… Дані діаграми… Graph Options Параметри діаграми Left Axis Ліва вісь Right Axis Права вісь @@ -3708,6 +3722,9 @@ effect Points Точки Show Import Options Показувати параметри імпорту Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запитувати параметри імпорту кожного файлу PDF, DXF чи текстового файлу перед розміщенням; якщо вимкнено, використовуються останні вибрані параметри Stylistic Alternates Стилістичні альтернативи + Ligatures Лігатури + Ornaments Орнаменти + Figures Цифри Swash Розчерк Swatch Conflict Конфлікт зразків Swatch Conflicts Конфлікти зразків @@ -4520,6 +4537,27 @@ axis Both Обидві @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: діалогове вікно не може відкритися всередині зворотного виклику вбудованої функції, гетера, перетворення або файлу, який виконує $.evalFile; викличте його з власного коду скрипту @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: наступна відповідь у `answers` призначена для {_1}, а не для {name} @msg {name}: `answers` has no answer left for this dialog {name}: у `answers` не залишилося відповіді для цього діалогового вікна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use У `answers` залишилася {n} відповідь, яку скрипт не використав|У `answers` залишилися {n} відповіді, які скрипт не використав|У `answers` залишилося {n} відповідей, які скрипт не використав +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} залишив без змін {n} об’єкт під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єкти під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єктів під пензлем ({_2}): він змінює форму лише контурів +liquify-tool Warp Інструмент «Деформація» +liquify-tool Twirl Інструмент «Закручування» +liquify-tool Pucker Інструмент «Зморщування» +liquify-tool Bloat Інструмент «Роздування» +liquify-tool Scallop Інструмент «Фестон» +liquify-tool Crystallize Інструмент «Кристалізація» +liquify-tool Wrinkle Інструмент «Зморшки» +liquify-kind graphs діаграми +liquify-kind type текст +liquify-kind symbols символи +liquify-kind images зображення +liquify-kind meshes сітки +liquify-kind envelopes оболонки +liquify-kind repeats повтори +liquify-kind placed documents розміщені документи +liquify-kind blends переходи +liquify-list-two {0}, {1} {0} і {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} і {1} @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 запуск скрипту цієї функції завершився @@ -5161,6 +5199,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. Налаштування імпортовано. @@ -5536,6 +5576,7 @@ axis Both Обидві Change Panel Layout Змінити розташування панелей Close Panel Закрити панель Collapse Panel Group Згорнути групу панелей + Cycle Display Sizes Перемкнути розміри відображення Move Panel Перемістити панель Group with Згрупувати з Resize panels Змінити розмір панелей @@ -5893,6 +5934,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} містить керівні символи diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e1cc56f54c..0eda271a39 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 @@ -753,6 +754,18 @@ font-technology Variable Biến thiên Copy Width Point Sao chép điểm chiều rộng Copyright Bản quyền Copyright Info URL: URL thông tin bản quyền: + Save Metadata Template… Lưu mẫu siêu dữ liệu… + Import Options Tùy chọn nhập + Clear existing fields and use the template's Xóa các trường hiện có và dùng các trường của mẫu + Keep existing fields, but replace those the template has Giữ các trường hiện có, nhưng thay thế các trường mà mẫu có + Keep existing fields, but append those the template has Giữ các trường hiện có, nhưng nối thêm các trường mà mẫu có +@msg the template name can't be empty tên mẫu không được để trống +@msg the template name isn't usable as a file name không thể dùng tên mẫu làm tên tệp +@msg no metadata templates folder here không có thư mục mẫu siêu dữ liệu ở đây +@msg give `name` or `path`, not both hãy chỉ định `name` hoặc `path`, không phải cả hai +@msg give one of `path`, `name` and `data` hãy chỉ định một trong `path`, `name` và `data` +@msg mode must be replace, keep or append chế độ phải là replace, keep hoặc append +@msg the file is not an XMP metadata template tệp không phải là mẫu siêu dữ liệu XMP Copyright Notice: Thông báo bản quyền: Copyright Status: Trạng thái bản quyền: Copyright Symbol Ký hiệu bản quyền @@ -1704,6 +1717,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 @@ -4089,6 +4104,9 @@ mark-style Japanese Kiểu Nhật Show Import Options Hiện tùy chọn nhập Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Hỏi tùy chọn nhập của từng tệp PDF, DXF hoặc văn bản trước khi đặt; khi tắt, dùng các tùy chọn đã chọn gần nhất Stylistic Alternates Ký tự thay thế theo phong cách + Ligatures Chữ ghép + Ornaments Hoa văn + Figures Chữ số Swash Swash Swatch Conflict Xung đột mẫu màu Swatch Conflicts Xung đột mẫu màu @@ -4960,6 +4978,27 @@ theme Appearance Giao diện @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: hộp thoại không thể mở bên trong lệnh gọi lại của hàm dựng sẵn, getter, phép chuyển đổi hoặc tệp mà $.evalFile chạy; hãy gọi nó từ mã của chính tập lệnh @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: câu trả lời tiếp theo trong `answers` dành cho {_1}, không phải {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` không còn câu trả lời nào cho hộp thoại này +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` có {n} câu trả lời mà tập lệnh không dùng +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} giữ nguyên {n} đối tượng dưới cọ ({_2}): chỉ biến dạng đường dẫn +liquify-tool Warp Biến dạng +liquify-tool Twirl Xoáy +liquify-tool Pucker Nhíu +liquify-tool Bloat Phình +liquify-tool Scallop Vỏ sò +liquify-tool Crystallize Kết tinh +liquify-tool Wrinkle Nhăn +liquify-kind graphs biểu đồ +liquify-kind type chữ +liquify-kind symbols ký hiệu +liquify-kind images hình ảnh +liquify-kind meshes lưới +liquify-kind envelopes bao hình +liquify-kind repeats lặp lại +liquify-kind placed documents tài liệu đã đặt +liquify-kind blends hòa trộn +liquify-list-two {0}, {1} {0} và {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} và {1} @msg vc.document{place} is too large for a script vc.document{place} quá lớn đối với tập lệnh @msg vc.log: the log of this run is full vc.log: nhật ký của lần chạy này đã đầy @msg this function's script run has ended lần chạy tập lệnh của hàm này đã kết thúc @@ -5699,6 +5738,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ố @@ -5909,6 +5950,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 @@ -7196,6 +7238,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 ý diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4d1a8d40e9..fd853f3557 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -599,6 +599,18 @@ antiAlias Sharp 锐利 Copy Width Point 复制宽度点 Copyright 版权 Copyright Info URL: 版权信息 URL: + Save Metadata Template… 存储元数据模板… + Import Options 导入选项 + Clear existing fields and use the template's 清除现有字段并使用模板中的字段 + Keep existing fields, but replace those the template has 保留现有字段,但替换模板中包含的字段 + Keep existing fields, but append those the template has 保留现有字段,但追加模板中包含的字段 +@msg the template name can't be empty 模板名称不能为空 +@msg the template name isn't usable as a file name 模板名称不能用作文件名 +@msg no metadata templates folder here 此处没有元数据模板文件夹 +@msg give `name` or `path`, not both 请提供 `name` 或 `path`,不能同时提供 +@msg give one of `path`, `name` and `data` 请提供 `path`、`name` 和 `data` 中的一个 +@msg mode must be replace, keep or append 模式必须为 replace、keep 或 append +@msg the file is not an XMP metadata template 该文件不是 XMP 元数据模板 Copyright Notice: 版权声明: Copyright Status: 版权状态: Copyright Symbol 著作权符号 @@ -1380,6 +1392,8 @@ file-filter Templates 模板 Graph 图表 Graph Data 图表数据 Graph Type 图表类型 + Graph Type… 图表类型… + Graph Data… 图表数据… Graph Options 图表选项 Left Axis 左轴 Right Axis 右轴 @@ -3528,6 +3542,9 @@ digits Malayalam 马拉雅拉姆数字 Show Import Options 显示导入选项 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前询问每个 PDF、DXF 或文本文件的导入选项;关闭时使用上次选择的选项 Stylistic Alternates 风格替代字 + Ligatures 连字 + Ornaments 装饰字 + Figures 数字 Swash 花饰字 Swatch Conflict 色板冲突 Swatch Conflicts 色板冲突 @@ -4795,6 +4812,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} @@ -4979,6 +4998,27 @@ imageTrace Outline 轮廓 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:对话框不能在内置函数的回调、getter、转换或 $.evalFile 运行的文件中打开;请从脚本自身的代码中调用 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}:`answers` 中的下一个回答是给 {_1} 的,而不是给 {name} 的 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已没有此对话框的回答 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 个脚本未使用的回答 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未更改画笔下的 {n} 个对象({_2}):它只重塑路径 +liquify-tool Warp 变形 +liquify-tool Twirl 旋转扭曲 +liquify-tool Pucker 收缩 +liquify-tool Bloat 膨胀 +liquify-tool Scallop 扇贝 +liquify-tool Crystallize 晶格化 +liquify-tool Wrinkle 褶皱 +liquify-kind graphs 图表 +liquify-kind type 文字 +liquify-kind symbols 符号 +liquify-kind images 图像 +liquify-kind meshes 网格 +liquify-kind envelopes 封套 +liquify-kind repeats 重复 +liquify-kind placed documents 置入的文档 +liquify-kind blends 混合 +liquify-list-two {0}, {1} {0}和{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}和{1} @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 此函数的脚本运行已结束 @@ -5836,6 +5876,7 @@ effect Vertical 垂直 Change Panel Layout 更改面板布局 Close Panel 关闭面板 Collapse Panel Group 折叠面板组 + Cycle Display Sizes 切换显示大小 Move Panel 移动面板 Group with 组合到 Resize panels 调整面板大小 @@ -6135,6 +6176,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} 包含控制字符 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 87e74d4fb0..d1ee466b89 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -616,6 +616,18 @@ font-technology Variable 可變 Copy Width Point 複製寬度點 Copyright 版權 Copyright Info URL: 著作權資訊網址: + Save Metadata Template… 儲存中繼資料範本… + Import Options 匯入選項 + Clear existing fields and use the template's 清除現有欄位並使用範本的欄位 + Keep existing fields, but replace those the template has 保留現有欄位,但取代範本中包含的欄位 + Keep existing fields, but append those the template has 保留現有欄位,但附加範本中包含的欄位 +@msg the template name can't be empty 範本名稱不能空白 +@msg the template name isn't usable as a file name 範本名稱無法用作檔案名稱 +@msg no metadata templates folder here 這裡沒有中繼資料範本資料夾 +@msg give `name` or `path`, not both 請提供 `name` 或 `path`,不可同時提供 +@msg give one of `path`, `name` and `data` 請提供 `path`、`name` 和 `data` 其中之一 +@msg mode must be replace, keep or append 模式必須是 replace、keep 或 append +@msg the file is not an XMP metadata template 這個檔案不是 XMP 中繼資料範本 Copyright Notice: 著作權聲明: Copyright Status: 著作權狀態: Copyright Symbol 著作權符號 @@ -1415,6 +1427,8 @@ file-filter Templates 範本 Graph 圖表 Graph Data 圖表資料 Graph Type 圖表類型 + Graph Type… 圖表類型… + Graph Data… 圖表資料… Graph Options 圖表選項 Left Axis 左軸 Right Axis 右軸 @@ -2441,6 +2455,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} @@ -2625,6 +2641,27 @@ file-filter Templates 範本 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:對話框不能在內建函式的回呼、getter、轉換或 $.evalFile 執行的檔案中開啟;請從指令碼本身的程式碼呼叫 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}:`answers` 中的下一個回答是給 {_1} 的,而不是給 {name} 的 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已沒有此對話框的回答 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 個指令碼未使用的回答 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未變更筆刷下的 {n} 個物件({_2}):它只重塑路徑 +liquify-tool Warp 彎曲 +liquify-tool Twirl 旋轉扭曲 +liquify-tool Pucker 縮攏 +liquify-tool Bloat 膨脹 +liquify-tool Scallop 扇形化 +liquify-tool Crystallize 結晶化 +liquify-tool Wrinkle 皺摺 +liquify-kind graphs 圖表 +liquify-kind type 文字 +liquify-kind symbols 符號 +liquify-kind images 影像 +liquify-kind meshes 網格 +liquify-kind envelopes 封套 +liquify-kind repeats 重複 +liquify-kind placed documents 已置入的文件 +liquify-kind blends 漸變 +liquify-list-two {0}, {1} {0}和{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}和{1} @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 此函式的指令碼執行已結束 @@ -4791,6 +4828,9 @@ digits Malayalam 馬來亞拉姆數字 Show Import Options 顯示讀入選項 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前詢問每個 PDF、DXF 或文字檔案的讀入選項;關閉時使用上次選擇的選項 Stylistic Alternates 風格替代字 + Ligatures 連字 + Ornaments 裝飾字 + Figures 數字 Swash 花體字 Swatch Conflict 色票衝突 Swatch Conflicts 色票衝突 @@ -5672,6 +5712,7 @@ effect Soft 柔和 Change Panel Layout 變更面板配置 Close Panel 關閉面板 Collapse Panel Group 摺疊面板群組 + Cycle Display Sizes 切換顯示大小 Move Panel 移動面板 Group with 群組至 Resize panels 調整面板大小 @@ -5970,6 +6011,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} 包含控制字元 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f89789d5d..0b8ee67183 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 @@ -71,6 +71,7 @@ pub mod script_runs; pub mod scripts_menu; mod scrub; pub mod shortcut_editor; +pub mod shortcut_sheet; pub mod shortcuts; pub mod state; pub mod stylus; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4c286f1da9..e4806b0457 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -189,7 +189,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( @@ -657,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", 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/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 c78622458f..266f423838 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1741,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/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index cac85259f3..d99d4ad068 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -11,8 +11,11 @@ //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`glyph_form_items`]). +//! After its Unicode ranges and Alternates for Current Selection, the Show menu lists the OpenType +//! categories the browsed font has ([`vectorcraft_text::FontFace::glyph_categories`]): each shows +//! the glyphs its features give, as Entire Font shows them. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; @@ -72,6 +75,75 @@ const SUBSETS: [(&str, u32, u32); 7] = [ /// double-click the glyph to replace it). const ALTERNATES: &str = "Alternates for Current Selection"; +/// The Show menu's choice of an OpenType category of the browsed font, after [`ALTERNATES`]; the +/// panel state `gl-category` holds the category's id ([`vectorcraft_text::GlyphCategoryKind::id`]). +/// Public behavior: [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) +/// (with an OpenType font, a category chosen from the Show menu restricts the kinds of glyphs the +/// panel displays). Which categories are offered, their names and their order are ours. +const CATEGORY: usize = SUBSETS.len() + 1; + +/// The Show menu label of `category`: a stylistic set by the font's name for it, else `Set N`, as +/// the OpenType panel names it. +fn category_label(category: &vectorcraft_text::GlyphCategory) -> String { + use vectorcraft_text::GlyphCategoryKind as K; + match category.kind { + K::Ligatures => tl!("Ligatures").to_string(), + K::Swashes => tl!("Swash").to_string(), + K::StylisticAlternates => tl!("Stylistic Alternates").to_string(), + K::StylisticSet(number) => super::opentype::set_label(&vectorcraft_text::StylisticSet { number, name: category.name.clone() }), + K::SmallCaps => tl!("Small Caps").to_string(), + K::Ornaments => tl!("Ornaments").to_string(), + K::Fractions => tl!("Fractions").to_string(), + K::Figures => tl!("Figures").to_string(), + } +} + +/// The ids and Show menu labels of `face`'s OpenType categories, in the menu's order. +fn categories(face: Option<&vectorcraft_text::FontFace>) -> Vec<(String, String)> { + face.map(|f| f.glyph_categories().iter().map(|c| (c.kind.id(), category_label(c))).collect()).unwrap_or_default() +} + +/// The Show menu's choice: the entry index (a Unicode range, [`ALTERNATES`] or [`CATEGORY`]) and, +/// for a category, its place in `cats`. A category the browsed font does not have is Entire Font, +/// and so is an index past the entries. +fn shown(ctx: &egui::Context, cats: &[(String, String)]) -> (usize, Option) { + let subset: usize = pstate(ctx, "gl-subset"); + match subset { + CATEGORY => { + let id: String = pstate(ctx, "gl-category"); + match cats.iter().position(|c| c.0 == id) { + Some(i) => (CATEGORY, Some(i)), + None => (0, None), + } + } + s if s > CATEGORY => (0, None), + s => (s, None), + } +} + +/// Show category `id` of the browsed font. +fn show_category(ctx: &egui::Context, id: &str) { + set_pstate(ctx, "gl-category", id.to_string()); + set_pstate(ctx, "gl-subset", CATEGORY); +} + +/// The face the panel browses: the font picked in the panel, else the current text's font, else +/// the fallback family, with that family and style. The same family and style can have a different +/// face id at the selection's version or axes; that instance is used when the Type tool's selected +/// character is set in the font. +fn browsed_face(app: &VectorcraftApp, ctx: &egui::Context) -> (String, String, Option>) { + let db = FontDb::global(); + let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); + // The panel browses the current text's font unless another font was picked here. + let picked: Option<(String, String)> = pstate(ctx, "gl-font"); + let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); + let face = selected_target(app) + .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) + .and_then(|t| db.style_face(t.style)) + .or_else(|| db.face(&family, &style)); + (family, style, face) +} + thread_local! { static TEX: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } @@ -226,41 +298,58 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) -> bool { /// Browse and insert glyphs from the chosen font, with font controls below the glyph grid. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let db = FontDb::global(); - let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); - // The panel browses the current text's font unless another font was picked here. - let picked: Option<(String, String)> = pstate(ui.ctx(), "gl-font"); - let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); - let subset: usize = pstate(ui.ctx(), "gl-subset"); + // The same family and style can have a different face id at the selection's version or axes. + // That instance is used for both the previews and Fit's applicability check. + let (family, style, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (subset, category) = shown(ui.ctx(), &cats); let (_, lo, hi) = SUBSETS[subset.min(SUBSETS.len() - 1)]; let w = ui.available_width(); - let names: Vec<&str> = SUBSETS.iter().map(|s| s.0).chain([ALTERNATES]).collect(); + // A stylistic set's name is the font's, shown as it is: the built-in labels are translated here. + let labels: Vec = + SUBSETS.iter().map(|s| tl!(s.0).to_string()).chain([tl!(ALTERNATES).to_string()]).chain(cats.iter().map(|c| c.1.clone())).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); + let current = match category { + Some(i) => CATEGORY + i, + None => subset, + }; ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Show:")).color(t.text_dim)); - if let Some(i) = widgets::dropdown(ui, "gl-subset", names[subset.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { - set_pstate(ui.ctx(), "gl-subset", i); + if let Some(i) = widgets::dropdown_names(ui, "gl-subset", names[current.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { + match i.checked_sub(CATEGORY).and_then(|k| cats.get(k)) { + Some((id, _)) => show_category(ui.ctx(), id), + None => set_pstate(ui.ctx(), "gl-subset", i), + } } }); - if subset >= SUBSETS.len() { + if subset == SUBSETS.len() { alternates(app, ui, w); font_row(app, ui, &family, &style, w); return; } - // The same family and style can have a different face id at the selection's version or axes. - // Use that instance for both the previews and Fit's applicability check. - let face = selected_target(app) - .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) - .and_then(|t| db.style_face(t.style)) - .or_else(|| db.face(&family, &style)); let Some(face) = face else { ui.label(egui::RichText::new(tl!("No fonts are available.")).color(t.text_dim)); return; }; - let chars: Vec<(char, u32)> = - face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); - // Entire Font also lists the glyphs no character maps (positional forms, alternates, - // ligatures) by glyph id, after the characters. - let unencoded = if subset == 0 { face.unencoded_glyphs() } else { Default::default() }; + let (chars, unencoded): (Vec<(char, u32)>, Vec) = match category.and_then(|i| face.glyph_categories().get(i)) { + // A category lists its glyphs that a character maps by that character, and the others by + // glyph id after them. + Some(c) => { + let wanted: HashSet = c.glyphs.iter().copied().collect(); + // A glyph several characters map is listed once, by the first of them; a glyph only a + // space or control character maps is listed by glyph id, as no character it can insert. + let mut mapped: HashSet = HashSet::new(); + let chars: Vec<(char, u32)> = + face.chars().into_iter().filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g)).collect(); + (chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect()) + } + None => { + let chars = face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); + // Entire Font also lists the glyphs no character maps (positional forms, alternates, + // ligatures) by glyph id, after the characters. + (chars, if subset == 0 { face.unencoded_glyphs().to_vec() } else { vec![] }) + } + }; let total = chars.len() + unencoded.len(); let cell = CELL_STEPS[cell_index(app)]; let cols = ((w / cell).floor() as usize).max(1); @@ -1046,16 +1135,25 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { glyph_form_items(app, ui); ui.separator(); } + let (_, _, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (cur, category) = shown(ui.ctx(), &cats); for (i, (name, _, _)) in SUBSETS.iter().enumerate() { - let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { set_pstate(ui.ctx(), "gl-subset", i); } } - let cur: usize = pstate(ui.ctx(), "gl-subset"); - if menu_item(ui, tl!("Alternates for Current Selection"), true, cur >= SUBSETS.len()) { + if menu_item(ui, tl!("Alternates for Current Selection"), true, cur == SUBSETS.len()) { set_pstate(ui.ctx(), "gl-subset", SUBSETS.len()); } + if !cats.is_empty() { + ui.separator(); + } + for (i, (id, label)) in cats.iter().enumerate() { + if menu_item(ui, label, true, category == Some(i)) { + show_category(ui.ctx(), id); + } + } } #[cfg(test)] @@ -1628,6 +1726,34 @@ mod tests { assert!(face.glyph_name(unencoded[0]).is_some(), "the font names its glyphs"); } + /// The panel menu lists the browsed font's OpenType categories after Alternates for Current + /// Selection, a stylistic set by the font's name for it; choosing one shows the glyphs its + /// features give and names it in Show. A font without that category shows Entire Font. + #[test] + fn the_show_menu_lists_the_fonts_opentype_categories() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, HALF_FORM_FAMILY, categories_font, half_form_font}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + FontDb::global().add_font(half_form_font(false).expect("the test font builds")); + let (mut app, _) = editing("a"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-font", Some((CATEGORIES_FAMILY.to_string(), "Regular".to_string()))); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + let at = items.iter().position(|t| t == "Alternates for Current Selection").expect("the alternates item"); + assert_eq!(items[at + 1..], ["Ligatures", "Round Dots", "Small Caps", "Figures"]); + choose(&ctx, &mut app, "Figures"); + assert_eq!(pstate::(&ctx, "gl-category"), "figures"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "2 glyphs") && all.iter().any(|s| s == "Figures"), "{all:?}"); + choose(&ctx, &mut app, "Round Dots"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "1 glyph") && all.iter().any(|s| s == "Round Dots"), "{all:?}"); + set_pstate(&ctx, "gl-font", Some((HALF_FORM_FAMILY.to_string(), "Regular".to_string()))); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "Entire Font") && !all.iter().any(|s| s == "Round Dots"), "{all:?}"); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + assert_eq!(items.last().map(String::as_str), Some("Alternates for Current Selection"), "{items:?}"); + } + #[test] fn zoom_stops_at_the_ends() { assert_eq!(nudge_cell(CELL_DEFAULT, 1), CELL_DEFAULT + 1); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 5db4cfbd17..fe144edbf9 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -312,8 +312,9 @@ fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { } /// A Stylistic Sets menu entry: the font's own name for the set, shown as the font gives it, or -/// `Set 1` through `Set 20` in the UI language. -fn set_label(set: &StylisticSet) -> String { +/// `Set 1` through `Set 20` in the UI language. The Glyphs panel's Show menu names its stylistic +/// set entries the same way. +pub(super) fn set_label(set: &StylisticSet) -> String { match &set.name { Some(name) => name.clone(), None => crate::i18n::fmt(tl!("Set {n}"), &[("n", &set.number.to_string())]), 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 fd77707fcd..6e933d44cd 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -944,6 +944,26 @@ mod tests { assert_eq!(nine, json!([-0.123456789, 1.5, -1.255, -2.75])); } + /// Symbol Options › Align to Pixel Grid is off for a new symbol, OK sends it, and the dialog + /// reopens with the symbol's setting. + #[test] + fn symbol_options_sets_align_to_pixel_grid() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10.3, "y": 10.6, "width": 30, "height": 20})).unwrap(); + app.run("ui.symbolOptions", json!({})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("alignToPixelGrid")); + app.ui.dialog.as_mut().unwrap().fields.insert("alignToPixelGrid".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + let name = symbols(&mut app)[0].clone(); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], true); + app.run("ui.symbolOptions", json!({"edit": true, "name": name})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("alignToPixelGrid")); + app.ui.dialog.as_mut().unwrap().fields.insert("alignToPixelGrid".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 35e17797b1..8948e9acd5 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -426,6 +426,49 @@ fn a_mixed_checkbox_shows_a_dash_and_another_change_keeps_each_effects_value() { assert!(named(&controls(&mut app, &ctx), "Add Light").is_disabled()); } +/// The Bevel heading's Reset sets every bevel setting back to its default on each selected Extrude & +/// Bevel, as one undo step, and leaves Depth and the rotation as each effect has them. With every +/// bevel setting at its default it is off and records nothing. +#[test] +fn the_bevel_reset_restores_only_the_bevel_settings_of_each_selected_effect() { + use crate::panels::tests_appearance::click; + let mut app = app(); + let bevelled = json!({"bevel": "rounded", "bevelWidth": 9.0, "bevelHeight": 6.0, "bevelRepeat": 3, "bevelSpace": 20.0, "bevelInside": true, "bevelBothSides": true, "depth": 70.0, "rotationX": 15.0}); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": bevelled})).unwrap(); + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"bevel": "cove", "bevelWidth": 2.0, "depth": 30.0}})) + .unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let nodes = controls(&mut app, &ctx); + let reset = named(&nodes, "Reset"); + assert!(!reset.is_disabled(), "changed bevel settings turn Reset on"); + let at = reset.bounds().map(|r| egui::pos2(((r.x0 + r.x1) / 2.0) as f32, ((r.y0 + r.y1) / 2.0) as f32)).unwrap(); + let history = undo_len(&app); + click(&ctx, &mut app, at, show); + assert_eq!(undo_len(&app), history + 1, "one undo step for both objects"); + let defaults = vectorcraft_effects::default_params("threeD.extrude").unwrap(); + let merged = |app: &VectorcraftApp, id: u64| { + let params = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params.clone(); + vectorcraft_effects::merged_params("threeD.extrude", ¶ms) + }; + for id in [a, b] { + for key in ["bevel", "bevelWidth", "bevelHeight", "bevelRepeat", "bevelSpace", "bevelInside", "bevelBothSides"] { + assert_eq!(merged(&app, id)[key], defaults[key], "{key} of {id}"); + } + } + assert_eq!((merged(&app, a)["depth"].clone(), merged(&app, b)["depth"].clone()), (json!(70.0), json!(30.0))); + assert_eq!(merged(&app, a)["rotationX"], 15.0); + let nodes = controls(&mut app, &ctx); + assert!(named(&nodes, "Reset").is_disabled(), "every bevel setting at its default: Reset is off"); + let history = undo_len(&app); + click(&ctx, &mut app, at, show); + assert_eq!(undo_len(&app), history, "an unavailable Reset records nothing"); +} + /// Revolve's Cap checkbox shows a dash when the selected effects disagree on it. #[test] fn a_mixed_revolve_cap_shows_a_dash() { @@ -839,9 +882,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 +1075,84 @@ 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() } diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index 687174e839..ce9900fdf8 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -174,15 +174,17 @@ fn new_document_cards_follow_the_chosen_units() { /// Choosing units in Preset Details changes the chosen document, not every recent one: each card /// keeps the units its document was made in, so switching between inches and millimetres leaves the -/// other templates as they were; choosing another card brings its units back. +/// other templates as they were; choosing another card brings its units back while no units were +/// chosen in the Units menu. #[test] fn recent_cards_keep_their_own_units() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - // 8.5 × 11 in, then 210 × 297 mm, which Recent lists first and the dialog opens on. + // 8.5 × 11 in, then 210 × 297 mm, which Recent lists first and the dialog opens on, in + // Preferences › Units › General (points). run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); app.run("file.newDialog", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Millimeters")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Points")); app.ui.dialog.as_mut().unwrap().fields.insert("units".into(), json!("Points")); let t = dialog_texts(&mut app); assert!(shows(&t, "595.276 × 841.89 pt"), "the chosen entry in points: {t:?}"); @@ -200,6 +202,54 @@ fn recent_cards_keep_their_own_units() { assert_eq!((d.fields["width"].clone(), d.fields["height"].clone()), (json!(612.0), json!(792.0))); } +/// Units chosen in the Units menu (here through `ui.dialog.set`) stay chosen when a Recent card made +/// in other units is clicked, and the document is made in them. +#[test] +fn a_recent_card_keeps_the_units_chosen_in_the_menu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "units".into(), json!("Millimeters")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let inches = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "8.5 × 11 in").center(); + click(&ctx, &mut app, inches, &mut draw); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["width"].clone(), d.fields["units"].clone()), (json!(612.0), json!("Millimeters"))); + crate::dialogs::confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.units, doc.artboards[0].rect.width()), (Unit::Millimeters, 612.0)); +} + +/// A double-click on a Recent or Saved card made in inches creates the document in the millimeters +/// chosen in the Units menu (here through `ui.dialog.set`) before it. +#[test] +fn a_double_clicked_card_keeps_the_units_chosen_in_the_menu() { + for category in ["Recent", "Saved"] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.newPresets.save", json!({"name": "Letter in", "width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("category".into(), json!(category)); + crate::dialogs::set_field(d, "units".into(), json!("Millimeters")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let card = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "8.5 × 11 in").center(); + click(&ctx, &mut app, card, &mut draw); + click(&ctx, &mut app, card, &mut draw); + assert!(app.ui.dialog.is_none(), "the {category} card's double-click creates: {:?}", app.ui.status); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.units, doc.artboards[0].rect.width()), (Unit::Millimeters, 612.0), "the {category} card"); + } +} + /// A saved preset keeps the units it was saved in too, whichever units the dialog is showing. #[test] fn saved_cards_keep_their_own_units() { diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index aab1892ea2..979e3e7d7f 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -263,7 +263,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { 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); + // The closed list button is too narrow for a name and shows none; the open list marks the + // current data set. + let picked = widgets::combo_named(ui, "variables-active", Some(tl!("Data Sets")), "", 26.0, |ui| { + let mut chosen = None; + for (i, name) in names.iter().enumerate() { + if ui.add(egui::Button::selectable(*name == current, *name)).clicked() { + chosen = Some(i); + } + } + chosen + }); if let Some(name) = picked.and_then(|i| names.get(i)) && *name != current { @@ -430,6 +440,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); } @@ -453,6 +467,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() }; @@ -562,6 +593,37 @@ mod tests { self.frame(app, vec![Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: none }]); self.frame(app, vec![]); } + + /// The panel's accessibility nodes after two frames without input. + fn nodes(&mut self, app: &mut VectorcraftApp) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + self.frame(app, vec![]); + let out = self.frame(app, vec![]); + out.platform_output.accesskit_update.expect("an accessibility tree").nodes + } + + /// Clicks the center of `node`. + fn click(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node) { + use egui::{Event, Modifiers, PointerButton}; + let b = node.bounds().expect("bounds"); + let pos = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + 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 }]); + self.frame(app, vec![]); + } + + /// Clicks the Data Set list button and returns the rows of the open list: the buttons that + /// were not in the panel before it opened. + fn open_data_set_list(&mut self, app: &mut VectorcraftApp) -> Vec { + use egui::accesskit::Role; + let before = self.nodes(app); + let (_, list) = + before.iter().find(|(_, n)| n.role() == Role::ComboBox && n.label() == Some("Data Sets")).expect("the Data Set list button"); + let list = list.clone(); + self.click(app, &list); + let after = self.nodes(app); + after.into_iter().filter(|(id, n)| n.role() == Role::Button && !before.iter().any(|(b, _)| b == id)).map(|(_, n)| n).collect() + } } fn set_names(app: &mut VectorcraftApp) -> Vec { @@ -574,7 +636,8 @@ mod tests { } /// 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. + /// the open list then marks the renamed data set as the current one, and a click on another + /// row chooses that data set. #[test] fn the_data_set_box_renames_the_current_data_set() { let mut app = app_with_data(); @@ -587,10 +650,16 @@ mod tests { 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. + // The new name is what the box shows, and what the list offers, marked, 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(); + let rows = d.open_data_set_list(&mut app); + // The accessibility update lists nodes in hash-map order, so the rows are compared by name. + let mut marked: Vec<(Option<&str>, bool)> = rows.iter().map(|n| (n.label(), n.toggled() == Some(egui::accesskit::Toggled::True))).collect(); + marked.sort(); + assert_eq!(marked, [(Some("Data Set 2"), false), (Some("Spring"), true)]); + let other = rows.iter().find(|n| n.label() == Some("Data Set 2")).expect("the Data Set 2 row").clone(); + d.click(&mut app, &other); assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Data Set 2")); } @@ -626,6 +695,12 @@ mod tests { app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); let before = undo_steps(&app); let mut d = Driver::new(); + let nodes = d.nodes(&mut app); + let (_, field) = nodes + .iter() + .find(|(_, n)| matches!(n.role(), egui::accesskit::Role::TextInput | egui::accesskit::Role::MultilineTextInput)) + .expect("the Data Set box"); + assert!(field.is_disabled(), "the Data Set box is enabled without a data set"); d.type_name(&mut app, "Spring"); assert!(set_names(&mut app).is_empty()); assert_eq!(undo_steps(&app), before); @@ -758,6 +833,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 0ad9fbc3ed..3141cfb3c6 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -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 @@ -223,8 +226,8 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result 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| { @@ -520,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 @@ -560,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() diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 88a97206c7..348aed01fa 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1184,7 +1184,7 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { let snapshot = snapshot(); let km = crate::keymap::keymap_in(&snapshot, overrides); let backtick = backtick_text(); - let shown_set = if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set }; + let shown_set = shown_set_name(set); let mut out = format!("{}\n{} {shown_set}\n", tl!("Keyboard Shortcuts"), tl!("Set:")); for (tools, heading) in [(true, "Tools"), (false, "Menu Commands")] { out += &format!("\n{}\n", tl!(heading)); @@ -1197,6 +1197,139 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { out } +/// A set's name as the dialog shows it: the presets and Custom in the UI language. +fn shown_set_name(set: &str) -> &str { + if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set } +} + +/// Export Text's file formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextFormat { + /// [`export_text`]'s text file. + Text, + /// The printable shortcut sheet as a PDF ([`crate::shortcut_sheet::sheet_pdf`]). + Sheet, + /// A CSV file of [`export_sections`] ([`crate::shortcut_sheet::csv`]). + Csv, +} + +impl TextFormat { + pub const ALL: [Self; 3] = [Self::Text, Self::Sheet, Self::Csv]; + + /// The `format` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Text => "text", + Self::Sheet => "sheet", + Self::Csv => "csv", + } + } + + fn extension(self) -> &'static str { + match self { + Self::Text => "txt", + Self::Sheet => "pdf", + Self::Csv => "csv", + } + } + + /// The save dialog's file type. + fn filter(self) -> crate::FileFilter { + let label = match self { + Self::Text => "Text", + Self::Sheet => "Shortcut sheet", + Self::Csv => "CSV", + }; + crate::FilePick::filter(label, &[self.extension()]) + } + + fn file_name(self) -> String { + format!("VectorCraft Shortcuts.{}", self.extension()) + } + + /// `path` with `format`'s extension: kept when it has it in any letter case, the extension of + /// another of these formats replaced, and the extension added to any other path. + fn with_extension(path: &str, format: Self) -> String { + let ext = vectorcraft_engine::cmd::fileio::extension(path); + if ext.eq_ignore_ascii_case(format.extension()) { + path.to_string() + } else if Self::ALL.iter().any(|f| f.extension().eq_ignore_ascii_case(&ext)) { + std::path::Path::new(path).with_extension(format.extension()).to_string_lossy().into_owned() + } else { + format!("{path}.{}", format.extension()) + } + } + + /// The format a save dialog's answer picked: the file type it reports, else the extension of + /// `path`; text for any other. + fn picked(path: &str, file_type: Option<&str>) -> Self { + let ext = file_type.map_or_else(|| vectorcraft_engine::cmd::fileio::extension(path), str::to_string); + Self::ALL.into_iter().find(|f| f.extension().eq_ignore_ascii_case(ext.trim_start_matches('.'))).unwrap_or(Self::Text) + } +} + +/// The section name for menu commands no menu holds, as Export Text's heading has it. +const MENU_COMMANDS: &str = "Menu Commands"; + +/// Export Text's rows in sections, for the shortcut sheet and the CSV file: Tools, then one section +/// per top-level menu in the order the dialog first lists a command of it, with the names and +/// shortcuts as the dialog shows them, each name without its top-level menu. Every row the dialog +/// lists is there, with an empty shortcut when it has none. +pub fn export_sections(overrides: &Overrides) -> Vec { + use crate::shortcut_sheet::{Row, Section}; + let snapshot = snapshot(); + let km = crate::keymap::keymap_in(&snapshot, overrides); + let backtick = backtick_text(); + let mut tools = Section { title: tl!("Tools").to_string(), rows: vec![] }; + let mut menus: Vec
= vec![]; + for e in snapshot.entries.iter().filter(|e| listed(km.overrides(), e)) { + let shortcut = dialog_shortcuts_with(&km, &e.key, backtick.as_deref()).unwrap_or_default(); + if e.is_tool { + tools.rows.push(Row { name: shown_name(e), shortcut }); + continue; + } + let group = shown_group(&e.group); + let (top, rest) = group.split_once(" › ").unwrap_or((group.as_str(), "")); + let top = if top.is_empty() { tl!(MENU_COMMANDS) } else { top }; + let label = shown_label(e); + let inner = if rest.is_empty() { label.to_string() } else { format!("{rest} › {label}") }; + let name = if e.shows_key { format!("{inner} ({})", e.key) } else { inner }; + match menus.iter_mut().find(|s| s.title == top) { + Some(s) => s.rows.push(Row { name, shortcut }), + None => menus.push(Section { title: top.to_string(), rows: vec![Row { name, shortcut }] }), + } + } + std::iter::once(tools).chain(menus).collect() +} + +/// The file `format` writes for `set` with `overrides`: the sheet on `page`. +fn export_text_file(format: TextFormat, set: &str, overrides: &Overrides, page: crate::shortcut_sheet::PageSize) -> Result, String> { + match format { + TextFormat::Text => Ok(export_text(set, overrides).into_bytes()), + TextFormat::Sheet => { + let title = format!("{} · {}", tl!("Keyboard Shortcuts"), shown_set_name(set)); + crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides), page) + } + TextFormat::Csv => Ok(crate::shortcut_sheet::csv(&export_sections(overrides), ["Group", "Command", "Shortcut"]).into_bytes()), + } +} + +/// The sheet's paper when `pageSize` is left out: A4 when the current document prints on A4 (its +/// print settings, or, with none saved, a first artboard of A4 size either way up), else Letter. +fn default_sheet_page(app: &VectorcraftApp) -> crate::shortcut_sheet::PageSize { + use crate::shortcut_sheet::PageSize; + let Some(st) = app.session.active() else { return PageSize::Letter }; + let a4 = match st.doc.print_setup.clone().and_then(|v| serde_json::from_value::(v).ok()) { + Some(settings) => settings.media == vectorcraft_pdf::Media::A4, + None => st.doc.artboards.first().is_some_and(|a| { + let (w, h) = PageSize::A4.landscape(); + let (long, short) = (a.rect.width().max(a.rect.height()), a.rect.width().min(a.rect.height())); + (long - w).abs() < 1.0 && (short - h).abs() < 1.0 + }), + }; + if a4 { PageSize::A4 } else { PageSize::Letter } +} + // ---------- UI commands ---------- pub fn open(app: &mut VectorcraftApp) { @@ -1329,19 +1462,75 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option None, + Ok(Some(f)) => match TextFormat::ALL.into_iter().find(|t| t.name() == f) { + Some(t) => Some(t), + None => { + let key = "format"; + return Some(Err(format!("`{key}` must be one of {}", TextFormat::ALL.map(TextFormat::name).join(", ")))); + } + }, + Err(e) => return Some(Err(e)), + }; + let page = match s("pageSize") { + Ok(None) => default_sheet_page(app), + Ok(Some(n)) => match crate::shortcut_sheet::PageSize::parse(&n) { + Some(page) => page, + None => { + let key = "pageSize"; + return Some(Err(format!( + "`{key}` must be one of {}", + crate::shortcut_sheet::PageSize::ALL.map(crate::shortcut_sheet::PageSize::name).join(", ") + ))); + } + }, + Err(e) => return Some(Err(e)), + }; + // A given path is written as text unless `format` says otherwise; a save dialog offers + // every format (text first) unless `format` names one, and its answer picks the format. + let (path, format) = match path { + Some(path) => (Some(path), format.unwrap_or(TextFormat::Text)), + None => { + let shown = format.unwrap_or(TextFormat::Text); + let filters = format.map_or_else(|| TextFormat::ALL.map(TextFormat::filter).to_vec(), |f| vec![f.filter()]); + let pick = crate::FilePick { filters, ..crate::FilePick::named(&shown.file_name()) }; + match crate::picks::save_with_type(app, &pick) { + Some((answer, file_type)) => { + let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, file_type.as_deref())); + // The format that `format` names, or that a dialog reports as the type + // picked, gives the name its extension. A file already at a path + // changed that way, which the dialog did not check, is replaced only + // after asking. + let typed = format.is_some() || file_type.is_some(); + let path = if typed { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; + let request = crate::picks::PickRequest::Save(pick.clone()); + if path != answer && crate::picks::ask_to_replace(app, request, &answer, file_type.as_deref(), &path) { + return Some(Err("cancelled".into())); + } + (Some(path), picked) + } + None => (None, shown), + } + } + }; + // Its save dialog is open: the file is made and written when it answers. + if path.is_none() && app.file_dialog_open() { + return Some(Err("cancelled".into())); + } + let bytes = match export_text_file(format, &app.ui.shortcut_set, &app.ui.shortcut_overrides, page) { + Ok(bytes) => bytes, + Err(e) => return Some(Err(e)), + }; + match path { Some(path) => match app.services.write.as_mut() { - Some(w) => w(&path, text.as_bytes()).map(|_| json!({"path": path})), + Some(w) => w(&path, &bytes).map(|_| json!({"path": path})), None => Err("no file writer".into()), }, - // Its save dialog is open: the file is written when it answers. - None if app.file_dialog_open() => Err("cancelled".into()), None => match app.services.download.as_mut() { - Some(dl) => dl("VectorCraft Shortcuts.txt", text.as_bytes()).map(|()| Value::Null), - None => Ok(json!({"text": text})), + Some(dl) => dl(&format.file_name(), &bytes).map(|()| Value::Null), + None if format == TextFormat::Sheet => Ok(json!({"pdf": vectorcraft_svg::base64_encode(&bytes)})), + None => Ok(json!({"text": String::from_utf8_lossy(&bytes)})), }, } } @@ -2171,6 +2360,169 @@ mod tests { assert_eq!(*text, expected); } + /// The sheet's sections: Tools first, then each top-level menu once, in the + /// order the dialog first lists a command of it, holding every row the dialog lists with its + /// shortcut, the command named without its top-level menu. + #[test] + fn export_sections_hold_every_listed_row_once_by_top_level_menu() { + let mut ov = Overrides::new(); + crate::keymap::set_override(&mut ov, "edit.preferences", "Ctrl+Alt+Shift+9"); + let (sections, listed_rows, tops) = with_steady_plugins(|| { + let km = keymap_with(&ov); + let listed: Vec = entries().iter().filter(|e| listed(km.overrides(), e)).cloned().collect(); + let mut tops: Vec = vec![]; + for e in listed.iter().filter(|e| !e.is_tool) { + let top = e.group.split(" › ").next().filter(|t| !t.is_empty()).unwrap_or(MENU_COMMANDS).to_string(); + if !tops.contains(&top) { + tops.push(top); + } + } + (export_sections(&ov), listed.len(), tops) + }); + let titles: Vec<&str> = sections.iter().map(|s| s.title.as_str()).collect(); + assert_eq!(titles[0], "Tools"); + assert_eq!(titles[1..], tops.iter().map(String::as_str).collect::>()[..], "one section per top-level menu"); + for menu in ["File", "Edit", "Object", "Type", "Select", "Effect", "View", "Window", "Help"] { + assert!(titles.contains(&menu), "no {menu} section: {titles:?}"); + } + assert_eq!(sections.iter().map(|s| s.rows.len()).sum::(), listed_rows, "every listed row once"); + let prefs = entry("edit.preferences").expect("the Preferences row"); + let top = prefs.group.split(" › ").next().unwrap_or_default().to_string(); + let name = shown_name(&prefs).strip_prefix(&format!("{top} › ")).map(str::to_string).expect("Preferences is in a menu"); + let section = sections.iter().find(|s| s.title == top).expect("its menu's section"); + assert!(section.rows.iter().any(|r| r.name == name && r.shortcut.ends_with('9')), "{name} in {:?}", section.rows); + let pen = sections[0].rows.iter().find(|r| r.shortcut == menus::pretty_shortcut(default_of("tool:pen").unwrap_or_default())); + assert!(pen.is_some(), "the Pen tool's row"); + } + + /// `format` picks the file: text (the default, the same bytes as before) or the PDF sheet. A + /// given path is written as text whatever its extension, and a bad `format` or `pageSize` is an + /// error that writes nothing. + #[test] + fn export_text_command_writes_text_or_a_sheet() { + type Files = std::rc::Rc)>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + w.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + let (files, text) = with_steady_plugins(|| { + written.borrow_mut().clear(); + app.run("shortcuts.exportText", json!({"path": "/a/plain.txt"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/named.txt", "format": "text"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/as-text.pdf"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.pdf", "format": "sheet", "pageSize": "a4"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.txt", "format": "sheet"})).unwrap(); + (written.borrow().clone(), export_text(&app.ui.shortcut_set, &app.ui.shortcut_overrides)) + }); + let [plain, named, as_text, sheet, sheet_as_named] = files.as_slice() else { panic!("{} files", files.len()) }; + for f in [plain, named, as_text] { + assert_eq!(f.1, text.as_bytes(), "{}", f.0); + } + assert!(sheet.1.starts_with(b"%PDF-"), "{}", sheet.0); + assert_eq!(sheet_as_named.0, "/a/sheet.txt", "a path is written as given"); + assert!(sheet_as_named.1.starts_with(b"%PDF-")); + written.borrow_mut().clear(); + let mut err = |p: Value| app.run("shortcuts.exportText", p); + assert_eq!(err(json!({"path": "/a/x", "format": "xlsx"})), Err("`format` must be one of text, sheet, csv".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": "Sheet"})), Err("`format` must be one of text, sheet, csv".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": 3})), Err("`format` must be a string".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "legal"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "A4"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert!(written.borrow().is_empty()); + } + + /// `format: "csv"` writes the CSV file: the `Group,Command,Shortcut` header, then a record per + /// row the dialog lists, every group and row of [`export_sections`] once. Without a file it + /// comes back under `text`. + #[test] + fn export_text_command_writes_a_csv_file() { + type Files = std::rc::Rc)>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let (returned, files, sections) = with_steady_plugins(|| { + app.services.write = None; + written.borrow_mut().clear(); + let returned = app.run("shortcuts.exportText", json!({"format": "csv"})); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + w.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + app.run("shortcuts.exportText", json!({"path": "/a/list.csv", "format": "csv"})).unwrap(); + (returned, written.borrow().clone(), export_sections(&app.ui.shortcut_overrides)) + }); + let [(path, bytes)] = files.as_slice() else { panic!("{} files", files.len()) }; + assert_eq!(path, "/a/list.csv"); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert_eq!(returned.unwrap()["text"].as_str(), Some(text.as_str()), "the same file without a writer"); + assert_eq!(text, crate::shortcut_sheet::csv(§ions, ["Group", "Command", "Shortcut"])); + assert!(text.starts_with("\u{feff}Group,Command,Shortcut\r\nTools,"), "{text}"); + let records = text.matches("\r\n").count(); + assert_eq!(records, 1 + sections.iter().map(|s| s.rows.len()).sum::(), "a header and a record per row"); + for s in §ions { + assert!(text.contains(&format!("\r\n{},", s.title)), "no {} group", s.title); + } + } + + /// With no `pageSize` the sheet is on A4 when the current document prints on A4: its print + /// settings say so, or, with none saved, its first artboard is A4 either way up; else Letter. + #[test] + fn the_sheet_is_on_a4_when_the_document_prints_on_a4() { + use crate::shortcut_sheet::PageSize; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "no document"); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "a Letter artboard"); + app.session.add_document(vectorcraft_doc::Document::new(595.28, 841.89), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "an A4 artboard"); + let printing = |w, h, media| { + let mut doc = vectorcraft_doc::Document::new(w, h); + doc.print_setup = serde_json::to_value(vectorcraft_pdf::PrintSettings { media, ..Default::default() }).ok(); + doc + }; + app.session.add_document(printing(595.28, 841.89, vectorcraft_pdf::Media::Letter), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "an A4 artboard printing on Letter"); + app.session.add_document(printing(612.0, 792.0, vectorcraft_pdf::Media::A4), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "printing on A4"); + } + + /// Without a path, a file writer or a download, `shortcuts.exportText` returns the file: the + /// text file under `text` and the sheet as base64 under `pdf`. + #[test] + fn export_text_without_a_file_returns_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let (text, sheet) = + with_steady_plugins(|| (app.run("shortcuts.exportText", json!({})), app.run("shortcuts.exportText", json!({"format": "sheet"})))); + let text = text.unwrap(); + assert!(text["text"].as_str().unwrap_or_default().starts_with("Keyboard Shortcuts\n"), "{text}"); + let sheet = sheet.unwrap(); + // "%PDF-" in base64. + assert!(sheet["pdf"].as_str().unwrap_or_default().starts_with("JVBERi0"), "{}", sheet.to_string().len()); + } + + /// The save dialog's answer picks the format: the file type it reports, else the extension + /// typed; text for any other. + #[test] + fn the_save_dialogs_answer_picks_the_export_text_format() { + assert_eq!(TextFormat::picked("/a/sheet.PDF", None), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list", Some("pdf")), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list.pdf", Some("txt")), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.txt", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.json", None), TextFormat::Text); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list.txt", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Text), "/a/list.txt"); + assert_eq!(TextFormat::picked("/a/list.CSV", None), TextFormat::Csv); + assert_eq!(TextFormat::picked("/a/list", Some("csv")), TextFormat::Csv); + assert_eq!(TextFormat::with_extension("/a/list.pdf", TextFormat::Csv), "/a/list.csv"); + assert_eq!(TextFormat::with_extension("/a/list.PDF", TextFormat::Sheet), "/a/list.PDF"); + assert_eq!(TextFormat::with_extension("/a/v1.2", TextFormat::Sheet), "/a/v1.2.pdf"); + } + /// The dialog's Import… leaves an action its function key when the imported set gives the key /// to a command, through both Cancel and OK. #[test] diff --git a/crates/ui-egui/src/shortcut_sheet.rs b/crates/ui-egui/src/shortcut_sheet.rs new file mode 100644 index 0000000000..bcd9732381 --- /dev/null +++ b/crates/ui-egui/src/shortcut_sheet.rs @@ -0,0 +1,530 @@ +//! Keyboard Shortcuts › Export Text…'s printable shortcut sheet and CSV file. +//! +//! The rows come from [`crate::shortcut_editor::export_sections`]: a Tools section and one section +//! per top-level menu. The sheet lists the rows that have a shortcut, each section under a colored +//! band with the shortcut on the left and the name on the right, flowed down columns of landscape +//! pages, and is written as a PDF by laying it out as a document. The CSV file lists every row +//! ([RFC 4180](https://www.rfc-editor.org/rfc/rfc4180.txt) quoting, CRLF line ends). + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +/// One section of the list: Tools or a top-level menu, with its rows in the dialog's order. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub title: String, + pub rows: Vec, +} + +/// A row: the command's name within its section and its shortcuts as the dialog shows them (empty +/// when it has none). +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub name: String, + pub shortcut: String, +} + +/// The sheet's paper, used in landscape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageSize { + Letter, + A4, +} + +impl PageSize { + pub const ALL: [Self; 2] = [Self::Letter, Self::A4]; + + /// The `pageSize` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Letter => "letter", + Self::A4 => "a4", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|p| p.name() == s) + } + + /// Width and height of a landscape page in points. + pub fn landscape(self) -> (f64, f64) { + match self { + Self::Letter => (792.0, 612.0), + Self::A4 => (841.89, 595.28), + } + } +} + +/// Whether a spreadsheet would read `s` as a formula: it starts with `=`, `+`, `-` or `@` and has +/// more after it, or starts with a tab or a carriage return. +fn reads_as_formula(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some('=' | '+' | '-' | '@') => chars.next().is_some(), + Some('\t' | '\r') => true, + _ => false, + } +} + +/// A CSV field: a field a spreadsheet would read as a formula starts with an apostrophe, and a +/// field with a comma, a double quote or a line break is quoted, with each double quote doubled. +fn csv_field(s: &str) -> String { + let s = if reads_as_formula(s) { format!("'{s}") } else { s.to_string() }; + if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } +} + +/// The CSV file: a byte order mark, so spreadsheets read it as UTF-8, a header row of `headers`, +/// then one `section,name,shortcut` record per row, each ending in CRLF. +pub fn csv(sections: &[Section], headers: [&str; 3]) -> String { + let mut out = String::from("\u{feff}"); + let mut record = |fields: [&str; 3]| { + out += &fields.map(csv_field).join(","); + out += "\r\n"; + }; + record(headers); + for s in sections { + for r in &s.rows { + record([&s.title, &r.name, &r.shortcut]); + } + } + out +} + +/// Section band colors, in turn. +const BANDS: [(u8, u8, u8); 9] = [ + (0x2f, 0x6d, 0xb5), + (0xc0, 0x39, 0x2b), + (0x27, 0x86, 0x5f), + (0x8e, 0x44, 0xad), + (0xd3, 0x54, 0x00), + (0x16, 0x87, 0x9a), + (0x9a, 0x7d, 0x0a), + (0x5d, 0x6d, 0x7e), + (0xc2, 0x18, 0x5b), +]; + +const MARGIN: f64 = 30.0; +const TITLE_SIZE: f64 = 15.0; +/// From the top margin to the top of the first column. +const TITLE_SPACE: f64 = 28.0; +const COLUMNS: usize = 4; +const GUTTER: f64 = 12.0; +const BAND_HEIGHT: f64 = 13.0; +const BAND_SIZE: f64 = 8.0; +const ROW_HEIGHT: f64 = 9.5; +const ROW_SIZE: f64 = 7.0; +/// Space above a section that does not start a column. +const SECTION_SPACE: f64 = 6.0; +/// The least and the most of a column's width the shortcuts take. +const SHORTCUT_SHARE: f64 = 0.3; +const MAX_SHORTCUT_SHARE: f64 = 0.5; +/// Space between pages in the document. +const PAGE_GAP: f64 = 36.0; +const FONT: &str = "Source Sans 3"; + +/// The sheet's text style. +fn style(size: f64, bold: bool, fill: Color) -> CharStyle { + CharStyle { + font_family: FONT.into(), + font_style: if bold { "Bold" } else { "Regular" }.into(), + size, + fill: Paint::solid(fill), + ..CharStyle::default() + } +} + +/// The width `text` takes in `style`. +fn width(text: &str, style: &CharStyle) -> f64 { + let t = TextObject::point(Point::ZERO, text, style.clone()); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.width() +} + +/// The most characters of a name or title the sheet measures; no line on a page holds more. +const MAX_FIT_CHARS: usize = 400; + +/// `text`, shortened with an ellipsis to fit in `room`: the longest start of it that fits with the +/// ellipsis, found with a binary search, so a long imported name takes a few layouts. +fn fitted(text: &str, style: &CharStyle, room: f64) -> String { + let chars: Vec = text.chars().take(MAX_FIT_CHARS + 1).collect(); + if chars.len() <= MAX_FIT_CHARS && width(text, style) <= room { + return text.to_string(); + } + let cut = |n: usize| chars.iter().take(n).collect::().trim_end().to_string() + "…"; + let (mut lo, mut hi) = (0, chars.len().min(MAX_FIT_CHARS)); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if width(&cut(mid), style) <= room { lo = mid } else { hi = mid - 1 } + } + if lo == 0 && width("…", style) > room { String::new() } else { cut(lo) } +} + +/// Builds the sheet's document: one artboard per page. +struct Sheet { + doc: Document, + page: (f64, f64), + /// Pages so far. + pages: usize, + /// The column being filled, 0-based, and the top of its free space. + column: usize, + y: f64, + /// The shortcut column's width; the names start there. + split: f64, +} + +impl Sheet { + fn origin(&self) -> f64 { + (self.pages - 1) as f64 * (self.page.0 + PAGE_GAP) + } + + fn column_width(&self) -> f64 { + (self.page.0 - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64 + } + + fn column_left(&self) -> f64 { + self.origin() + MARGIN + self.column as f64 * (self.column_width() + GUTTER) + } + + fn top(&self) -> f64 { + MARGIN + TITLE_SPACE + } + + fn bottom(&self) -> f64 { + self.page.1 - MARGIN + } + + fn add(&mut self, mut n: Node) { + n.id = self.doc.alloc_id(); + let Some(layer) = self.doc.default_layer() else { return }; + let len = self.doc.children(Some(layer)).map_or(0, |c| c.len()); + // Insertion into the document's own layer only fails for a node id already used, and + // every node gets a new id above. + let _ = self.doc.insert(Some(layer), len, n); + } + + fn rect(&mut self, r: Rect, fill: Color) { + self.add(Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(fill), Paint::None, 0.0))); + } + + fn text(&mut self, at: Point, text: &str, style: CharStyle) { + if !text.is_empty() { + self.add(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(at, text, style))))); + } + } + + /// Starts a page with `title` at its top. + fn new_page(&mut self, title: &str) { + self.pages += 1; + let rect = Rect::new(self.origin(), 0.0, self.origin() + self.page.0, self.page.1); + if self.pages == 1 { + if let Some(a) = self.doc.artboards.first_mut() { + a.rect = rect; + } + } else if let Some(mut a) = self.doc.artboards.first().cloned() { + a.id = self.pages as u32; + a.name = format!("Artboard {}", self.pages); + a.rect = rect; + self.doc.artboards.push(a); + } + let style = style(TITLE_SIZE, true, Color::BLACK); + let room = self.page.0 - 2.0 * MARGIN; + let shown = fitted(title, &style, room); + self.text(Point::new(self.origin() + MARGIN, MARGIN + TITLE_SIZE), &shown, style); + self.column = 0; + self.y = self.top(); + } + + /// Room for `height` more in the column, else the next column or page. + fn make_room(&mut self, height: f64, title: &str) -> bool { + if self.y + height <= self.bottom() { + return false; + } + if self.column + 1 < COLUMNS { + self.column += 1; + self.y = self.top(); + } else { + self.new_page(title); + } + true + } + + fn band(&mut self, title: &str, color: Color) { + let (x, w) = (self.column_left(), self.column_width()); + self.rect(Rect::new(x, self.y, x + w, self.y + BAND_HEIGHT), color); + let style = style(BAND_SIZE, true, Color::WHITE); + let shown = fitted(title, &style, w - 8.0); + self.text(Point::new(x + 4.0, self.y + BAND_HEIGHT - 3.6), &shown, style); + self.y += BAND_HEIGHT; + } + + /// Draws one line of a row: `key` on the left and, on the row's first line, `name` on the right. + fn line(&mut self, key: &str, name: Option<&str>, shaded: bool) { + let (x, w) = (self.column_left(), self.column_width()); + if shaded { + self.rect(Rect::new(x, self.y, x + w, self.y + ROW_HEIGHT), Color::rgb8(0xee, 0xf0, 0xf2)); + } + let baseline = self.y + ROW_HEIGHT - 2.6; + self.text(Point::new(x + 3.0, baseline), key, shortcut_style(key, self.split - 6.0)); + if let Some(name) = name { + let plain = style(ROW_SIZE, false, Color::BLACK); + let name = fitted(name, &plain, w - self.split - 3.0); + self.text(Point::new(x + self.split, baseline), &name, plain); + } + self.y += ROW_HEIGHT; + } +} + +/// The style of shortcut `key` in `room`: a shortcut is never cut short, and one too wide for +/// `room` is set smaller. +fn shortcut_style(key: &str, room: f64) -> CharStyle { + let bold = style(ROW_SIZE, true, Color::BLACK); + let wide = width(key, &bold); + if wide > room && wide > 0.0 && room > 0.0 { style(ROW_SIZE * room / wide, true, Color::BLACK) } else { bold } +} + +/// The separate shortcuts of a row's shortcut text, which the dialog joins with ` · `; a row has at +/// least one line. +fn shortcuts(text: &str) -> Vec<&str> { + let keys: Vec<&str> = text.split(" · ").filter(|s| !s.is_empty()).collect(); + if keys.is_empty() { vec![""] } else { keys } +} + +/// The sheet as a document on `page`-sized landscape artboards: `title` at the top of each page, +/// then each section that has a row with a shortcut under a colored band, its rows with a shortcut +/// below it (shortcut on the left, name on the right), flowed down the columns and onto further +/// pages. A section that continues in the next column repeats its band there. A row with several +/// shortcuts has a line for each, kept in one column unless the row is taller than a column, and a +/// shortcut is never shortened; a name too long for its column ends in an ellipsis. +pub fn sheet_document(title: &str, sections: &[Section], page: PageSize) -> Document { + let page = page.landscape(); + let mut s = Sheet { doc: Document::new(page.0, page.1), page, pages: 0, column: 0, y: 0.0, split: 0.0 }; + // The shortcut column is as wide as the widest shortcut, within limits. + let bold = style(ROW_SIZE, true, Color::BLACK); + let widest = sections.iter().flat_map(|sec| &sec.rows).flat_map(|r| shortcuts(&r.shortcut)).map(|k| width(k, &bold)).fold(0.0, f64::max); + let w = s.column_width(); + s.split = (widest + 6.0).clamp(w * SHORTCUT_SHARE, w * MAX_SHORTCUT_SHARE); + s.doc.title = title.to_string(); + s.new_page(title); + // The most a row takes in one piece: a column below its band. + let column = s.bottom() - s.top() - BAND_HEIGHT; + let whole = |row: &Row| shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT <= column; + let piece = |row: &Row| if whole(row) { shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT } else { ROW_HEIGHT }; + let listed = sections.iter().filter(|sec| sec.rows.iter().any(|r| !r.shortcut.is_empty())); + for (i, sec) in listed.enumerate() { + let (r, g, b) = BANDS[i % BANDS.len()]; + let color = Color::rgb8(r, g, b); + let space = if s.y > s.top() { SECTION_SPACE } else { 0.0 }; + let mut rows = sec.rows.iter().filter(|r| !r.shortcut.is_empty()).peekable(); + let first = rows.peek().map_or(ROW_HEIGHT, |r| piece(r)); + if !s.make_room(space + BAND_HEIGHT + first, title) { + s.y += space; + } + s.band(&sec.title, color); + for (n, row) in rows.enumerate() { + if s.make_room(piece(row), title) { + s.band(&sec.title, color); + } + let split = !whole(row); + for (k, key) in shortcuts(&row.shortcut).into_iter().enumerate() { + // A row taller than a column goes on in the next one, line by line. + if k > 0 && split && s.make_room(ROW_HEIGHT, title) { + s.band(&sec.title, color); + } + s.line(key, (k == 0).then_some(row.name.as_str()), n % 2 == 1); + } + } + } + s.doc +} + +/// The sheet as a PDF, one page per artboard of [`sheet_document`]. +pub fn sheet_pdf(title: &str, sections: &[Section], page: PageSize) -> Result, String> { + let doc = sheet_document(title, sections, page); + let opts = vectorcraft_pdf::PdfOptions { title: Some(title.to_string()), ..Default::default() }; + vectorcraft_pdf::export(&doc, &opts).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(name: &str, shortcut: &str) -> Row { + Row { name: name.into(), shortcut: shortcut.into() } + } + + /// Every type object in `doc`, in stacking order: its text, its style and its left edge. + fn text_objects(doc: &Document) -> Vec<(String, CharStyle, f64)> { + let mut out = vec![]; + let Some(layer) = doc.default_layer() else { return out }; + for n in doc.children(Some(layer)).into_iter().flatten() { + if let NodeKind::Text(t) = &n.kind { + out.push((t.plain_text(), t.first_style(), t.xf.translation().x)); + } + } + out + } + + /// The text of every type object in `doc`, in stacking order. + fn texts(doc: &Document) -> Vec { + text_objects(doc).into_iter().map(|(t, ..)| t).collect() + } + + /// Every node of `doc` lies on one of its pages. + fn assert_on_pages(doc: &Document) { + let l = doc.default_layer().unwrap_or(NodeId(0)); + for n in doc.children(Some(l)).into_iter().flatten() { + let Some(b) = n.geometric_bounds() else { continue }; + let on = |a: &vectorcraft_doc::Artboard| { + let r = a.rect.inflate(0.5, 0.5); + r.union(b) == r + }; + assert!(doc.artboards.iter().any(on), "{b:?} is off the pages"); + } + } + + /// A field with a comma, a double quote or a line break is quoted, with its double quotes + /// doubled; other fields are written as they are, and each record ends in CRLF. + #[test] + fn csv_quotes_fields_with_commas_quotes_and_line_breaks() { + let sections = [ + Section { title: "Edit".into(), rows: vec![row("Paste in Front, Place", "Ctrl+F"), row("Say \"Hi\"", "")] }, + Section { title: "Two\nLines".into(), rows: vec![row("Plain", "Ctrl+,")] }, + ]; + let text = csv(§ions, ["Group", "Command", "Shortcut"]); + assert_eq!( + text, + "\u{feff}Group,Command,Shortcut\r\nEdit,\"Paste in Front, Place\",Ctrl+F\r\nEdit,\"Say \"\"Hi\"\"\",\r\n\"Two\nLines\",Plain,\"Ctrl+,\"\r\n" + ); + } + + /// A field a spreadsheet would read as a formula starts with an apostrophe; a lone `+`, `-`, + /// `=` or `@` key and other fields are written as they are. + #[test] + fn csv_keeps_fields_from_reading_as_formulas() { + let sections = [Section { + title: "Plug-ins".into(), + rows: vec![row("=HYPERLINK(\"x\")", "+"), row("@Sum", "-"), row("-Minus", "- · Ctrl+-"), row("Tab\tName", "=")], + }]; + let text = csv(§ions, ["Group", "Command", "Shortcut"]); + assert_eq!( + text, + "\u{feff}Group,Command,Shortcut\r\nPlug-ins,\"'=HYPERLINK(\"\"x\"\")\",+\r\nPlug-ins,'@Sum,-\r\nPlug-ins,'-Minus,'- · Ctrl+-\r\nPlug-ins,Tab\tName,=\r\n" + ); + assert_eq!(csv_field("\tx"), "'\tx"); + assert_eq!(csv_field("\rx"), "\"'\rx\""); + } + + /// The sheet lists the rows that have a shortcut and leaves out the others, and a section with + /// no shortcut at all has no band. + #[test] + fn sheet_leaves_out_rows_and_sections_without_a_shortcut() { + let sections = [ + Section { title: "Tools".into(), rows: vec![row("Pen", "P"), row("Unbound Tool", "")] }, + Section { title: "Empty Menu".into(), rows: vec![row("Nothing", "")] }, + Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }, + ]; + let doc = sheet_document("Keyboard Shortcuts · Custom", §ions, PageSize::Letter); + let t = texts(&doc); + assert_eq!(t, ["Keyboard Shortcuts · Custom", "Tools", "P", "Pen", "Edit", "Ctrl+C", "Copy"]); + } + + /// Each page is a landscape artboard of the paper picked, and rows that do not fit on one page + /// go on to more pages of the same size, each with the title. + #[test] + fn sheet_pages_are_landscape_pages_of_the_paper_picked() { + let rows: Vec = (0..600).map(|i| row(&format!("Command {i}"), &format!("Ctrl+{i}"))).collect(); + let sections = [Section { title: "Edit".into(), rows }]; + for (page, (w, h)) in [(PageSize::Letter, (792.0, 612.0)), (PageSize::A4, (841.89, 595.28))] { + let doc = sheet_document("Sheet", §ions, page); + assert!(doc.artboards.len() >= 2, "{page:?}: {} pages", doc.artboards.len()); + for a in &doc.artboards { + assert!((a.rect.width() - w).abs() < 1e-9 && (a.rect.height() - h).abs() < 1e-9, "{page:?}: {:?}", a.rect); + } + let t = texts(&doc); + assert_eq!(t.iter().filter(|s| *s == "Sheet").count(), doc.artboards.len(), "a title on every page"); + assert_eq!(t.iter().filter(|s| s.starts_with("Command ")).count(), 600, "every row once"); + assert_on_pages(&doc); + // Each column the section takes starts with its band. + let mut columns: Vec = vec![]; + for (_, _, x) in text_objects(&doc).iter().filter(|(t, ..)| t.starts_with("Command ")) { + if !columns.iter().any(|c| (c - x).abs() < 1e-6) { + columns.push(*x); + } + } + assert!(columns.len() > COLUMNS, "{page:?}: {} columns", columns.len()); + assert_eq!(t.iter().filter(|s| *s == "Edit").count(), columns.len(), "{page:?}: a band in every column"); + } + let pdf = sheet_pdf("Sheet", &[Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }], PageSize::A4).unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + assert_eq!(PageSize::parse("a4"), Some(PageSize::A4)); + assert_eq!(PageSize::parse("A4"), None); + assert_eq!(PageSize::parse("legal"), None); + } + + /// A row with more shortcuts than a column holds goes on in the next column, under its band + /// again, and stays on the pages. + #[test] + fn a_row_taller_than_a_column_goes_on_in_the_next() { + let keys: Vec = (0..150).map(|i| format!("Ctrl+F{i}")).collect(); + let sections = [Section { title: "Edit".into(), rows: vec![row("Many", &keys.join(" · ")), row("After", "Ctrl+A")] }]; + let doc = sheet_document("Sheet", §ions, PageSize::Letter); + assert_on_pages(&doc); + let t = texts(&doc); + for k in &keys { + assert_eq!(t.iter().filter(|s| *s == k).count(), 1, "{k}"); + } + assert_eq!(t.iter().filter(|s| *s == "Many").count(), 1); + assert!(t.iter().filter(|s| *s == "Edit").count() >= 3, "{t:?}"); + assert!(t.contains(&"After".to_string())); + } + + /// The sheet's font has the macOS modifier symbols the key names use, and the ellipsis. + #[test] + fn the_sheets_font_has_the_key_name_characters() { + let db = vectorcraft_text::FontDb::global(); + for face in ["Regular", "Bold"] { + let f = db.face(FONT, face).expect("the bundled face"); + for c in "⌃⌥⇧⌘…".chars() { + assert!(f.covers(c), "{face} lacks {c} (U+{:04X})", c as u32); + } + } + } + + /// A row with several shortcuts lists each on a line of its own, and a shortcut too wide for + /// its column is kept whole and set smaller to fit. + #[test] + fn sheet_keeps_every_shortcut_of_a_row_whole() { + let long = "Ctrl+Alt+Shift+".repeat(6) + "PageDown"; + let sections = [Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C · Ctrl+Insert"), row("Long", &long)] }]; + let objects = text_objects(&sheet_document("Sheet", §ions, PageSize::Letter)); + let t: Vec<&str> = objects.iter().map(|(t, ..)| t.as_str()).collect(); + assert_eq!(t, ["Sheet", "Edit", "Ctrl+C", "Copy", "Ctrl+Insert", long.as_str(), "Long"]); + let (_, short, _) = &objects[2]; + assert_eq!(short.size, ROW_SIZE); + let (_, set, _) = &objects[5]; + let (w, _) = PageSize::Letter.landscape(); + let column = (w - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64; + assert!(set.size < ROW_SIZE, "{}", set.size); + assert!(width(&long, set) <= column * MAX_SHORTCUT_SHARE - 6.0 + 0.01, "{} wide", width(&long, set)); + } + + /// A name too long for its column is cut short with an ellipsis. + #[test] + fn a_long_name_is_cut_short_to_fit_its_column() { + let long = "Command ".repeat(20); + let doc = sheet_document("Sheet", &[Section { title: "Edit".into(), rows: vec![row(&long, "Ctrl+L")] }], PageSize::Letter); + let shown = texts(&doc).into_iter().find(|t| t.starts_with("Command")).unwrap_or_default(); + assert!(shown.ends_with('…') && shown.len() < long.len(), "{shown}"); + let plain = style(ROW_SIZE, false, Color::BLACK); + let room = 100.0; + assert!(width(&shown, &plain) > 0.0); + let fit = fitted(&long, &plain, room); + assert!(width(&fit, &plain) <= room, "{fit}"); + let one_more = long.chars().take(fit.chars().count()).collect::().trim_end().to_string() + "…"; + assert!(width(&one_more, &plain) > room || one_more == fit, "{fit} is the longest start that fits"); + // A name far longer than any line is measured only in part. + let huge = "x".repeat(1_000_000); + let title = fitted(&huge, &style(TITLE_SIZE, true, Color::BLACK), 700.0); + assert!(title.ends_with('…') && title.chars().count() <= MAX_FIT_CHARS + 1, "{} chars", title.chars().count()); + } +} diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index d6a06960bb..9d4ae15493 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -456,7 +456,9 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { d.fields.insert("set".into(), json!("Custom")); click(&mut app, "Export Text…", dialogs); match shown.requests().as_slice() { - [PickRequest::Save(pick)] => assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..])])), + [PickRequest::Save(pick)] => { + assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..]), ("CSV", &["csv"][..])])) + } other => panic!("{other:?}"), } shown.answer(&["/keys/list.txt"]); @@ -474,6 +476,76 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "the dialog stays open"); } +/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet or the CSV file +/// for a name typed with `.pdf` or `.csv`, and for a type the dialog reports with a name typed +/// without an extension, that type's file under the name with its extension. +#[test] +fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() { + for (answer, path, start) in [ + (&["/keys/list.pdf"][..], "/keys/list.pdf", &b"%PDF-"[..]), + (&["/keys/list.csv"][..], "/keys/list.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]), + (&["/keys/table", "csv"][..], "/keys/table.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]), + (&["/keys/sheet", "pdf"][..], "/keys/sheet.pdf", &b"%PDF-"[..]), + (&["/keys/plain", "txt"][..], "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]), + ] { + let (mut app, shown, _) = app(); + type Files = Rc)>>>; + let files: Files = Default::default(); + let f = files.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + f.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(answer); + poll(&mut app); + let files = files.borrow(); + let [(written, bytes)] = files.as_slice() else { panic!("{files:?}") }; + assert_eq!(written, path); + assert!(bytes.starts_with(start), "{path}: {:?}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)])); + } +} + +/// `shortcuts.exportText` with a `format` and no `path` gives the name its save dialog answers +/// that format's extension, though the dialog reports no file type. +#[test] +fn export_text_with_a_format_gives_the_answered_name_its_extension() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + let _ = app.run("shortcuts.exportText", json!({"format": "sheet"})); + shown.answer(&["/keys/sheet"]); + poll(&mut app); + assert_eq!(*written.borrow(), ["/keys/sheet.pdf"]); +} + +/// A name that Export Text… gives the picked type's extension names a file the save dialog did +/// not check: when one is there, a question asks before replacing it and nothing is written +/// meanwhile. +#[test] +fn keyboard_shortcuts_export_text_asks_before_replacing_a_file_its_extension_names() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/keys/list.pdf")); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(&["/keys/list.txt", "pdf"]); + poll(&mut app); + assert!(written.borrow().is_empty(), "{:?}", written.borrow()); + let d = app.ui.dialog.as_ref().expect("a question"); + assert_eq!(d.str("path"), "/keys/list.pdf"); +} + /// Keyboard Shortcuts' Import… opens a shortcut set another app saved as text (`.kys`) in Import /// Shortcut Set over the dialog when its file dialog answers, and the dialog's working set stays in /// Keyboard Shortcuts, which Cancel shows again. 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/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index df003ddb01..87bc207950 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -89,7 +89,13 @@ fn save_panels_show_the_file_type_they_write() { app.run("shortcuts.export", json!({})).unwrap(); assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sets", &["json"][..])]), "Keyboard Shortcuts › Export…"); app.run("shortcuts.exportText", json!({})).unwrap(); - assert_eq!(last_shown(&shown), FilePick::filters([("Text", &["txt"][..])]), "Keyboard Shortcuts › Export Text…"); + assert_eq!( + last_shown(&shown), + FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..]), ("CSV", &["csv"][..])]), + "Keyboard Shortcuts › Export Text…" + ); + app.run("shortcuts.exportText", json!({"format": "sheet"})).unwrap(); + assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sheet", &["pdf"][..])]), "shortcuts.exportText with a format"); let presets = [ ("pdf.preset.save", json!({"name": "Mine"}), "pdf.preset.export", "PDF presets", pdfcmds::PRESET_EXTS), ("print.presets.save", json!({"name": "Mine"}), "print.presets.export", "Print presets", printpresets::PRESET_EXTS), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5a5b96ff50..b3f3fe9b19 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1068,6 +1068,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, …}` | diff --git a/docs/development.md b/docs/development.md index 100786bb83..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)) | diff --git a/docs/effects-parity.md b/docs/effects-parity.md index fcc3ae5b52..74d2ac8f63 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, 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)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); 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, 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)) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7a73bdc4c1..4278489b61 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -140,7 +140,7 @@ private editing data. VectorCraft: document's defaults and the normal character style carry 1. A run with both Tate-chu-yoko and Standard Vertical Roman Alignment is written as Tate-chu-yoko, with the type attributes warning. Type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, turned or unevenly scaled area type and type on a path, area type in an open frame, - type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of + type on an open path whose ends meet, area type whose wrap cannot be reconstructed from plain saved paths, compound paths or groups, type of only white space, threads of type on a path, threads whose frames differ in orientation, type and stories past the sizes VectorCraft's reader reads, and type with inline graphics, ruby, gradient or pattern paint or an appearance or opacity mask of its own, other patterns, other clipping objects and live objects (placed documents included) are written as plain filled and stroked paths, and freeform gradients, gradients along diff --git a/docs/gaps.md b/docs/gaps.md index 1647b6331e..6be95c171b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -38,6 +38,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); 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. | @@ -469,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. @@ -894,6 +897,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 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. | @@ -1141,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 2098f154e5..a3a24a39fd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 @@ -667,7 +672,7 @@ sampler. | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | -| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | +| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners; an ellipse takes `anchors`, 2–1000, default 4). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | @@ -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 @@ -1187,6 +1195,18 @@ pixels per point, and the file stores the resolution that results, as with `ppi` either one wins over `ppi` and `scale`. A value that is not a positive number is refused. Export for Screens rows keep their own size (`scale: "512w"`). +`shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). +Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many +anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a +click with the Ellipse tool) has an Anchors field that sends it, as the nearest whole number from 2 to 1000 (an +empty field, or text that is not a number, sends 4). The count confirmed last is kept as the Ellipse tool's `anchors` +option (`tool.setOption`), and the next Ellipse dialog opens on it. A drag with the Ellipse tool still draws a live +ellipse. + +```json +{"name":"run_command","arguments":{"command":"shape.ellipse","params":{"x":100,"y":100,"width":120,"height":80,"anchors":6}}} +``` + Long-tail commands: ```json @@ -1313,7 +1333,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 @@ -1420,9 +1440,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 @@ -2018,9 +2040,10 @@ and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `o `enhanced` in `imageTrace.make` and `imageTrace.makeAndExpand`. A null is read as a key left out. These commands refuse a string or another value that is not a number with `` `radius` must be a number, not "2" ``, -naming the key, and change nothing: `radius` in `shape.rectangle`; `sides` and `rotation` in `shape.polygon`; -`radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, `brightness`, `growth`, `fuzziness`, -`rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and +naming the key, and change nothing: `radius` in `shape.rectangle`; `anchors` in `shape.ellipse` (a number that is +not a whole number from 2 to 1000 gets `` `anchors` must be a whole number between 2 and 1000 (got 2.5) ``); `sides` +and `rotation` in `shape.polygon`; `radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, +`brightness`, `growth`, `fuzziness`, `rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and `ringSeed` in `shape.flare` (`seed` must also be a whole number of at least 0, and `ringSeed` a whole number from 0 to 2^53 - 1); `decay` and `segments` in `shape.spiral`; `rows` and `columns` in `shape.rectangularGrid`; `concentric` and `radial` in `shape.polarGrid`; `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`; @@ -3271,16 +3294,24 @@ horizontal guide between its top and bottom. Released anywhere else, it makes no These families are in the live catalog (`command_list` / `vectorcraft://commands`); the prompt `trace-and-style` already walks Image Trace. Short agent entry points: -- Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic` and `type`: - `static`|`dynamic`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, ids?}`, - `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns +- Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: + `static`|`dynamic` and `alignToPixelGrid`), + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 or above 1 puts a guide outside the art, and the art then scales by the cells it falls in; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is - Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), + Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog; + `alignToPixelGrid` is Symbol Options › Align to Pixel Grid, off by default: when it is on, the horizontal and + vertical straight segments of the paths in the symbol's art snap to whole points (half points for an odd centered + stroke) as the art is drawn at the symbol's natural size, its stroke weights become whole points, and each instance + placed at that size, reflected across one axis or not, moves to whole points and goes back to them after every move; + VectorCraft leaves a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's + art, where it is, snaps the art again after it is edited, and does not count + instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has + adds no undo step), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after `object.resetBoundingBox`; a hidden or locked instance's art stays hidden or locked and is not selected), `symbol.replace`, @@ -3374,6 +3405,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 @@ -3547,6 +3586,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 @@ -3847,6 +3891,15 @@ already walks Image Trace. Short agent entry points: `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 @@ -3956,11 +4009,11 @@ already walks Image Trace. Short agent entry points: edges joined to it end to end that draw with the stroke paint `match`, and `samePaint` paints every edge of the group that draws with that stroke paint; the stroke's weight is not compared. An edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully - transparent or has no such stroke. Each click of a double-click or triple-click runs as it - arrives and is its own undo step 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; + 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 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 place of its topmost fill; its strokes, their order and the face's own visibility, opacity and blending mode stay as @@ -3974,10 +4027,12 @@ already walks Image Trace. Short agent entry points: `"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.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. + takes `through`, at most 4096 ids of the group's edges, each given once, that the join counts as drawing with `match` + whatever they draw with now; a hidden edge among them is still skipped. The tool passes each other edge of the group + that either of the double-click's two clicks painted and that drew with `match` before that click. `through` with + another scope, or one that is not an array of the group's edge ids or names an edge twice, is an error and changes + nothing. `livePaint.fill` refuses a `scope` other than `"one"` with `points`. Both replies add `count`, the number of + faces or edges the click reaches, including those that already had the paint. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the @@ -4510,9 +4565,10 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar `exclude: true` keeps its colours. A row's `from` may be an empty list: the row recolors nothing, adds no library swatch with `limitTo` and gives `group` no color, unless it has `added: true` (a color the Edit tab's Add Color tool added): without `groupColors`, its new color then joins `group` after the new colors of the rows with current colors. +`recolor.randomize` leaves a row without current colors as it is and shuffles only the rows that hold current colors. `recolor.randomize` and `recolor.weigh` keep such a row, and `recolor.randomize` keeps its `added`. A row without `from`, or with a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside -Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click another row and Merge to move its colors into it. An +Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An empty row does not count toward Colors. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo @@ -5748,9 +5804,20 @@ 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. +`path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside +it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool +reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133)). +Closed shapes lose the rectangle's area, and open paths are cut where they cross its edges. The tip's size, angle, +roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or +`points` and `rect` together is refused, and when nothing is erased no undo step is added. In the desktop app an +Alt-drag with the Eraser draws the marquee from the press point to the pointer, Alt+Shift keeps it square on its +larger side, and Escape cancels it. + These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in `path.reshapeSegment` and `object.blend.spine.reshapeSegment`; `x`, `y` and `t` in `path.curvatureEdit`; `x` and `y` @@ -5855,7 +5922,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. @@ -5928,7 +5995,11 @@ 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 @@ -6319,18 +6390,49 @@ path and label, with its id when the row shows it, and the key runs what a click {id}`. A removed plug-in's row goes away and its key runs nothing; its shortcut stays saved and applies again when a plug-in with the same id is installed. -`shortcuts.exportText {path?}` saves the current set's shortcut list as a UTF-8 text file, as Edit › Keyboard -Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard Shortcuts" line -and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each section lists the -rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per row, with the name, a -tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut ends after the tab. -Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that cannot be written, -returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's [Export keyboard -shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) +`shortcuts.exportText {path?, format?, pageSize?}` saves the current set's shortcut list as a UTF-8 text file, as +Edit › Keyboard Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard +Shortcuts" line and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each +section lists the rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per +row, with the name, a tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut +ends after the tab. Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that +cannot be written, returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's +[Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes saving the list from the Keyboard Shortcuts dialog as a text file, and does not describe its layout. +`format` picks the file: `"text"` (the default) writes the text file above, `"sheet"` a printable shortcut sheet as a +PDF and `"csv"` a CSV file. A `path` is written as given, in the format `format` names, or as text without `format`. +In the desktop app, without `path`, the save dialog offers the three formats (Text, Shortcut sheet and CSV, Text first) +unless `format` names one, and the file type picked in it decides. When `format` names a format, or the dialog reports +the type picked, the name the dialog returns gets that format's extension (`.txt`, `.pdf` or `.csv`): one of these +extensions is replaced, and the extension is added to any other name. When that names a file that is already there, a +question asks before replacing it. The web app downloads the format `format` names, text without it. With no file +dialog, file writer or download, the command returns the file: the text file and the CSV file as `text`, the sheet in +base64 as `pdf`. A `format` other than `"text"`, `"sheet"` or `"csv"`, or a `pageSize` other than `"letter"` or +`"a4"` (lowercase), returns an error, and nothing is written. + +The shortcut sheet lists the rows that have a shortcut in groups: the Tools rows under the Tools group, then each +top-level menu as a group, in the order the dialog first lists a command of it, with the command named without its +top-level menu. The group names, command names and shortcuts are in the UI language, as the dialog shows them. Each +group has a colored band with its name, and below it the rows, the shortcut on the left and the name on the right. The +groups flow down four columns of landscape pages and onto more pages when they do not fit. `pageSize` is `"letter"` +(792 × 612 pt) or `"a4"` (841.89 × 595.28 pt). Without it the sheet is on A4 when the current document prints on A4 +(its print settings, or, with none saved, a first artboard of A4 size), and on Letter otherwise. Each page is titled +with "Keyboard Shortcuts" and the set's name. A group that continues in the next column repeats its band there. A row +with several shortcuts has a line for each, kept in one column unless the row is taller than a column. A shortcut is +never shortened: one too wide for its column is set smaller. A name too long for its column ends in "…". The type is +Source Sans 3, which VectorCraft bundles and which has the macOS modifier symbols (⌃ ⌥ ⇧ ⌘). Characters it does not +have are drawn in another font the app has loaded, when one has them. The layout is VectorCraft's own. + +The CSV file is UTF-8 with a byte order mark, with CRLF line ends and fields quoted as +[RFC 4180](https://www.rfc-editor.org/rfc/rfc4180.txt) describes. Its header row is `Group,Command,Shortcut` in every +UI language. Each row the dialog lists has one record, in the sheet's groups and with names and shortcuts in the UI +language, and a row with no shortcut has an empty Shortcut field. A field that starts with `=`, `+`, `-` or `@` and has +more after it, or that starts with a tab or a carriage return, starts with an apostrophe (`'`). + ```json {"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.txt"}}} +{"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.pdf","format":"sheet","pageSize":"a4"}}} ``` The desktop app adds its active artboard, the one the Artboards panel highlights, to the `object.align`, @@ -7014,8 +7116,12 @@ A saved or Recent preset whose size (up to 3,999,856 pt), `artboards` (1 to 1,000), spacing (0 to 100,000 pt) or bleed (0 to 72 pt a side) lies outside those ranges is read with the nearer end of each range, and a size of 0 or less is read as 1 pt. The desktop app's `file.newDialog` (Cmd/Ctrl+N) opens the New Document dialog on the first Recent entry, or on the -Print category's Letter while Recent is empty. `file.newWithoutDialog` (Cmd/Ctrl+Alt+N) runs `file.new` with those -settings and the next untitled name, without opening the dialog, and returns what `file.new` returns. +Print category's Letter while Recent is empty. The dialog opens in Preferences › Units › General (`unitsGeneral`), +also when the Recent entry was made in other units. An entry made in pixels, and an entry that is a saved preset in +the units it was saved in, keep their units. Clicking another Recent or Saved card brings back the units that card was +made in. Units chosen in the dialog's Units menu, or set with `ui.dialog.set` (the `units` field), stay when another +tab or preset is chosen. These are VectorCraft's own rules. `file.newWithoutDialog` (Cmd/Ctrl+Alt+N) runs `file.new` +with those settings and the next untitled name, without opening the dialog, and returns what `file.new` returns. `window.nextDocument` (Cmd/Ctrl+F6) and `window.previousDocument` (Cmd/Ctrl+Shift+F6) make the next and the previous open document in tab order the current one, as a click on its tab does, and return `{index}`. After the last document comes the first, and before the first document comes the last. From the Home screen they go to the first and the last @@ -7205,7 +7311,10 @@ 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. @@ -7216,7 +7325,8 @@ slices (Place PSD). `showImportOptions: false` places such a file without asking 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. A `showImportOptions` that is not true or false is refused, and nothing is placed. The +`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 @@ -7256,8 +7366,10 @@ 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 @@ -7607,6 +7719,34 @@ written unless the whole batch succeeds puts the saves and exports last, or runs {"name":"run_command","arguments":{"command":"file.info","params":{"author":"Ada","keywords":"poster, fair","rating":4,"copyrightStatus":"copyrighted","copyrightNotice":"© 2026 Ada"}}} ``` +A PDF, `.ai` or `.ait` also opens with the `authorTitle` and `rating` its XMP packet gives (`photoshop:AuthorsPosition`, +`xmp:Rating`, a whole number from 0 to 5). + +Metadata templates (the menu at the top of File Info: Save Metadata Template…, Import…, the saved templates and +Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=278) keep File +Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not blank +or the `Untitled-N` name a new document gets), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, +`copyrightNotice` and `copyrightUrl` that have a value as an XMP packet, using the properties listed above; the dates +are left out. `fields` takes `file.info`'s editable keys in place of the document's values. `name` saves into the +metadata templates folder as `.xmp` (the folder is made when it is missing; a name with characters file systems reject, a dot at either end, or a +device name such as `CON` is refused, and a template of the same name is replaced), `path` writes that file, and with +neither the reply's `data` is the packet; `name` and `path` together are refused. In the app the folder is +`Metadata Templates` in VectorCraft's settings folder; the web build has none. +`file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}` reads one template (a file, a template in the +folder, or the packet as text; at most 8 MB, more than any saved template holds) and merges it in one undo step, recording nothing when no field changes. +`mode` is VectorCraft's own name for the three ways: `replace` clears the fields a template can hold (not the title) +and takes the template's, `keep` keeps the fields and takes each one the template gives, and `append` keeps the fields, +adds the template's keywords and takes its other fields only where the field is empty. A value `file.info` would +refuse is left out. With `apply: false` nothing changes and the reply is the merged File Info, merged into `base` (the +fields as `file.info` takes them) when given; the File Info dialog uses this for Import. A missing or bad `mode`, a +file that is not XMP and a file over 8 MB are refused. `file.info.templates {create?}` lists the folder's `.xmp` files +(the first 1,000 by name) as `{name, file, path}`, with the `folder` where the caller's file access shows full +paths; `create: true` makes the folder first. `applyTemplate`'s `name` takes either a listed `name` or its `file`. + +```json +{"name":"run_command","arguments":{"command":"file.info.applyTemplate","params":{"name":"Studio","mode":"append"}}} +``` + ## Document Raster Effects Settings `document.rasterEffectsSettings` holds how raster effects (shadows, glows, blurs, feathers) become images when PDF @@ -8715,7 +8855,10 @@ path is that path, under the even-odd rule, so the image shows only inside it. T that can be edited or released. `file.place` answers `image`, the id of the image in the clip group. The [import options help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) says that a file imported as one flattened image keeps the document's clipping path when it has one. `links.update` -and `links.relink` read the file's pixels again and leave the clip group and its clipping path as they are. Files that name no clipping path, or name a path +and `links.relink` read the file again: the clip group's clipping path becomes the one the new file names, under the +even-odd rule, and the clip group stays as a plain group of the image when the new file names none. A plain image relinked to such a +file goes into a clip group of its path. A clip group whose clipping path was changed in the document, or whose fill rule was, is kept as a +clipping mask, with the file's clip group inside it. Files that name no clipping path, or name a path they don't have, come in as a plain image. `file.place` with `replace` on such a clip group puts a new image, clipped or not, at the scale and rotation of the image in the group. @@ -9609,9 +9752,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 @@ -10104,8 +10253,8 @@ other marks take the values of their letter. Setting one value leaves the other 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 Middle Eastern -Options on, the Character panel shows both fields, blank where the selected characters differ, with -200, -100, -50, +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. @@ -10216,6 +10365,24 @@ off. {"name":"run_command","arguments":{"command":"text.setGlyphAlternate","params":{"id":7,"start":2,"gid":1043}}} ``` +After Alternates for Current Selection, the Glyphs panel's Show menu and panel menu list the OpenType categories the +browsed font has, and choosing one shows the glyphs its features give: characters first, then glyphs no character maps, +which a double-click applies to the selected character as Entire Font does. `text.glyphCategories {family, style?}` +lists them: `{family, style, categories: [{id, name?, glyphs: [glyph id]}]}`, from the single, alternate, multiple and +ligature substitutions of the font's `GSUB` features, each glyph once, in this order: `ligatures` (`liga`, `dlig`, +`hlig`), `swashes` (`swsh`, `cswh`), `stylisticAlternates` (`salt`), `ss01` to `ss20`, `smallCaps` (`smcp`, `c2sc`), +`ornaments` (`ornm`), `fractions` (`frac`, `afrc`, `numr`, `dnom`) and `figures` (`lnum`, `onum`, `pnum`, `tnum`). A +category without glyphs is left out, a stylistic set carries the font's name for it as `name` when the font gives one +(the menu shows that name, else Set N), and contextual lookups are not followed. Without `style` the family's first +style is used. The command refuses a family or style that is not available and a `family` or `style` that is not a +string. The categories, their features, their names and their order are VectorCraft's own; the panel restricting its +glyphs to a category chosen from the Show menu is described in [Glyphs panel +overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html). + +```json +{"name":"run_command","arguments":{"command":"text.glyphCategories","params":{"family":"Source Sans 3","style":"Regular"}}} +``` + ### Alternates as OpenType feature values `text.setGlyphAlternate`'s choice swaps a glyph id into one character and shapes that character apart from its neighbours. diff --git a/docs/roadmap.md b/docs/roadmap.md index e1d6af64fd..da1645efb2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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. | @@ -169,7 +170,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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. | @@ -410,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 b478beeaa8..cbb3b8a31d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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. | @@ -185,7 +186,7 @@ the work list made from it. Deep areas have their own checklists: [UI and intera | 2026-10-22 | minor | PDF import: a gap between glyphs of two sizes reads as a space measured against the smaller size (#3623); mixed-size regression. Scores and hours unchanged. | | 2026-10-21 | minor | PDF import: letter-spaced type keeps its word spaces and gains none between letters; synthetic Tc and glyph-by-glyph regressions. Scores and hours unchanged. | | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | -| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 353 of 375 items wired (94.1%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | +| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 717 of 719 items wired (99.7%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | | **Feature depth** (each area scored by behaviour, weighted) | **~75%** | estimated, area table below | | **Ready for real work, mainstream illustrator** | **~65%** (60–70%) | estimated, see [Ready for real work](#ready-for-real-work) | | **Ready for real work, full Illustrator** (decides the stage) | **~62%** (57–67%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | @@ -210,11 +211,16 @@ tests and the CI gate. See [Calibration](#calibration). Adobe install, its `Info.plist` and `.lproj` folders included, and forbids launching or measuring it. So nothing here is a menu dump or a side-by-side measurement: the numbers come from our own code against Illustrator's public documentation. -- **From the code (measured, origin/main `01e165af`):** - - Menu tree (`crates/ui-egui/src/menus.rs`, laid out in Illustrator's menu order): 348 items bound to - commands, 26 stubs (`todo(…)`/`todos(…)`), so 93.0% of menu items do something (348 and 26 after Snap to Glyph shipped in #3124; 348 and 27 after the - Revolve merge; 350 and 25, 93.3%, after Graph › Design and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate). The menu stubs on `a47d7eec` are Effect › 3D and Materials › Materials, - Edit › Spelling › Check Spelling and Help › VectorCraft Help. +- **From the code (measured, origin/main `01e165af`; the menu tree at `957397e7`):** + - Menu tree (`crates/ui-egui/src/menus/tree.rs` and `submenus.rs`, laid out in Illustrator's menu order): walking + `menu_tree()` at `957397e7` finds 717 items bound to commands and 2 stubs (`todo(…)`), so 99.7% of menu items do + something. The two stubs are Effect › 3D and Materials › Materials and Help › VectorCraft Help; Edit › Spelling › + Check Spelling opens its dialog. The count includes the Effect entries built from the effect catalog. It leaves + out 239 entries in the recent-file, recent-font, saved-selection and saved-view slots and in the Open With, + Scripts, Plug-ins, Type › Font, Effect › SVG Filters and View › Perspective Grid preset submenus, some of which + also hold built-in commands. Earlier counts covered fewer entries: 348 items and 26 stubs (`todo(…)`/`todos(…)`), 93.0%, at `01e165af` and + after Snap to Glyph shipped in #3124; 348 and 27 after the Revolve merge; 350 and 25, 93.3%, after Graph › Design + and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate. - Engine commands: ~710 ids registered with `cmd!` across `crates/engine/src/cmd` (plus macro-generated families), and 85 UI-only commands (`UI_COMMANDS`). - Tools: 91 in `crates/tools/src/catalog.rs`; Touch Type is listed but not implemented, and the Dimension @@ -271,7 +277,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** | | @@ -595,6 +601,7 @@ since 2026-10-01. - 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 › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 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. @@ -628,6 +635,7 @@ 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. @@ -769,6 +777,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images and the Profile Mismatches and Missing Profiles prompts are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. +- **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). @@ -844,10 +853,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). @@ -876,7 +887,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`. @@ -938,6 +949,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. @@ -989,7 +1001,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`. @@ -1000,6 +1012,8 @@ 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`). + - A script's error about answers in `answers` that it did not use, and Liquify's warning about the objects under the brush that it left as they were, show in the status bar in the interface language for one answer or object as well as for several, with the count's own form in each catalog that translates all status and error messages; the English the commands return stays as it was (`messages_with_one_or_several_items_translate_in_every_complete_catalog`, `unused_answers_are_counted_in_the_singular_and_the_plural`, `liquify_warns_about_one_or_several_skipped_objects`). + - In that Liquify warning, the tool's name and each kind of object it left (graphs, type, symbols, images, meshes, envelopes, repeats, placed documents, blends) are shown in the interface language too, in the order the command lists them and joined as the language joins a list, in each catalog that translates all status and error messages (`liquify-tool`, `liquify-kind` and `liquify-list-*` rows); a kind that Liquify does not list leaves the tool and the list in English (`liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog`). - 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. @@ -1100,7 +1114,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. Tests `shortcut_editor::tests::export_text_*` and `tests::picks::keyboard_shortcuts_export_text_writes_the_working_set_as_text`. + - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. It also offers a CSV file of the same rows (`format: "csv"`; Group, Command and Shortcut columns). Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. - On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side decorations, such as GNOME) and the window is not opened through XWayland, the app bar's window buttons follow the `button-layout` key of `org.gnome.desktop.wm.preferences` ([schema](https://gitlab.gnome.org/GNOME/gsettings-desktop-schemas/-/blob/master/schemas/org.gnome.desktop.wm.preferences.gschema.xml.in)): Close alone at the right, all three at the left, or split between the ends, in the listed order with the first one leftmost. When the key cannot be read or names no window button, and for an app frame turned on by `VECTORCRAFT_TITLEBAR=app` or VectorCraft Title Bar on Every Desktop, all three stay at the right. Tests `titlebar::tests::caption_buttons_follow_the_caption_layout`, `tests::the_caption_buttons_follow_the_frame_layout` and `tests::the_start_frame_applies_the_app_title_bar_preference`. - On Linux and the BSDs, Preferences › User Interface › VectorCraft Title Bar on Every Desktop (off by default) uses the app bar as the title bar from the next start in the sessions where the desktop would draw the window's frame (X11, Wayland compositors with server-side decorations such as KDE Plasma, a window opened through XWayland). System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it, and `VECTORCRAFT_TITLEBAR` also takes precedence over System Title Bar for the run it is set in. Only the values `app`, `system` and `desktop` take precedence (case-sensitive, surrounding spaces ignored); any other value, such as `unknown`, is ignored and does not override System Title Bar. @@ -1170,14 +1184,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. + VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. 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`). @@ -1427,6 +1442,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes. The grid lists the selected character's alternate glyphs from `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. A double-click applies the feature that draws the variant, or a glyph choice if no supported feature draws it, as detailed below. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Native files keep a glyph choice with the face it was made in; another font or version draws the default glyph. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. + With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. @@ -1449,7 +1465,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`). @@ -1504,7 +1520,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. @@ -1549,6 +1565,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. @@ -1579,7 +1596,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 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 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_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges, live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges, live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before, 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}`, `canvas::tests::bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before`, `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. @@ -1608,6 +1625,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`. @@ -1699,6 +1718,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). @@ -1791,7 +1811,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 `