diff --git a/Cargo.lock b/Cargo.lock index ae8a3ee6c7..32cffe9fda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6100,6 +6100,7 @@ dependencies = [ "serde_json", "smithay-clipboard", "socket2", + "tempfile", "vectorcraft-engine", "vectorcraft-render", "vectorcraft-text", @@ -6163,6 +6164,7 @@ dependencies = [ "objc2-core-foundation", "objc2-core-text", "serde_json", + "tempfile", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-engine", @@ -6469,6 +6471,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-geom", + "vectorcraft-pathops", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 8f39e3b58d..f7faf7a924 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -45,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features = objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] } [dev-dependencies] +tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b7334586ca..2d8df45926 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -2,9 +2,9 @@ //! //! ```text //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] //! vectorcraft-cli commands -//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] +//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] //! vectorcraft-cli perf [--paths 50000] [--deep] @@ -81,11 +81,12 @@ USAGE: allowed, and a kind left out grants none of its access. They imply --headless: a running app enforces its own (vectorcraft --control PORT --automation-read-root DIR …). - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE - is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports - (pixels per point, default 1); other formats leave it out. Prints one JSON result per step. + is a template, written as file.saveAsTemplate writes it). Raster exports use the document's + raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins + over --scale) is given; other formats leave them out. Prints one JSON result per step. --commands reads steps from FILE, or from standard input for -, where it stands among the --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. @@ -94,10 +95,10 @@ USAGE: vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] Open IN (any readable format) and export OUT in the format its extension picks (see Writable - formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it - out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard + formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects + resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -279,13 +280,15 @@ fn commands() -> Result<(), String> { } fn convert(args: &[String]) -> Result<(), String> { - let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"]; + let valued = + ["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"]; if help_requested(args, &valued) { return help(); } let mut files = vec![]; let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = - (1.0f64, None::, None::, false, false, false, false); + (None::, None::, None::, false, false, false, false); + let mut ppi = None::; let mut decimals = None::; // Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`, // `transparentImages`); the engine checks their values. @@ -293,7 +296,15 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?, + "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => { + ppi = Some( + it.next() + .and_then(|v| v.parse().ok()) + .filter(|n: &f64| n.is_finite() && *n > 0.0) + .ok_or("--ppi needs a positive finite number")?, + ); + } "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -326,7 +337,7 @@ fn convert(args: &[String]) -> Result<(), String> { // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG, // PSD). let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale); + let mut params = with_pixel_scale(params, &output, scale, ppi); if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } @@ -372,12 +383,17 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster. +/// The export `params` for `path`, with explicit raster resolution options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - params["scale"] = json!(scale); + if let Some(scale) = scale { + params["scale"] = json!(scale); + } + if let Some(ppi) = ppi { + params["ppi"] = json!(ppi); + } } params } @@ -485,7 +501,7 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"]; + let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; if help_requested(args, &valued) { return help(); } @@ -494,7 +510,8 @@ fn run(args: &[String]) -> Result<(), String> { // The step of the `--cmd` just given, which a `--params` sets. let mut params_for: Option = None; let mut stdin_read = false; - let mut scale = 1.0; + let mut scale = None::; + let mut ppi = None::; let mut it = args.iter(); while let Some(a) = it.next() { let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}")); @@ -531,7 +548,16 @@ fn run(args: &[String]) -> Result<(), String> { } "--scale" | "-s" => { let raw = val("a number")?; - scale = raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?; + scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + } + "--ppi" => { + let raw = val("a number")?; + ppi = Some( + raw.parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, + ); } other => return Err(format!("unknown run option `{other}`")), } @@ -576,7 +602,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index 33815fbf36..3ff82512d8 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -187,6 +187,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String { format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" }) } +/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee +/// selection and snapping cost when nothing narrows the search. +fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> { + use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; + let err = |e: vectorcraft_engine::EngineError| e.to_string(); + let mut s = vectorcraft_engine::Session::new(); + s.add_document(synthetic(n)?, None); + let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() }; + s.select_tool("selection", view).map_err(err)?; + // Off the art (nothing under the pointer), the case every hover over empty canvas pays. + let off = Point::new(-200.0, -200.0); + let hover = |s: &mut vectorcraft_engine::Session| { + let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view); + let _ = s.cursor(off, Mods::default(), view); + }; + rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s)))); + s.execute("select.all", &json!({})).map_err(err)?; + rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s)))); + let doc = s.doc().map_err(err)?.doc.clone(); + rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default()))))); + let r = Rect::new(600.0, 450.0, 1000.0, 750.0); + rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false))))); + let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0); + rows.push(( + format!("smart guide targets in view ({n} paths)"), + median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))), + )); + // Adding one more object to a selection of half the document: the command a shift-click ends + // in, without the pointer handling and hit test before it. + let ids: Vec = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default(); + s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?; + let mut k = ids.len() / 2; + rows.push(( + format!("select.toggle in a {}-object selection", ids.len() / 2), + median_ms(5, || { + k += 1; + let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]})); + }), + )); + Ok(()) +} + /// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole /// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with /// the peak so far where `rss_mb` reads one. @@ -282,6 +324,8 @@ fn deep(n: usize) -> Result<(), String> { }), )); note("after typing"); + pointing(n, &mut rows)?; + note("after pointing"); // Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render // worker and a panel each draw them. { diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 1423b78b42..c60357b5f8 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() { assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4"); } +#[test] +fn raster_exports_use_document_resolution_unless_overridden() { + let source = tmp("resolution.vectorcraft"); + ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]); + for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] { + for mode in ["run", "convert"] { + for format in ["png", "psd"] { + let path = tmp(&format!("resolution-{mode}-{width}.{format}")); + let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] }; + args.extend_from_slice(&flags); + ok(&args); + let bytes = std::fs::read(&path).unwrap(); + let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] }; + let expected = + if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] }; + assert_eq!(dimensions, expected.concat(), "{args:?}"); + } + } + } +} + +#[test] +fn raster_export_rejects_invalid_ppi() { + for ppi in ["0", "-150", "NaN", "inf", "high"] { + for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] { + let out = Command::new(BIN).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}"); + } + } +} + #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index f462132317..170a7e5c73 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -119,6 +119,7 @@ zbus = "=5.19.0" winresource = "0.1" [dev-dependencies] +tempfile = "3" # Bound socket buffers in real loopback transport deadline regressions. socket2 = { workspace = true } # src/portal_save.rs's tests build and read the portal's D-Bus values on every system. diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 1c0b4cd3c8..b9be306898 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -978,10 +978,17 @@ mod tests { use super::*; - fn dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id())); - std::fs::create_dir_all(&d).unwrap(); - d + fn dir(name: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap() + } + + #[test] + fn test_directory_is_removed_when_its_handle_is_dropped() { + let dir = dir("cleanup"); + let path = dir.path().to_path_buf(); + assert!(path.exists()); + drop(dir); + assert!(!path.exists()); } fn png(w: u32, h: u32) -> Vec { @@ -993,12 +1000,12 @@ mod tests { #[test] fn the_first_copied_file_that_is_art_pastes() { let d = dir("art"); - let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg")); + let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg")); std::fs::write(¬es, "not art").unwrap(); std::fs::write(&red, png(3, 2)).unwrap(); std::fs::write(&art, "").unwrap(); // Missing files, folders and text are skipped. - let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap(); + let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap(); assert_eq!((f.mime, f.data), (PNG, png(3, 2))); assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG)); // Only what Paste asks for. @@ -1032,7 +1039,8 @@ mod tests { /// An .eps file copied in a file manager pastes as EPS. #[test] fn a_copied_eps_file_pastes() { - let eps = dir("eps").join("equation.eps"); + let d = dir("eps"); + let eps = d.path().join("equation.eps"); std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap(); assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS)); assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none()); @@ -1040,7 +1048,8 @@ mod tests { #[test] fn a_crlf_left_by_the_uri_list_is_ignored() { - let red = dir("crlf").join("red.png"); + let d = dir("crlf"); + let red = d.path().join("red.png"); std::fs::write(&red, png(2, 2)).unwrap(); let with_cr = PathBuf::from(format!("{}\r", red.display())); assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG)); diff --git a/apps/vectorcraft/src/compositor_gpu.rs b/apps/vectorcraft/src/compositor_gpu.rs index 90e675b7f0..a5d6ae85e8 100644 --- a/apps/vectorcraft/src/compositor_gpu.rs +++ b/apps/vectorcraft/src/compositor_gpu.rs @@ -150,18 +150,16 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> { - let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?; // /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU. - std::fs::create_dir_all(dir.join("226:128/device"))?; - std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?; - std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?; + std::fs::create_dir_all(dir.path().join("226:128/device"))?; + std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?; + std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?; // A device that isn't a PCI GPU (a virtual one) has no ids. - std::fs::create_dir_all(dir.join("226:0/device"))?; - let render = super::pci_ids(&dir, makedev(226, 128)); - let virtual_gpu = super::pci_ids(&dir, makedev(226, 0)); - let missing = super::pci_ids(&dir, makedev(226, 1)); - std::fs::remove_dir_all(&dir)?; + std::fs::create_dir_all(dir.path().join("226:0/device"))?; + let render = super::pci_ids(dir.path(), makedev(226, 128)); + let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0)); + let missing = super::pci_ids(dir.path(), makedev(226, 1)); assert_eq!(render, Some((0x10de, 0x25ac))); assert_eq!(virtual_gpu, None); assert_eq!(missing, None); diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 40d84934f3..40e6a555c5 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() { /// PCI ids. Each GPU is listed once, the one with the panel as primary. #[test] fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> { - let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?; + let dir = temp.path(); let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> { std::fs::create_dir_all(dir.join(name).join("device"))?; std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?; @@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<() connector("card1-DP-2", "connected")?; connector("card2-Virtual-1", "connected")?; std::fs::write(dir.join("renderD128"), "")?; - let mut gpus = linux_display_gpus(&dir); + let mut gpus = linux_display_gpus(dir); gpus.sort_by_key(|g| g.pci); assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]); assert!(linux_display_gpus(&dir.join("no such dir")).is_empty()); - std::fs::remove_dir_all(&dir) + Ok(()) } #[test] @@ -616,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() { /// A log folder of its own for each test, and the guard that keeps other tests from starting a /// program while it runs: the test releases the start file's lock and takes it again, and a child /// starting meanwhile would keep it held (`crate::no_spawns`). -fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) { +struct TestDir(tempfile::TempDir); + +impl std::ops::Deref for TestDir { + type Target = std::path::Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } +} + +impl AsRef for TestDir { + fn as_ref(&self) -> &std::path::Path { + self.0.path() + } +} + +fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) { let spawns = crate::no_spawns(); - let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - (d, spawns) + let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap(); + (TestDir(dir), spawns) } /// What a start in `dir` leaves out; it then ends without crashing. @@ -670,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept"); assert_eq!(left_out.crash, None, "the note is shown once"); third.ended(); - let _ = std::fs::remove_dir_all(&dir); } /// A start whose first frame reached the screen, or that ended without crashing (a normal exit, @@ -693,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { assert!(finish(Ok(Ok(())), &first).is_ok()); drop(first); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } /// The process ended while the adapters were being listed (wgpu's DX12 backend creates a @@ -721,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() { second.none_left(); second.ended(); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } /// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that @@ -742,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() { explicit.picked(&c[0].key, &c[0].name, true); explicit.presented(); assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window"); - let _ = std::fs::remove_dir_all(&dir); } /// A damaged record, a file that can't be opened and one another starting copy of the app holds @@ -777,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() { assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]); // A folder in the file's place. - let _ = std::fs::remove_dir_all(&dir); + std::fs::remove_file(dir.join(START_FILE)).unwrap(); std::fs::create_dir_all(dir.join(START_FILE)).unwrap(); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2ca282d74c..978308b9e5 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -198,6 +198,30 @@ fn read_file_refuses_what_is_not_a_regular_file() { assert!(read_file("/dev/zero").is_err()); } +/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only +/// a regular file is read. +fn read_file_head(path: &str, max: usize) -> Result, String> { + use std::io::Read; + if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { + return Err(format!("{path}: not a file")); + } + let mut out = vec![]; + std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?; + Ok(out) +} + +#[cfg(test)] +#[test] +fn read_file_head_reads_no_more_than_it_is_asked_for() { + use std::io::Write as _; + let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap(); + f.write_all(b"0123456789").unwrap(); + let p = f.path().to_string_lossy(); + assert_eq!(read_file_head(&p, 4).unwrap(), b"0123"); + assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole"); + assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read"); +} + /// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) @@ -325,6 +349,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { #[cfg(windows)] stylus: Some(windows_stylus::start()), read: Some(Box::new(read_file)), + // Load Actions… refuses a file over its size limit without reading all of it. + read_head: Some(Box::new(read_file_head)), write: Some(Box::new(write_file)), exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. @@ -569,22 +595,20 @@ mod open_with_tests { use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates}; /// A fresh, empty folder under the system's temporary folder. - fn scratch(name: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d + fn scratch(name: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap() } /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing /// path. #[test] fn only_applications_are_started() { - let d = scratch("check"); + let temp = scratch("check"); + let d = temp.path(); let doc = d.join("notes.txt"); std::fs::write(&doc, "hi").unwrap(); assert!(check_app(&doc).is_err(), "a document"); - assert!(check_app(&d).is_err(), "a folder"); + assert!(check_app(d).is_err(), "a folder"); assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path"); if cfg!(target_os = "macos") { let app = d.join("Editor.app"); @@ -600,19 +624,19 @@ mod open_with_tests { std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); assert!(check_app(&tool).is_ok(), "an executable file"); } - let _ = std::fs::remove_dir_all(&d); } /// PhotoCraft is looked for only where it installs. #[test] fn photocraft_is_found_where_it_installs() { - let d = scratch("find"); + let temp = scratch("find"); + let d = temp.path(); if cfg!(target_os = "macos") { - let candidates = photocraft_candidates(Some(&d), None); + let candidates = photocraft_candidates(Some(d), None); assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app")); assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}"); std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap(); - assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app")); + assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app")); } else { let bin = d.join("bin"); std::fs::create_dir_all(&bin).unwrap(); @@ -636,7 +660,6 @@ mod open_with_tests { assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); } } - let _ = std::fs::remove_dir_all(&d); } /// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it diff --git a/apps/vectorcraft/src/logging/tests.rs b/apps/vectorcraft/src/logging/tests.rs index a1b54b353a..78b08a67b3 100644 --- a/apps/vectorcraft/src/logging/tests.rs +++ b/apps/vectorcraft/src/logging/tests.rs @@ -1,12 +1,29 @@ use super::*; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, UNIX_EPOCH}; -fn temp_dir(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - d +struct TestPath { + _parent: tempfile::TempDir, + path: PathBuf, +} + +impl std::ops::Deref for TestPath { + type Target = Path; + + fn deref(&self) -> &Self::Target { + &self.path + } +} + +impl AsRef for TestPath { + fn as_ref(&self) -> &Path { + &self.path + } +} + +fn temp_dir(tag: &str) -> TestPath { + let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap(); + let path = parent.path().join("log"); + TestPath { _parent: parent, path } } fn read(path: &Path) -> String { diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index a1b5b193c5..36223c559f 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -63,11 +63,10 @@ mod tests { /// fonts, is listed while it is registered. #[test] fn fonts_registered_from_other_folders_are_listed() { - let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); // A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS // installs. - let file = dir.join("Registered Font.ttf"); + let file = dir.path().join("Registered Font.ttf"); std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap(); let want = std::fs::canonicalize(&file).unwrap(); let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want)); @@ -78,7 +77,6 @@ mod tests { let registered = listed(); // SAFETY: as above. unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) }; - std::fs::remove_dir_all(&dir).unwrap(); assert!(registered); } } diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index a6daacb83a..f03572ebb2 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -335,13 +335,11 @@ mod tests { #[test] fn a_kept_preferences_copy_is_owner_only() { use std::os::unix::fs::PermissionsExt as _; - let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap(); + let dir = temp.path(); super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable"); let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 8ef0355831..0048323f03 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -192,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { #[cfg(test)] mod tests { use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + + struct TestDir(tempfile::TempDir); + + impl std::ops::Deref for TestDir { + type Target = Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } + } + + impl AsRef for TestDir { + fn as_ref(&self) -> &Path { + self.0.path() + } + } fn environment(key: &str) -> Option { match key { @@ -287,12 +302,8 @@ mod tests { assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into())); } - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d + fn temp(tag: &str) -> TestDir { + TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap()) } #[test] diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index f7026131c9..5ced4aef33 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -263,15 +263,23 @@ mod tests { use super::*; + struct TestDir(tempfile::TempDir); + + impl std::ops::Deref for TestDir { + type Target = Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } + } + /// A fresh folder for one test, with an existing file in it. - fn folder(name: &str) -> (PathBuf, PathBuf, String) { - let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let file = dir.join("a b.svg"); + fn folder(name: &str) -> (PathBuf, TestDir, String) { + let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap(); + let file = dir.path().join("a b.svg"); fs::write(&file, "").unwrap(); let file = file.to_string_lossy().into_owned(); - (dir.join(FILE_NAME), dir, file) + (dir.path().join(FILE_NAME), TestDir(dir), file) } fn primary(path: &Path) -> (Primary, mpsc::Receiver>) { @@ -303,12 +311,11 @@ mod tests { assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); drop(primary); assert!(!path.exists(), "the endpoint file goes with the app"); - let _ = fs::remove_dir_all(dir); } #[test] fn a_wrong_token_garbage_and_oversized_messages_are_refused() { - let (path, dir, file) = folder("refused"); + let (path, _dir, file) = folder("refused"); let (_primary, rx) = primary(&path); let token = read_endpoint(&path).unwrap().token; let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); @@ -323,12 +330,11 @@ mod tests { // The listener still serves a launch with the right token. forward(&path, std::slice::from_ref(&file)).unwrap(); assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); - let _ = fs::remove_dir_all(dir); } #[test] fn a_stale_endpoint_file_is_ignored_and_replaced() { - let (path, dir, file) = folder("stale"); + let (path, _dir, file) = folder("stale"); // The recorded app is gone: whatever holds the port closes without a greeting. (A freed // port can be taken by another test's listener meanwhile, which would then accept this // connection in place of its own client's.) @@ -357,18 +363,16 @@ mod tests { let (_primary, rx) = primary(&path); forward(&path, std::slice::from_ref(&file)).unwrap(); assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); - let _ = fs::remove_dir_all(dir); } #[test] fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() { - let (path, dir, _) = folder("replaced"); + let (path, _dir, _) = folder("replaced"); let (first, _rx1) = primary(&path); let (_second, _rx2) = primary(&path); let second_token = read_endpoint(&path).unwrap().token; drop(first); assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token)); - let _ = fs::remove_dir_all(dir); } #[test] @@ -383,9 +387,8 @@ mod tests { #[test] fn the_endpoint_file_is_the_users_alone() { use std::os::unix::fs::PermissionsExt as _; - let (path, dir, _) = folder("mode"); + let (path, _dir, _) = folder("mode"); let _primary = primary(&path); assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); - let _ = fs::remove_dir_all(dir); } } diff --git a/apps/vectorcraft/src/system_fonts.rs b/apps/vectorcraft/src/system_fonts.rs index 67bbf7843a..fe9df48ca4 100644 --- a/apps/vectorcraft/src/system_fonts.rs +++ b/apps/vectorcraft/src/system_fonts.rs @@ -284,8 +284,8 @@ mod tests { #[test] fn fonts_only_gdi_has_loaded_are_listed_by_their_files() { use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW}; - let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap(); + let dir = temp.path(); let file = dir.join("29457"); let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf"); let mut data = std::fs::read(source).unwrap(); @@ -303,7 +303,6 @@ mod tests { assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1); let files = super::font_files(); let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) }; - let _ = std::fs::remove_dir_all(&dir); let wanted = file.to_string_lossy().to_lowercase(); assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len()); } diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index e6096c54a7..116651fc8d 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -99,9 +99,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() { #[test] fn an_unreadable_ui_json_is_kept_beside_it() { - let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id())); - std::fs::create_dir(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap(); + let dir = temp.path(); let path = dir.join("ui.json"); super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable"); super::keep_prefs_copy(&path, b"not json", "ui.unreadable"); @@ -109,7 +108,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() { let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap(); let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap(); let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap(); - let _ = std::fs::remove_dir_all(&dir); assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced"); assert_eq!(second, b"not json"); assert_eq!(before, b"{}"); diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index b18bcddaee..5e996c4bdd 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -16,6 +16,14 @@ //! mouse message that Windows did not make from a pen or a touch //! () //! clears the feed. +//! +//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a +//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen +//! reports it (): +//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and +//! `rotation` in degrees 0..359 clockwise +//! (). +//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come. #![cfg_attr(not(windows), allow(dead_code))] use std::cell::RefCell; @@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; /// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure. const PEN_MASK_PRESSURE: u32 = 0x0001; +/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its +/// barrel rotation, its tilt along x and its tilt along y. +const PEN_MASK_ROTATION: u32 = 0x0002; +const PEN_MASK_TILT_X: u32 = 0x0004; +const PEN_MASK_TILT_Y: u32 = 0x0008; /// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows /// made from a pen or a touch. const MI_WP_SIGNATURE: u32 = 0xFF51_5700; @@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { // pointer that is not a pen. unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; - Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact)) + let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); + Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); @@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { /// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` /// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen -/// in contact that reports none; and the eraser end while it is inverted or its eraser button is -/// pressed. -fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample { +/// in contact that reports none; the eraser end while it is inverted or its eraser button is +/// pressed; and how it is held, `pose` ([`pen_pose`]). +fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample { let pressure = match pressure { 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, _ if in_contact => 1.0, _ => 0.0, }; - PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() } + PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose } +} + +/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is +/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the +/// rotation when it reports one, each kept within [`PenPose`]'s ranges. +fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { + let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; + let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); + let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); + PenPose { tilt, rotation }.sanitized() } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -390,7 +414,7 @@ mod tests { #[test] fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() { - let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser; + let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser; assert!(!eraser(0), "the tip"); assert!(!eraser(PEN_FLAG_BARREL), "the barrel button"); assert!(eraser(PEN_FLAG_INVERTED), "turned over"); @@ -399,19 +423,32 @@ mod tests { assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL)); } + #[test] + fn a_pens_tilt_and_rotation_come_where_it_reports_them() { + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) }); + assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel"); + let wild = pen_pose(all, 400, i32::MIN, 720); + assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges"); + let pose = pen_pose(all, 10, 20, 180); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { - assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5); - assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); + assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0); assert_eq!( - pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), + pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()), PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() }, "hovering" ); - assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); - assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one"); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0"); - assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0); + assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); + assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one"); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0); } #[test] diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 3915b239ed..e487226d4f 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -195,6 +195,24 @@ impl ImageBlob { jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16))) } + /// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8 + /// bits? Reads only its header. + pub fn is_cmyk16(&self) -> bool { + tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16))) + } + + /// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header. + pub fn header_size(&self) -> Option<(u32, u32)> { + let bytes = self.bytes.as_slice(); + if bytes.starts_with(&[0xFF, 0xD8]) { + let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); + d.decode_headers().ok()?; + let (w, h) = d.dimensions()?; + return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?)); + } + tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok()) + } + /// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded /// or are larger than [`MAX_CMYK_PIXELS`]. pub fn cmyk(&self) -> Option { @@ -633,6 +651,38 @@ mod tests { assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]); } + #[test] + fn a_header_gives_the_size_without_the_samples() { + assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2))); + // A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there. + let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec(); + // Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98). + let entries = [ + (256u16, 4u16, 1u32, 6000u32), + (257, 4, 1, 6000), + (258, 3, 4, 98), + (262, 3, 1, 5), + (273, 4, 1, 106), + (277, 3, 1, 4), + (279, 4, 1, 144_000_000), + ]; + for (tag, kind, count, value) in entries { + t.extend_from_slice(&tag.to_le_bytes()); + t.extend_from_slice(&kind.to_le_bytes()); + t.extend_from_slice(&count.to_le_bytes()); + t.extend_from_slice(&value.to_le_bytes()); + } + t.extend_from_slice(&0u32.to_le_bytes()); + t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]); + let big = ImageBlob::new("image/tiff", t); + assert!(big.is_cmyk()); + assert_eq!(big.header_size(), Some((6000, 6000))); + assert_eq!(big.cmyk(), None); + let mut png = Vec::new(); + image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF"); + } + #[test] fn a_cmyk_image_samples_its_ink_amounts() { let b = ImageBlob::cmyk_tiff(&inks()).unwrap(); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 976d48485f..102caf53db 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -72,6 +72,7 @@ impl Document { new_art, dimensions, retired_artboard_id: _, + opened_artboard: _, index: _, } = self; *version == other.version @@ -248,6 +249,7 @@ impl Document { new_art: Default::default(), dimensions: false, retired_artboard_id: Default::default(), + opened_artboard: None, index: Default::default(), }; let id = d.alloc_id(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 9bb8466bbb..988df4c511 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -325,6 +325,11 @@ pub struct Document { /// Never saved. #[serde(skip)] pub retired_artboard_id: RetiredArtboardId, + /// The id of the artboard an imported file names as its active one (a `.ai` file's + /// `CropAreaActive`): the document opens with that artboard active. `None`: the first. Never + /// saved. + #[serde(skip)] + pub opened_artboard: Option, /// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this /// is set, so documents without any pay nothing for them. #[serde(default, skip_serializing_if = "std::ops::Not::not")] diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index 2330e95ac9..781e61e685 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -46,10 +46,26 @@ impl LinkInfo { Self { path: path.into(), ..Self::default() } } - /// The file name: the path's last component, whichever system's separators it uses. + /// The file name: the path's last component, whichever system's separators it uses + /// ([`path_separators`]). pub fn name(&self) -> &str { - self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path) + self.path.rsplit(path_separators(&self.path)).next().unwrap_or(&self.path) } + + /// The folder the file is in: the path without its name and the separators before it. + pub fn folder(&self) -> &str { + let folder = self.path.get(..self.path.len().saturating_sub(self.name().len())).unwrap_or_default(); + folder.trim_end_matches(path_separators(&self.path)) + } +} + +/// The characters that separate the folders of `path`. A path with a colon and no `/` or `\` is a +/// classic Mac OS path (`Disk:Folder:file.tif`, as older documents store links), whose folders are +/// separated by colons. Any other path is separated by `/` and `\`: its file name may hold a colon +/// (`/Users/a/x:y.png`) and never holds a `/` or `\`. +pub fn path_separators(path: &str) -> &'static [char] { + const SLASHES: &[char] = &['/', '\\']; + if path.contains(':') && !path.contains(SLASHES) { &[':'] } else { SLASHES } } impl From<&str> for LinkInfo { @@ -164,6 +180,31 @@ impl ImageBlob { pub fn is_proxy(&self) -> bool { self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes)) } + + /// Does a colorize paint ([`crate::NodeExtras::colorize`]) show on these bytes? Not while + /// they are a preview whose pixels aren't grayscale, such as [`missing_placeholder`]: until + /// the file is relinked the image shows the preview as it is, and keeps the paint. + pub fn takes_colorize(&self) -> bool { + !self.is_proxy() || self.gray_source().is_some() + } +} + +/// The side of [`missing_placeholder`]'s image, in pixels. +pub const MISSING_SIDE: u32 = 64; + +/// What a linked image shows when an importer has no pixels for it (its file is missing or isn't +/// in the data): a light tile, crossed out, [`MISSING_SIDE`] pixels a side, as a PNG. `None` when +/// it can't be encoded. +pub fn missing_placeholder() -> Option> { + let last = MISSING_SIDE - 1; + let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| { + let edge = x == 0 || y == 0 || x == last || y == last; + let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1; + image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] }) + }); + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(png) } /// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or @@ -445,6 +486,12 @@ mod tests { .unwrap() } + #[test] + fn the_placeholder_is_a_png() { + let png = missing_placeholder().unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE); + } + #[test] fn a_path_string_from_older_files_reads_as_a_link() { let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap(); @@ -460,6 +507,35 @@ mod tests { assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2})); } + /// A classic Mac OS path is named by its last colon-separated component, and its folder is + /// what comes before; other paths keep their `/` and `\` separators, and a name never holds + /// one. + #[test] + fn a_classic_mac_path_is_named_by_its_last_component() { + let parts = |path: &str| { + let l = LinkInfo::new(path); + (l.name().to_string(), l.folder().to_string()) + }; + assert_eq!(parts("Macintosh HD:Images:photo.tif"), ("photo.tif".into(), "Macintosh HD:Images".into())); + assert_eq!(parts("Disk:photo.tif"), ("photo.tif".into(), "Disk".into())); + assert_eq!(parts("Disk:Art/2024:a\\b.tif"), ("b.tif".into(), "Disk:Art/2024:a".into())); + assert_eq!(parts("Disk:Images:../other.png"), ("other.png".into(), "Disk:Images:..".into()), "a name reaches no other folder"); + assert_eq!(parts("C:\\art\\photo.png"), ("photo.png".into(), "C:\\art".into())); + assert_eq!(parts("c:/art/photo.png"), ("photo.png".into(), "c:/art".into())); + assert_eq!(parts("/Users/a/x:y.png"), ("x:y.png".into(), "/Users/a".into()), "a POSIX name may hold a colon"); + assert_eq!(parts("./art/x:y.png"), ("x:y.png".into(), "./art".into())); + assert_eq!(parts("..\\art\\x:y.png"), ("x:y.png".into(), "..\\art".into())); + assert_eq!(parts("\\\\?\\C:\\art\\photo.png"), ("photo.png".into(), "\\\\?\\C:\\art".into())); + assert_eq!(parts("file:///art/photo.png"), ("photo.png".into(), "file:///art".into())); + assert_eq!(parts("file:/art/photo.png"), ("photo.png".into(), "file:/art".into())); + assert_eq!(parts("assets/icon:dark.png"), ("icon:dark.png".into(), "assets".into()), "a relative path with slashes"); + assert_eq!(parts(":Images:photo.tif"), ("photo.tif".into(), ":Images".into()), "a classic path relative to its folder"); + assert_eq!(parts("/Users/a//photo.png").1, "/Users/a", "repeated separators"); + assert_eq!(parts("photo.png"), ("photo.png".into(), String::new())); + assert_eq!(parts("C:photo.png"), ("photo.png".into(), "C".into()), "a drive-relative path has the same shape"); + assert_eq!(LinkInfo::new("Macintosh HD:Images:photo.tif").path, "Macintosh HD:Images:photo.tif", "the stored path is kept"); + } + #[test] fn a_reader_hashes_as_its_bytes_do() { // Several 64 KB reads, and none. diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 44efdb3278..a79b8e0f78 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -501,3 +501,45 @@ fn a_stroke_narrower_than_the_shape_keeps_its_hole() { assert_eq!(moves(&outline), 3, "{join:?}: two contours for the ring, one for the blob"); } } + +/// A subpixel stroke must retain its geometric thickness even when the normal display tolerance +/// is close to its weight. Original uneven circular arcs, independent of any user fixture. +#[test] +fn thin_curved_strokes_keep_their_width_between_notches() { + use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Shape}; + for (radius, degrees) in [(450.0, 47.0_f64), (438.0, 77.0), (450.0, 54.0)] { + let a = degrees.to_radians(); + let k = 4.0 / 3.0 * (a / 4.0).tan(); + let curve = CubicBez::new( + (radius, 0.0), + (radius, k * radius), + (radius * a.cos() + k * radius * a.sin(), radius * a.sin() - k * radius * a.cos()), + (radius * a.cos(), radius * a.sin()), + ); + let mut line = BezPath::new(); + line.move_to(curve.p0); + line.curve_to(curve.p1, curve.p2, curve.p3); + for width in [0.25, 1.0 / 3.0, 0.5, 1.0] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + let outline = line_outline(&line, &st, width, 0.25); + for step in 1..40 { + let t = step as f64 / 40.0; + let p = curve.eval(t); + let tangent = curve.deriv().eval(t).to_vec2().normalize(); + let normal = kurbo::Vec2::new(-tangent.y, tangent.x); + for side in [-1.0, 1.0] { + assert_ne!( + outline.winding(p + normal * (side * width * 0.45)), + 0, + "missing inner band at radius {radius}, {degrees} degrees, width {width}, t {t}" + ); + assert_eq!( + outline.winding(p + normal * (side * width * 0.55)), + 0, + "outside intended band at radius {radius}, {degrees} degrees, width {width}, t {t}" + ); + } + } + } + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b1b9efd60b..f02d6f6aa6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -168,6 +168,17 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) } } +/// A path is selected, or inside a selected group or compound path: Object › Path's items that +/// work on paths (not on text, images or other objects alone). +pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + // Stops at the first path: menus ask this every frame, and a selected group can hold many. + fn holds_path(n: &vectorcraft_doc::Node) -> bool { + matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c))) + } + if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) } +} /// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take). pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) } diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 15ba1dad45..324d7bde58 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -9,6 +9,7 @@ mod document; mod pathtools; mod pen; mod select; +mod shapes; mod typetools; use super::CommandSpec; @@ -23,6 +24,7 @@ pub fn specs() -> Vec { v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); + v.extend(shapes::specs()); v.extend(typetools::specs()); v } diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 0d279c0f64..4b76562e91 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -13,7 +13,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; use crate::cmd::fonts::{edit_symbol_texts, symbol_texts}; -use crate::cmd::textedit::editing_range; +use crate::cmd::textedit::{editing_range, editing_story}; use crate::cmd::typecmd::refresh_bounds; use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{EngineError, Result, Session}; @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Remove Breaks", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}", + "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", has_selection, remove_breaks ), @@ -730,12 +730,11 @@ fn join_text(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "joined": joined, "lines": count })) } -/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many -/// went. -fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { - let text = t.plain_text(); - let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); - let Some(range) = text.get(a..b) else { return 0 }; +/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between +/// two words). +fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> { + let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b)); + let Some(range) = text.get(a..b) else { return vec![] }; let mut prev = text.get(..a).and_then(|s| s.chars().next_back()); let mut cuts = vec![]; for (i, c) in range.char_indices() { @@ -753,6 +752,12 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { } cuts.push((at, space)); } + cuts +} + +/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a +/// space → how many went. +fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { for &(at, space) in cuts.iter().rev() { let insert = if space { " " } else { "" }; let end = at + brk.len_utf8(); @@ -763,6 +768,30 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { cuts.len() } +/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or +/// start of a frame between words of the frames on either side becomes a space. Each editable frame +/// comes with its own breaks, at its own bytes. +fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { + let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); + let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); + // The breaks in story order, handed to the frames in one pass. + let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable(); + let mut out = vec![]; + let mut start = 0; + for (id, text) in texts { + let end = start + text.len(); + let mut own = vec![]; + while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { + own.push((at - start, space)); + } + if d.is_editable(id) { + out.push((id, own)); + } + start = end; + } + out +} + fn remove_breaks(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.removeBreaks"; let (brk, label, none) = match text_param(p, "kind", C)? { @@ -771,21 +800,41 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))), None => return Err(bad(C, "missing `kind`")), }; - // The characters a Type tool has selected, else all the text of the selected type. + // The characters a Type tool has selected (after Select All in threaded text, all the text of + // every frame of the story), else all the text of the selected type. let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) }; + let story = if editing.is_some() { editing_story(s) } else { vec![] }; let d = &s.doc()?.doc; - let targets: Vec<(NodeId, usize, usize)> = match editing { - Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(), - None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(), + // Each type object with the breaks that go from it. + let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing { + Some(_) if !story.is_empty() => story_cuts(d, &story, brk), + Some((id, a, b)) => vec![(id, a.min(b), a.max(b))] + .into_iter() + .filter(|(id, ..)| d.is_editable(*id)) + .filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk)))) + .collect(), + None => { + let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + // A threaded story whose frames are all among them is read as one text, once. + let named: std::collections::HashSet = ids.iter().copied().collect(); + let mut done = std::collections::HashSet::new(); + let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![]; + for &id in &ids { + if !done.insert(id) { + continue; + } + let story = crate::cmd::threads::story_of(d, id); + if !story.is_empty() && story.iter().all(|f| named.contains(f)) { + done.extend(story.iter().copied()); + out.extend(story_cuts(d, &story, brk)); + } else if let Some(t) = text_of(d, id) { + out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk))); + } + } + out + } }; - let count: usize = targets - .iter() - .filter_map(|(id, a, b)| { - let text = text_of(d, *id)?.plain_text(); - let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b)); - Some(text.get(a..b)?.matches(brk).count()) - }) - .sum(); + let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum(); if count == 0 { return Err(EngineError::Other(none.into())); } @@ -794,9 +843,9 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { } let (removed, ids) = s.edit(label, |d, _| { let (mut removed, mut ids) = (0, vec![]); - for (id, a, b) in targets { + for (id, cuts) in targets { let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; - let n = strip_breaks(t, a, b, brk); + let n = apply_cuts(t, &cuts, brk); if n > 0 { refresh_bounds(t); removed += n; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index ac8947cb4a..574003b931 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -3,9 +3,10 @@ //! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the //! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, //! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest -//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend -//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object › -//! Plug-ins › Color Effects, are the UI's. +//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend +//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply +//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, +//! Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; @@ -14,13 +15,14 @@ mod print_fixes; mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind}; use vectorcraft_render::effects; use super::super::colorcmds::recolor_links; +use super::super::paint::{restore_unpainted_stroke, set_run_stroke}; use super::super::select::walk_selectable; -use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param}; -use crate::{Result, Session}; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param}; +use crate::{EngineError, Result, Session}; /// The kinds Select by Color Kind selects (`addon.color.select`). pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"]; @@ -72,6 +74,24 @@ pub fn specs() -> Vec { has_selection, nearest::apply ), + cmd!( + "addon.color.fillToStroke", + "Apply Fill to Stroke", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + has_doc, + |s, p| copy_paint(s, p, true) + ), + cmd!( + "addon.color.strokeToFill", + "Apply Stroke to Fill", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}", + has_doc, + |s, p| copy_paint(s, p, false) + ), ] .into_iter() .chain(legend::specs()) @@ -156,3 +176,97 @@ fn filter(s: &mut Session, p: &Value) -> Result { let swatches = |name: &str| kinds.get(name).copied(); recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) } + +/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own +/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and +/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that +/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in +/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing +/// changes, the document and its undo history stay as they are. +fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { + let (cmd, label) = + if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") }; + let skip_none = switch_or(p, "skipNone", false, cmd)?; + // One text style: its stroke takes its fill, or the other way. + let copy_run = |st: &mut CharStyle| { + let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() }; + if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } { + return; + } + if to_stroke { + set_run_stroke(st, from); + } else { + st.fill = from; + } + }; + if p.get("ids").is_none() + && p.get("id").is_none() + && let Some((id, a, b)) = super::super::textedit::editing_range(s)? + && a != b + { + // After Select All in threaded text, every frame's text takes it. + let story = super::super::textedit::editing_story(s); + let ranges: Vec<(NodeId, usize, usize)> = + if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() }; + let ids: Vec = ranges.iter().map(|(f, _, _)| *f).collect(); + let before = s.doc()?.doc.clone(); + let n = super::super::overprint::edit_counted(s, label, |d| { + for &(id, a, b) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run); + super::super::typecmd::refresh_bounds(t); + } + Ok(super::super::appearance::count_changed(d, &before, &ids)) + })?; + return Ok(json!({"objects": n})); + } + // A graph's series group stands for its marks, as for `paint.setFill`. + let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?); + let mut objects = 0; + if !ids.is_empty() { + let before = s.doc()?.doc.clone(); + super::super::overprint::edit_counted(s, label, |d| { + for id in &ids { + let Some(node) = d.node_mut(*id) else { continue }; + if let NodeKind::Text(t) = &mut node.kind { + for r in &mut t.runs { + copy_run(&mut r.style); + } + super::super::typecmd::refresh_bounds(t); + continue; + } + let ap = &mut node.appearance; + let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) }; + // A missing item reads as None: copying None onto it would add an item that + // changes nothing. + if (skip_none && from.is_none()) || from == to { + continue; + } + if to_stroke { + restore_unpainted_stroke(ap, None, &from); + ap.set_stroke(from); + } else { + ap.set_fill(from); + } + } + objects = super::super::appearance::count_changed(d, &before, &ids); + // The graph keeps the paint its series marks and labels now have. + let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke); + let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); + Ok(objects + usize::from(series || labels)) + })?; + } + // The defaults for new art change the same way, as Swap Fill and Stroke changes them. + let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() }; + if !(skip_none && from.is_none()) { + if to_stroke { + if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 { + s.paint.stroke_width = 1.0; + } + s.paint.stroke = from; + } else { + s.paint.fill = from; + } + } + Ok(json!({"objects": objects})) +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 52f7f3168e..fafdfc07dc 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Batch Trace Folder", ["Object", "Plug-ins", "Document Tools"], None, - "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", always, batch_trace::batch_trace_folder ), diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs index 0340fca183..61e59fc54f 100644 --- a/crates/engine/src/cmd/addons/document/batch_trace.rs +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -8,9 +8,9 @@ use serde_json::json; #[cfg(not(target_arch = "wasm32"))] use super::super::super::fileio; -use super::super::super::{Result, Session, bad}; #[cfg(not(target_arch = "wasm32"))] -use super::super::super::{bool_or, str_param}; +use super::super::super::str_param; +use super::super::super::{Result, Session, bad}; /// The command id. pub(super) const ID: &str = "addon.document.batchTraceFolder"; @@ -69,20 +69,39 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Resu pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result { let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?; let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?; - let format = str_param(p, "format").unwrap_or("vectorcraft"); + let format = match p.get("format") { + None => "vectorcraft", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`format` must be a string")), + }; + let preset = match p.get("preset") { + None => "Default", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`preset` must be a string")), + }; + let expand = match p.get("expand") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`expand` must be true or false")), + }; + let include_subdirs = match p.get("includeSubdirs") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")), + }; if !FORMATS.contains(&format) { return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", ")))); } - let preset = str_param(p, "preset").unwrap_or("Default").to_string(); + let preset = preset.to_string(); let presets = s.execute("imageTrace.presets", &json!({}))?; if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); } - let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; fileio::may_read(&folder)?; fileio::may_write(&dest)?; let mut files = vec![]; - images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; + images(&folder, include_subdirs, 0, &mut files)?; files.sort(); if files.is_empty() { return Err(bad(ID, "no images in the folder")); diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index a1bc5afff6..b0fbb41422 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -333,6 +333,35 @@ fn batch_trace_folder_traces_and_saves_each_image() { let _ = std::fs::remove_dir_all(&dir); } +/// Batch Trace Folder rejects optional values with the wrong type before opening images. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_rejects_wrong_typed_options() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace-bad-options"); + let src = dir.join("in"); + let out = dir.join("out"); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + for (key, value) in [ + ("format", json!(42)), + ("format", Value::Null), + ("preset", json!(false)), + ("preset", Value::Null), + ("expand", json!("true")), + ("expand", Value::Null), + ("includeSubdirs", json!(1)), + ("includeSubdirs", Value::Null), + ] { + let mut params = json!({"folder": src, "destinationFolder": out}); + params[key] = value; + let error = s.execute(C, ¶ms).unwrap_err(); + assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}"); + assert!(!out.exists(), "invalid options must not create a destination folder"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A folder too big to list in full is refused rather than traced in part. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index ce2869abca..b2ab59d851 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,33 +1,56 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects -//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu -//! (Object › Plug-ins › Selection Tools) and dialog are the UI's. +//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by +//! Link Status selects the images and placed documents whose file is linked, embedded, missing or +//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins +//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. #[cfg(test)] mod tests; +use std::collections::BTreeSet; + use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; -use super::super::select::{on_artboard, selectable}; -use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param}; -use crate::{Result, Session}; +use super::super::links::{Status, statuses}; +use super::super::select::{is_selectable, on_artboard, selectable}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; +/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept +/// in the document, a file not found, a file changed since it was read. +pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; + +/// The add-on's commands: Select by Artboards and Select by Link Status. pub fn specs() -> Vec { - vec![cmd!( - "addon.select.byArtboards", - "Select by Artboards", - ["Object", "Plug-ins", "Selection Tools"], - None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", - has_doc, - by_artboards - )] + vec![ + cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + ), + cmd!( + "addon.select.byLinkStatus", + "Select by Link Status", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}", + has_doc, + by_link_status + ), + ] } +/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie +/// outside the chosen artboards. fn by_artboards(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byArtboards"; let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); @@ -61,3 +84,112 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +/// The link statuses `p` asks for (`status`: one, or a list of them), each once. +fn link_statuses(p: &Value, cmd: &str) -> Result> { + let given: Vec<&Value> = match p.get("status") { + None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")), + Some(Value::Array(v)) => v.iter().collect(), + Some(v) => vec![v], + }; + let mut out = vec![]; + for v in given { + let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?; + let known = + LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?; + if !out.contains(known) { + out.push(*known); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose at least one status")); + } + Ok(out) +} + +/// The link status of every image object and placed document in the layers of `st`, as +/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is +/// looked at once. +pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> { + let linked = statuses(st); + let mut out = vec![]; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { + let status = match linked.get(&n.id).map(|(s, ..)| *s) { + Some(Status::Ok) => "linked", + Some(Status::Modified) => "modified", + Some(Status::Missing) => "missing", + None => "embedded", + }; + out.push((n.id, status)); + } + }); + out +} + +/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated +/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside +/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's +/// [`vectorcraft_doc::Document::locked_artboards`]. +fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> { + let d = &st.doc; + if is_selectable(d, st.isolation, locks, id) { + return None; + } + let ancestry = d.ancestry(id).unwrap_or_default(); + // Outside the isolated container, or the isolated container itself (its art is what's taken). + if let Some(c) = st.isolation.and_then(|i| d.node(i)) + && ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container()) + { + return Some("isolation"); + } + let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect(); + Some(if held.iter().any(|n| n.is_template()) { + "template" + } else if held.iter().any(|n| !n.visible) { + "hidden" + } else { + // A locked object, group or layer, or the locked artboard that holds it. + "locked" + }) +} + +/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the +/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list +/// those left out with the reason ([`skip_reason`]). +fn by_link_status(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byLinkStatus"; + let wanted = link_statuses(p, C)?; + let add = switch_or(p, "add", false, C)?; + let zoom = switch_or(p, "zoom", false, C)?; + let only: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()), + }; + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let (mut picked, mut skipped) = (vec![], vec![]); + for (id, status) in link_status_of_objects(st) { + if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) { + continue; + } + match skip_reason(st, &locks, id) { + None => picked.push(id), + Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })), + } + } + s.select(|_, sel| { + if add { + for id in &picked { + sel.add(*id); + } + } else { + sel.set(picked.iter().copied()); + } + })?; + let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::>(), "skipped": skipped }); + if zoom { + out["zoom"] = json!(true); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index bea05ff9e2..c97b278258 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -126,3 +126,185 @@ fn a_symbol_instance_is_measured_by_its_art() { assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); } + +/// Select by Link Status. +mod by_link_status { + use serde_json::{Value, json}; + use vectorcraft_doc::{Document, NodeId}; + + use crate::Session; + use crate::tests_links::{BLUE, Folder, RED, place, png, session, write}; + + const C: &str = "addon.select.byLinkStatus"; + + /// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`), + /// one whose file goes (`missing`), an embedded one, and a placed document whose file goes + /// (missing too), bottom to top. + struct Links { + s: Session, + ok: NodeId, + modified: NodeId, + missing: NodeId, + embedded: NodeId, + document: NodeId, + _dir: Folder, + } + + /// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two + /// removed. + fn links(name: &str) -> Links { + let dir = Folder::new(name); + let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); + write(&a, &png(10, 10, RED)); + write(&b, &png(12, 10, RED)); + write(&c, &png(14, 10, BLUE)); + write(&e, &png(16, 10, BLUE)); + write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0))); + let mut s = session(); + let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c)); + let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap()); + let document = place(&mut s, &d); + write(&b, &png(13, 10, BLUE)); + std::fs::remove_file(&c).unwrap(); + std::fs::remove_file(&d).unwrap(); + Links { s, ok, modified, missing, embedded, document, _dir: dir } + } + + /// Run the command with `p`, which must succeed. + fn run(s: &mut Session, p: Value) -> Value { + s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) + } + + /// `v` sorted. + fn sorted(mut v: Vec) -> Vec { + v.sort(); + v + } + + /// The selected objects, sorted. + fn selection(s: &Session) -> Vec { + sorted(s.doc().unwrap().selection.objects.clone()) + } + + /// The ids of a JSON list, sorted. + fn ids(v: &Value) -> Vec { + sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) + } + + #[test] + fn each_status_selects_its_images_and_placed_documents() { + let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status"); + // As the Links panel lists them. + let listed = s.execute("links.list", &json!({})).unwrap(); + let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone(); + assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s))); + let undo = s.doc().unwrap().history.undo.len(); + for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])] + { + s.execute("select.none", &json!({})).unwrap(); + let r = run(&mut s, json!({"status": status})); + assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}"); + assert_eq!(selection(&s), sorted(want), "{status}"); + assert_eq!(r["skipped"], json!([])); + assert!(r.get("zoom").is_none()); + } + // Several at once, in stacking order (bottom first); a status listed twice counts once. + let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]})); + assert_eq!(r["selected"], json!([ok.0, missing.0, document.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn ids_add_and_zoom() { + let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options"); + // Only among the ids given; other objects among them (a rectangle) are passed over. + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap(); + let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]})); + assert_eq!(r["selected"], json!([document.0])); + assert_eq!(selection(&s), vec![document]); + // Added to the selection. + let r = run(&mut s, json!({"status": "embedded", "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0]))); + assert_eq!(selection(&s), sorted(vec![document, embedded])); + // Replacing it by default. + run(&mut s, json!({"status": "modified"})); + assert_eq!(selection(&s), vec![modified]); + // Nothing to select: added, the selection stays; replacing, it empties. + let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([]))); + assert_eq!(selection(&s), vec![modified]); + run(&mut s, json!({"status": "linked", "ids": [embedded.0]})); + assert_eq!(selection(&s), vec![]); + // Zoom is reported for the caller (the desktop app zooms). + assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true); + assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none()); + } + + #[test] + fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() { + let dir = Folder::new("select-skipped"); + let files: Vec = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect(); + for (i, f) in files.iter().enumerate() { + write(f, &png(10 + i as u32, 10, RED)); + } + let mut s = session(); + let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i])); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + // Inside a locked group. + s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + // On a template layer. + let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let on_template = place(&mut s, &files[5]); + s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}"); + let mut reasons: Vec<(u64, String)> = + r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect(); + reasons.sort(); + let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")] + .into_iter() + .map(|(id, why)| (id.0, why.to_string())) + .collect(); + want.sort(); + assert_eq!(reasons, want, "{r}"); + assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str()))); + // In isolation mode, those outside the isolated group are left out. + s.execute("select.set", &json!({"ids": [mate.0]})).unwrap(); + let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": iso})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(r["selected"], json!([mate.0]), "{r}"); + let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone()); + assert_eq!(why(free), Some(json!("isolation"))); + assert_eq!(why(hidden), Some(json!("isolation"))); + } + + #[test] + fn bad_params_are_errors_and_leave_the_selection() { + let Links { mut s, ok, _dir, .. } = links("select-bad"); + for p in [ + json!({}), + json!({"status": null}), + json!({"status": []}), + json!({"status": "lost"}), + json!({"status": ["linked", "lost"]}), + json!({"status": 3}), + json!({"status": [true]}), + json!({"status": "linked", "add": "yes"}), + json!({"status": "linked", "zoom": 1}), + json!({"status": "linked", "ids": "1"}), + json!({"status": "linked", "ids": [999_999]}), + json!({"status": "linked", "ids": [-1]}), + json!({"status": "linked", "stauts": "missing"}), + ] { + s.execute("select.set", &json!({"ids": [ok.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}"); + } + // Without a document it is off, not a crash. + assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); + } +} diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs new file mode 100644 index 0000000000..c401733906 --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -0,0 +1,477 @@ +//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes +//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals +//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`, +//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes +//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star +//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box +//! rotation angles). + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use super::super::create::insert_look; +use super::super::{ + CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets, +}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.shapes.rectangle", + "Rectangle", + [], + None, + "{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + rectangle + ), + cmd!( + "addon.shapes.ellipse", + "Ellipse", + [], + None, + "{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + ellipse + ), + cmd!( + "addon.shapes.polygon", + "Polygon", + [], + None, + "{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + polygon + ), + cmd!( + "addon.shapes.star", + "Star", + [], + None, + "{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + star + ), + cmd!( + "addon.shapes.spiral", + "Spiral", + [], + None, + "{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}", + has_doc, + spiral + ), + cmd!( + "addon.shapes.box3d", + "3D Box", + [], + None, + "{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}", + has_doc, + box3d + ), + cmd!( + "addon.shapes.configure", + "Configure Shape", + [], + None, + "{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}", + has_selection, + configure + ), + ] +} + +fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) { + let start = f64_or(p, "startAngle", 0.0); + let end = f64_or(p, "endAngle", 360.0); + let mode = match str_param(p, "arcMode") { + Some("pie" | "slice") => shapes::EllipseMode::Slice, + Some("chord") => shapes::EllipseMode::Chord, + Some("arc" | "open") => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + }; + let span = (end - start).rem_euclid(360.0); + let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) }; + (pie, mode) +} + +fn rect_of(p: &Value, c: &str) -> Result { + let x = f64_req(p, "x", c)?; + let y = f64_req(p, "y", c)?; + let w = f64_req(p, "width", c)?; + let h = f64_req(p, "height", c)?; + Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs()) +} + +fn rect_xf(r: Rect, rot: f64) -> Affine { + if rot == 0.0 || !rot.is_finite() { + Affine::translate(r.origin().to_vec2()) + } else { + Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)) + } +} + +fn insert_custom(s: &mut Session, label: &str, live: Option, cs: CustomShape) -> Result { + let path = match (&live, cs.needs_extra_storage()) { + (Some(l), false) => l.to_path(), + _ => cs.to_path(), + }; + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, label, kind, look, None, true)?; + if cs.needs_extra_storage() + && let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn rectangle(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.rectangle"; + check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let radius = f64_or(p, "radius", 0.0).max(0.0); + let mut radii = [radius; 4]; + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + if let Some(val) = item.as_f64().filter(|n| n.is_finite()) { + radii[i] = val.max(0.0); + } + } + } + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf }; + let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode }; + let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" }; + insert_custom(s, label, Some(live), cs) +} + +fn ellipse(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.ellipse"; + check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf }; + let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf }; + insert_custom(s, "Ellipse", Some(live), cs) +} + +fn polygon(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.polygon"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + let cs = CustomShape::Polygon { + radius: r, + sides, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: None, + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Polygon", Some(live), cs) +} + +fn star(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.star"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r1 = f64_req(p, "radius1", c)?.abs(); + check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); + let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 }; + let cs = CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: Some(ratio), + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Star", None, cs) +} + +fn spiral(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.spiral"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["turns", "divergence", "innerRadius"], c)?; + check_switches(p, &["clockwise"], c)?; + let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0); + let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0); + let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999); + let clockwise = bool_or(p, "clockwise", true); + let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise }; + insert_custom(s, "Spiral", None, cs) +} + +fn box3d(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.box3d"; + let r = rect_of(p, c)?; + check_numbers(p, &["angleX", "angleY", "angleZ"], c)?; + check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?; + let angle_x = f64_or(p, "angleX", 30.0); + let angle_y = f64_or(p, "angleY", 30.0); + let angle_z = f64_or(p, "angleZ", 0.0); + let parallel_x = bool_or(p, "parallelX", false); + let parallel_y = bool_or(p, "parallelY", true); + let parallel_z = bool_or(p, "parallelZ", false); + let cs = CustomShape::Box3d { + w: r.width(), + h: r.height(), + angle_x, + angle_y, + angle_z, + parallel_x, + parallel_y, + parallel_z, + xf: Affine::translate(r.origin().to_vec2()), + }; + let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?; + if let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn configure(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.configure"; + check_numbers( + p, + &[ + "radius", + "startAngle", + "endAngle", + "sides", + "spokeRatio", + "rounded", + "randomized", + "turns", + "divergence", + "innerRadius", + "angleX", + "angleY", + "angleZ", + ], + c, + )?; + check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?; + let ids = targets(s, p)?; + let reset = bool_or(p, "reset", false); + let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some(); + let updated = s.edit("Live Shape", |d, _| { + let mut count = 0usize; + for id in ids { + let Some(n) = d.node_mut(id) else { continue }; + let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue }; + if apply_shape_params(&mut cs, p, reset) { + cs.write_to_node(n); + count += 1; + } + } + Ok(count) + })?; + Ok(json!({ "updated": updated })) +} + +fn num_param(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()) +} + +fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if let Some(a0) = num_param(p, "startAngle") { + pie.0 = a0.rem_euclid(360.0); + changed = true; + } + if let Some(a1) = num_param(p, "endAngle") { + pie.1 = a1.rem_euclid(360.0); + changed = true; + } + if let Some(m) = str_param(p, "arcMode") { + *arc_mode = parse_mode(m); + if *arc_mode == shapes::EllipseMode::Whole { + *pie = (0.0, 360.0); + } else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 { + *pie = (0.0, 270.0); + } + changed = true; + } + changed +} + +fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if reset { + *radii = [0.0; 4]; + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + if let Some(r) = num_param(p, "radius") { + *radii = [r.clamp(0.0, max_r); 4]; + changed = true; + } + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, v) in arr.iter().enumerate() { + if let Some(r) = v.as_f64().filter(|x| x.is_finite()) { + radii[i] = r.clamp(0.0, max_r); + changed = true; + } + } + } + changed | apply_arc_params(p, pie, arc_mode) +} + +fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option, rounded: &mut f64, randomized: &mut f64) -> bool { + let mut changed = false; + if reset { + *rounded = 0.0; + *randomized = 0.0; + if spoke_ratio.is_some() { + *spoke_ratio = Some(0.5); + } + changed = true; + } + if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) { + *sides = (n_sides as u32).clamp(3, 1000); + changed = true; + } + if let Some(star) = p.get("isStar").and_then(Value::as_bool) { + *spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None }; + changed = true; + } + if let Some(sr) = num_param(p, "spokeRatio") { + *spoke_ratio = Some(sr.clamp(0.01, 1.0)); + changed = true; + } + if let Some(rnd) = num_param(p, "rounded") { + *rounded = rnd.clamp(-10.0, 10.0); + changed = true; + } + if let Some(rand) = num_param(p, "randomized") { + *randomized = rand.clamp(-10.0, 10.0); + changed = true; + } + changed +} + +fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool { + match cs { + CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode), + CustomShape::Ellipse { pie, arc_mode, .. } => { + let mut changed = false; + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + changed | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => { + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + } + apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Spiral { turns, divergence, inner_radius, .. } => { + let mut changed = false; + if reset { + *turns = 3.0; + *divergence = 1.0; + *inner_radius = 0.0; + changed = true; + } + if let Some(t) = num_param(p, "turns") { + *turns = t.clamp(0.01, 1024.0); + changed = true; + } + if let Some(div) = num_param(p, "divergence") { + *divergence = div.clamp(0.0, 1000.0); + changed = true; + } + if let Some(ir) = num_param(p, "innerRadius") { + *inner_radius = ir.clamp(0.0, 0.999); + changed = true; + } + changed + } + CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => { + let mut changed = false; + if reset { + *angle_x = 30.0; + *angle_y = 30.0; + *angle_z = 0.0; + *parallel_x = false; + *parallel_y = true; + *parallel_z = false; + changed = true; + } + for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] { + if let Some(v) = num_param(p, k) { + *slot = v; + changed = true; + } + } + for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] { + if let Some(v) = p.get(k).and_then(Value::as_bool) { + *slot = v; + changed = true; + } + } + changed + } + } +} + +fn parse_mode(m: &str) -> shapes::EllipseMode { + match m { + "pie" | "slice" => shapes::EllipseMode::Slice, + "chord" => shapes::EllipseMode::Chord, + "arc" | "open" => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + } +} diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs new file mode 100644 index 0000000000..793ae6074c --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -0,0 +1,137 @@ +use serde_json::json; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use crate::Session; + +fn new_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +#[test] +fn default_shapes_do_not_alter_standard_documents() { + let mut s = new_session(); + + // Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute. + let rect_id = + NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!( + **live, + LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((10.0, 20.0)) + } + ); + assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0))); + + // Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute. + let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }); + assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0))); +} + +#[test] +fn addon_shapes_commands_and_format_roundtrip_preserve_paths() { + let mut s = new_session(); + + // Create customizable shapes through addon.shapes.* commands. + let box_id = NodeId( + s.execute( + "addon.shapes.box3d", + &json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert_eq!(path.subpaths.len(), 3); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6) + ); + + s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap(); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6)); + + let ell_id = NodeId( + s.execute( + "addon.shapes.ellipse", + &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(!path.subpaths[0].closed); + + s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap(); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(path.subpaths[0].closed); + + let rect_id = NodeId( + s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0]) + ); + + let poly_id = NodeId( + s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap() + ["id"] + .as_u64() + .unwrap(), + ); + s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(poly_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6) + ); + + let spiral_id = NodeId( + s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(spiral_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6) + ); + + // Verify that saving and reopening a document containing add-on shapes preserves both the + // baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored + // extras attribute across a save/load roundtrip. + let doc_before = s.doc().unwrap().doc.clone(); + let bytes = vectorcraft_format::save(&doc_before, false); + let doc_after = vectorcraft_format::load(&bytes).unwrap(); + let re_saved = vectorcraft_format::save(&doc_after, false); + assert_eq!(bytes, re_saved); + for id in [box_id, ell_id, rect_id, poly_id, spiral_id] { + let a = doc_before.node(id).unwrap(); + let b = doc_after.node(id).unwrap(); + assert_eq!(a.kind, b.kind); + assert_eq!(CustomShape::read(a), CustomShape::read(b)); + } +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 13186ed2ef..aa8f3b7df3 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -12,14 +12,14 @@ mod flavours; pub(crate) mod resources; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; pub use flavours::{ImageRead, read_image}; @@ -98,6 +98,114 @@ pub struct Clipboard { pub guides: Vec, } +/// Indices of segments selected on `sp` (either explicitly or via incident anchors). +pub(crate) fn subpath_selected_segments( + sp: &vectorcraft_geom::SubPath, + si: usize, + seg_refs: Option<&BTreeSet<(usize, usize)>>, + anchor_refs: Option<&BTreeSet<(usize, usize)>>, +) -> BTreeSet { + let seg_count = sp.segment_count(); + if seg_count == 0 { + return BTreeSet::new(); + } + let n = sp.anchors.len(); + let mut selected_segs = BTreeSet::new(); + + let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si)); + if has_explicit_segs { + if let Some(segments) = seg_refs { + for &(s, seg) in segments { + if s == si && seg < seg_count { + selected_segs.insert(seg); + } + } + } + return selected_segs; + } + + if let Some(anchors) = anchor_refs { + let sub_anchors: BTreeSet = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect(); + if !sub_anchors.is_empty() { + for i in 0..seg_count { + let next = (i + 1) % n; + if sub_anchors.contains(&i) && sub_anchors.contains(&next) { + selected_segs.insert(i); + } + } + + for &i in &sub_anchors { + let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) }; + let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) }; + if !prev_selected && !next_selected { + if sp.closed { + selected_segs.insert((i + n - 1) % n); + selected_segs.insert(i); + } else { + if i > 0 { + selected_segs.insert(i - 1); + } + if i < seg_count { + selected_segs.insert(i); + } + } + } + } + } + } + + selected_segs +} + +/// When direct selection is active on a path (some anchors or segments selected), extract only +/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None` +/// when the node is selected whole or is not a path. +pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option> { + let seg_refs = selection.segments.get(&node.id); + let anchor_refs = selection.anchors.get(&node.id); + if seg_refs.is_none() && anchor_refs.is_none() { + return None; + } + let path = node.path_data()?; + let mut subpath_segs = Vec::new(); + let mut total_segs = 0; + let mut total_selected = 0; + + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs); + total_segs += sp.segment_count(); + total_selected += segs.len(); + subpath_segs.push(segs); + } + + if total_selected == 0 { + return None; + } + + // When every segment of the path is selected, copy the object unchanged. + if total_segs > 0 && total_selected == total_segs { + return None; + } + + let mut pieces = vec![]; + for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) { + let seg_count = sp.segment_count(); + if selected_segs.is_empty() || seg_count == 0 { + continue; + } + let unselected: BTreeSet = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect(); + let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) }; + for surviving_sp in surviving { + let mut piece = node.clone(); + if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind { + piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide }; + } + pieces.push(piece); + } + } + if pieces.is_empty() { None } else { Some(pieces) } +} + impl Clipboard { pub fn is_empty(&self) -> bool { self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() @@ -118,15 +226,31 @@ impl Clipboard { } /// Objects `roots` of `st`'s document with their resources, source artboard and layers. - pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self { + pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self { let d = &*st.doc; let mut nodes = vec![]; let mut source_layers = vec![]; for id in roots { let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue }; - nodes.push(n.clone()); - // The nearest enclosing layer (or sublayer). - source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone())); + let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()); + let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. }))); + let inherit_appearance = |mut piece: Node| { + if let Some(parent) = compound_parent + && piece.appearance.items.is_empty() + { + piece.appearance = parent.appearance.clone(); + } + piece + }; + if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) { + for piece in pieces { + nodes.push(inherit_appearance(piece)); + source_layers.push(layer_name.clone()); + } + } else { + nodes.push(inherit_appearance(n.clone())); + source_layers.push(layer_name); + } } // Symbol instances are measured by their art. let symbols = d.symbol_boxes(); diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 88bf436f9a..0358acddf7 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -119,7 +119,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}", + "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", has_doc, join_scrub ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 8d95ee0017..660f52121e 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -336,7 +336,13 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { if let Some(st) = look.appearance.stroke_mut() { pen.write(st); } - insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected) + let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?; + if !keep_selected { + // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke + // by dropping the earlier selection, it does not keep it (#5752). + s.select(|_, sel| sel.clear())?; + } + Ok(out) } // ---------- Blob Brush ---------- diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index a4aa1f79a8..d63bdaea77 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,4 +1,6 @@ -use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths}; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; use super::{ Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Result, Session, SimplifyOptions, SubPath, Value, json, number_or, po, @@ -179,11 +181,121 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { // ---------- Join tool ---------- +/// Most open subpaths the Join tool compares pairwise for crossings before it only joins ends. +const MAX_TRIM_SUBPATHS: usize = 64; + +/// One end of an open subpath that runs on past where it crosses another: the part kept, which +/// ends at the crossing, and the part past it. +struct Overhang { + kept: SubPath, + cut: SubPath, +} + +impl Overhang { + fn at(&self) -> Option { + self.kept.anchors.last().map(|a| a.p) + } +} + +/// The overhangs of `sp` at its first and last crossing (`places`: subpath, segment, t, in order). +/// A crossing on an end anchor leaves no overhang there. +fn overhangs(sp: &SubPath, places: &[(usize, usize, f64)]) -> Vec { + let mut out = vec![]; + for (place, at_start) in [(places.first(), true), (places.last(), false)] { + let Some(&(_, seg, t)) = place else { continue }; + let (split, marks) = pt::insert_at(sp, &[(seg, t)]); + let Ok([first, second]) = <[SubPath; 2]>::try_from(split.cut_at(&marks)) else { continue }; + let (mut kept, cut) = if at_start { (second, first) } else { (first, second) }; + if at_start { + kept.reverse(); + } + out.push(Overhang { kept, cut }); + } + out +} + +/// Does the scrub `pts` (`scrub` as a path) cross `cut` or pass within `tol` of it? +fn scrubbed(cut: &SubPath, pts: &[Point], scrub: &PathData, tol: f64) -> bool { + let pd = PathData::single(cut.clone()); + pt::crossings(&[&pd, scrub], false).is_some_and(|c| c.first().is_some_and(|v| !v.is_empty())) + || cut.anchors.iter().any(|a| dist_to_polyline(pts, a.p) <= tol) + || pts.iter().any(|q| pd.nearest(*q).is_some_and(|n| n.4 <= tol)) +} + +/// Two crossing open subpaths, each `(path, subpath)`, trimmed and joined at the crossing. +struct TrimJoin { + a: (NodeId, usize), + b: (NodeId, usize), + joined: SubPath, +} + +/// #5844: two open subpaths among `ids` that cross, where the scrub runs over the part of each +/// that overhangs the crossing, trimmed at the crossing and joined there with a corner. When +/// several pairs or ends qualify, the one trimming the least wins. +fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: f64) -> Result> { + let mut open = vec![]; + for &id in ids { + let (pd, _) = path_of(d, id)?; + open.extend(pd.subpaths.into_iter().enumerate().filter(|(_, sp)| !sp.closed && sp.anchors.len() >= 2).map(|(si, sp)| (id, si, sp))); + } + if open.len() > MAX_TRIM_SUBPATHS { + return Ok(None); + } + let scrub = PathData::single(SubPath::polyline(pts, false)); + let mut best: Option<(f64, TrimJoin)> = None; + for (i, (ida, sa, a)) in open.iter().enumerate() { + for (idb, sb, b) in open.iter().skip(i + 1) { + let (pa, pb) = (PathData::single(a.clone()), PathData::single(b.clone())); + let Some(places) = pt::crossings(&[&pa, &pb], false) else { continue }; + let (Some(on_a), Some(on_b)) = (places.first(), places.get(1)) else { continue }; + let (oa, ob) = (overhangs(a, on_a), overhangs(b, on_b)); + for x in oa.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) { + for y in ob.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) { + let (Some(xa), Some(ya)) = (x.at(), y.at()) else { continue }; + let trimmed = subpath_len(&x.cut) + subpath_len(&y.cut); + if xa.distance(ya) > 1e-2 || best.as_ref().is_some_and(|b| b.0 <= trimmed) { + continue; + } + // `x` ends at the crossing; `y`, reversed, starts there: one corner anchor. + let mut joined = x.kept.clone(); + let mut rest = y.kept.clone(); + rest.reverse(); + let (Some(last), Some(first)) = (joined.anchors.last_mut(), rest.anchors.first()) else { continue }; + *last = + Anchor { p: last.p, h_in: last.h_in, h_out: first.h_out + (last.p - first.p), kind: vectorcraft_geom::AnchorKind::Corner }; + joined.anchors.extend(rest.anchors.into_iter().skip(1)); + best = Some((trimmed, TrimJoin { a: (*ida, *sa), b: (*idb, *sb), joined })); + } + } + } + } + Ok(best.map(|(_, t)| t)) +} + pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { const C: &str = "path.joinScrub"; let pts = points_param(p, "points", C)?; let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0); let st = s.doc()?; + let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)); + // Paths that cross with their ends scrubbed are trimmed there and joined (#5844). + if let Some(TrimJoin { a: (ida, sa), b: (idb, sb), joined }) = trim_join(&st.doc, &targets, &pts, tol)? { + s.edit("Join", |d, sel| { + let missing = || crate::EngineError::Other("Join: a subpath went missing".into()); + *path_mut(d, ida)?.subpaths.get_mut(sa).ok_or_else(missing)? = joined; + let pbm = path_mut(d, idb)?; + if sb >= pbm.subpaths.len() { + return Err(missing()); + } + pbm.subpaths.remove(sb); + if ida != idb && pbm.is_empty() { + d.remove(idb)?; + } + sel.set([ida]); + Ok(()) + })?; + return Ok(json!({ "id": ida.0 })); + } // Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start). let poly = { let mut bp = BezPath::new(); @@ -202,7 +314,7 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { }; let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied()); let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![]; - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) { + for id in targets { let (pd, _) = path_of(&st.doc, id)?; for (si, sp) in pd.subpaths.iter().enumerate() { if sp.closed || sp.anchors.len() < 2 { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e022998fa0..5b68b28d8d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, RulerMode, Unit}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; use super::clipboard::SwatchChoices; @@ -626,7 +626,7 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true)) } /// [`selected_roots`] for the selected objects inside the isolated object `root` @@ -637,18 +637,18 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { let st = s.doc()?; let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); - Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) + Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { - roots_within(doc, ids, |_| false) + roots_within(doc, ids, |_, _| false) } -/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the -/// compound's id. -fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bool) -> Vec { +/// [`roots_of`]; a compound path's member listed stays itself when `keep_member` holds for the +/// compound's id or the member's id. +fn roots_within(doc: &Document, ids: Vec, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -658,7 +658,7 @@ fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bo let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !keep_member(n.id, id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) @@ -689,11 +689,24 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option>)>) -> i }) } +/// The direct-selection flag and resolved root nodes for Copy and Cut operations. +fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { + let st = s.doc()?; + let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature"); + let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty()); + let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| { + in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member))) + }); + Ok((direct, roots)) +} + fn copy(s: &mut Session, _: &Value) -> Result { // The Artboard tool copies its artboard (and the art on it). if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), false); } + let (direct, targets) = copy_cut_targets(s)?; let st = s.doc()?; // Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay // behind. @@ -704,9 +717,13 @@ fn copy(s: &mut Session, _: &Value) -> Result { .filter_map(|i| st.doc.guides.get(*i)) .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() }) .collect(); - let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? }; - let st = s.doc()?; - let mut clip = Clipboard::copy(st, &roots); + let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets }; + let mut clip = Clipboard::copy(st, &roots, direct); + // Direct-selected anchors or segments that make no segment: nothing to copy, so the + // clipboard keeps what it held. + if direct && clip.nodes.is_empty() { + return Ok(json!({ "copied": 0 })); + } // Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes // measure from, as the objects' artboard is. if clip.nodes.is_empty() @@ -729,23 +746,80 @@ fn cut(s: &mut Session, p: &Value) -> Result { if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), true); } - // Copy promotes a compound member to its compound. Cut must remove the same objects it - // copied, while Clear on its own deletes exactly the selected members. // Ruler guides selected on their own: Copy takes them, Clear removes them. if s.doc()?.selection.is_empty() { copy(s, p)?; return clear(s, &json!({})); } - let ids = selected_roots(s)?; - copy(s, p)?; + // Copy promotes a compound member to its compound. Cut must remove the same objects it + // copied, while Clear on its own deletes exactly the selected members. + let (direct, roots) = copy_cut_targets(s)?; + let res = copy(s, p)?; + if res.get("copied").and_then(Value::as_u64) == Some(0) { + return Ok(res); + } // The selected ruler guides it copied go with the objects, in the same undo step (#3226). - if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) } + if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) } +} + +fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + // The selected ruler guides were copied too (#3226): they go in the same undo step. + let gone = selection.guides.clone(); + d.retain_guides(selection, |i, _| !gone.contains(&i)); + let mut survivors = vec![]; + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct { + d.remove(*id)?; + continue; + } + let Some(path) = node.path_data() else { + d.remove(*id)?; + continue; + }; + + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + for (si, sp) in path.subpaths.iter().enumerate() { + let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp.clone()); + } else { + subpaths.extend(super::path::without_segments(sp.clone(), &cuts)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(*id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + } else { + let path_node = super::path::path_mut(d, *id)?; + path_node.subpaths = subpaths; + survivors.push(*id); + } + } + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() } fn clear(s: &mut Session, p: &Value) -> Result { let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // Direct-selected anchors or segments: remove those, and any objects selected whole with them. - if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() { + if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) { return super::path::delete_anchors(s, p); } // Selected ruler guides (selected on their own). @@ -756,6 +830,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { // Guides selected with the art go with it (not when ids are given, unless `guides` says so: // Cut, which names the objects it copied). let with_guides = explicit.is_none() || bool_or(p, "guides", false); + let is_explicit = explicit.is_some(); let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc)); // Keep the selected ids themselves, without promoting compound members. Delete a selected // ancestor just once; its selected descendants leave with it. Layers themselves are kept. @@ -769,12 +844,26 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { + let parents: Vec<_> = + ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect(); d.remove_many(&ids)?; + for p in parents { + if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { + d.remove(p)?; + } + } if with_guides { let gone = sel.guides.clone(); d.retain_guides(sel, |i, _| !gone.contains(&i)); } - sel.clear(); + if is_explicit { + for id in &ids { + sel.remove(*id); + } + sel.prune(d); + } else { + sel.clear(); + } Ok(()) })?; ok() @@ -803,7 +892,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { return Err(EngineError::NoNode(*id)); } - let clip = Clipboard::copy(source, &roots_of(&source.doc, ids)); + let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false); let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); if !center.x.is_finite() || !center.y.is_finite() { @@ -874,7 +963,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let off = s.prefs.paste_offset; let st = s.doc()?; let same_doc = clip.source_doc == Some(st.uid); - let parent = st.target_parent()?; + let parent = st.target_parent_for_path()?; // Copied artboards come back with their art: together right of the last artboard, as they lay, // or where they were (Paste in Place, in Front, in Back). Paste on All Artboards pastes only the // art. @@ -907,8 +996,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let anchor = if front || back { let order = st.selection.in_paint_order(&st.doc); let a = if front { order.last() } else { order.first() }; - let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })); - a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id)) + let isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let can_enter_compound = clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. })) + || (isolated_compound && clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); + a.map(|id| paste_anchor(&st.doc, *id, can_enter_compound)).and_then(|id| st.doc.position(id)) } else { None }; @@ -975,7 +1066,45 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } }; *placed.entry(par).or_default() += 1; - new_ids.push(d.insert(par, idx, c)?); + let compound_par = par.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if let Some(par_id) = compound_par { + match c.kind { + NodeKind::Compound { children, .. } => { + let count = children.len(); + for (offset, child) in children.into_iter().enumerate() { + let mut child_node = Arc::unwrap_or_clone(child); + let child_id = d.alloc_id(); + child_node.id = child_id; + child_node.appearance = Default::default(); + if let NodeKind::Path { live, .. } = &mut child_node.kind { + *live = None; + } + let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) }; + new_ids.push(d.insert(par, insert_idx, child_node)?); + } + if count > 1 { + *placed.entry(par).or_default() += count - 1; + } + } + NodeKind::Path { .. } => { + c.appearance = Default::default(); + if let NodeKind::Path { live, .. } = &mut c.kind { + *live = None; + } + new_ids.push(d.insert(par, idx, c)?); + } + _ => { + let outer_par = d.parent_of(par_id); + let beside_idx = d.position(par_id).map(|(_, i, _)| i + 1).unwrap_or(usize::MAX); + let offset = *placed.entry(outer_par).or_default(); + *placed.entry(outer_par).or_default() += 1; + let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) }; + new_ids.push(d.insert(outer_par, insert_idx, c)?); + } + } + } else { + new_ids.push(d.insert(par, idx, c)?); + } } } sel.set(new_ids.iter().copied()); @@ -1016,11 +1145,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho })) } -/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only -/// paths (a compound path holds paths only). -fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId { +/// What pasted art goes beside: `id`, or the compound path holding it when the art cannot enter +/// the compound path (a compound path holds paths only; compound paths unpack into isolated compounds). +fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId { match doc.parent_of(id) { - Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, + Some(p) if !can_enter_compound && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, _ => id, } } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5b734c5a26..b1a422dea2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index b125e48a88..1108d3e2ca 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -202,13 +202,14 @@ impl RasterOptions { } } - /// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point; + /// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution, + /// within 0.01–64 pixels per point; /// `background`, else `page` (the document's background). - fn settings(&self, page: Option<[u8; 3]>) -> Result { + fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result { if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) { return Err(bad(C, format!("ppi must be a positive number, not {ppi}"))); } - let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0)); + let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale)); let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?; let embed_icc = self.embed_icc.unwrap_or(true); Ok(RasterExportOptions { @@ -544,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { // New Document → Background Contents: White makes the export opaque, unless `background` // says otherwise (JPEG has no alpha: white either way). let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]); - let mut settings = o.settings(page)?; + let mut settings = o.settings(page, doc.raster_ppi())?; let size = o.pixel_size()?; let format = match f.id { "png" => RasterFormat::Png, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 09e8de8294..33ecfa8ab2 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -76,7 +76,12 @@ pub(super) const RANGE: FormatOption = FormatOption { description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)", }; -const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" }; +const SCALE: FormatOption = FormatOption { + name: "scale", + ty: "number", + default: "null", + description: "pixels per point (0.01–64); without ppi or scale, uses the document's raster effects resolution", +}; const WIDTH: FormatOption = FormatOption { name: "width", @@ -112,8 +117,8 @@ const RECT: FormatOption = FormatOption { const PPI: FormatOption = FormatOption { name: "ppi", ty: "number", - default: "72", - description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale", + default: "null", + description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale; without either, uses the document's raster effects resolution", }; const BACKGROUND: FormatOption = FormatOption { diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 2f9312259c..6cb513db62 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "editingData", ty: "boolean", default: "true", - description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)", + description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)", }, FormatOption { name: "aiVersion", diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 69158c04b8..fca92d73f5 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -459,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() { ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap(); - assert_eq!(png["options"]["scale"]["default"], 1); + assert_eq!(png["options"]["scale"]["default"], Value::Null); assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len()); } diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 0f97a58627..0aa1733d8f 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -124,6 +124,30 @@ fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() { assert_eq!(d.metadata.author, "Ann Lee"); } +#[test] +fn an_ai_file_opens_with_its_active_artboard() { + let board = |x: i32, name: &str| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n", + x + 200 + ) + }; + let document = format!( + "%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n", + board(0, "One"), + board(300, "Two") + ); + let data = ai::sample_data(); + let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap(); + let data = [&data[..at], document.as_bytes(), &data[at..]].concat(); + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect(); + assert_eq!(names, ["One", "Two"], "{r}"); + assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}"); +} + #[test] fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() { let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0)); @@ -287,6 +311,38 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the +/// library the styles of its list, in the list's order, not the default styles; the file opens with +/// them too. +#[test] +fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { + let style = |name: &str, xa: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" + ) + }; + let styles = format!( + "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n", + style("Blue", "0 0 0 0 0 0 1 Xa\n"), + style("Green", "0 0 0 0 0 1 0 Xa\n"), + style("Red", "0 0 0 0 1 0 0 Xa\n") + ); + let data = ai::editing_data(200.0, 100.0, &styles); + let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"}); + let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}"); + let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap(); + let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Red", "Green", "Blue"], "{lib}"); + let r = open(&mut s, "fills.ai", &file, json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); + assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}"); +} + /// A 1-bit RGB image opens from the editing data in the colors its PDF part shows. #[test] fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { @@ -1023,6 +1079,46 @@ fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() { assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers"); } +/// A story of a `.ai` file's text document with no character or paragraph runs is set in +/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what +/// those styles leave out. +#[test] +fn an_ai_story_without_runs_takes_the_normal_styles() { + let story = "<< /0 << /0 (Hi\r) >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>"; + let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>"; + let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>"; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \ + /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + ai::layer("Art", text), + lines.join("\n") + ); + let mut s = Session::new(); + let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap(); + let mut texts = vec![]; + s.doc().unwrap().doc.walk(|c| { + if let NodeKind::Text(t) = &c.kind { + texts.push((**t).clone()); + } + }); + let [t] = texts.as_slice() else { panic!("one text object: {r}") }; + assert_eq!(t.plain_text(), "Hi"); + let style = &t.runs[0].style; + assert_eq!(style.size, 9.0, "{r}"); + assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false)); +} + /// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a /// placeholder): the editing data's type, outlined, as for an empty page. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index e7ea52d1ad..b87ec3ee2e 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -652,3 +652,265 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { let kinds = see_through_outline(&legacy.doc); assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}"); } + +/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric +/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a +/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops +/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and +/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement. +fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec { + use std::sync::Arc; + use vectorcraft_color::Paint; + use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + let link = |name: &Option| match name.as_deref().and_then(|n| doc.swatch(n)) { + Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(), + _ => "-".into(), + }; + let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p { + Paint::Gradient(g) => { + let geom = g.resolve(b); + let at: Vec = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)] + .map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0) + .to_vec(); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + let rgb = s.color.to_rgb().map(|v| (v * 100.0).round()); + format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint) + }) + .collect(); + format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch)) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)), + Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())), + Paint::None => "none".into(), + }; + // A compound path's paint is its own: its members' paint isn't drawn (Release gives them the + // compound path's), so a compound path's line lists only its members' bounds. + fn walk(nodes: &[Arc], f: &mut dyn FnMut(&Node)) { + for n in nodes { + f(n); + if !matches!(n.kind, NodeKind::Compound { .. }) { + walk(n.children().map(Vec::as_slice).unwrap_or_default(), f); + } + } + } + let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let lines = |nodes: &[Arc]| { + let mut lines = vec![]; + walk(nodes, &mut |n| { + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + return; + } + let Some(b) = n.geometric_bounds() else { return }; + let kind = match n.children() { + Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::>()), + None => "path".into(), + }; + let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + line += &match it { + AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)), + AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))), + }; + } + lines.push(line); + }); + lines + }; + let mut out = lines(&doc.layers); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1])); + out.extend(lines(&p.art)); + } + for sw in doc.swatches_iter() { + match &sw.paint { + // A gradient swatch reads back linked to itself. + Paint::Gradient(g) => { + let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone()))); + out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO))); + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)), + _ => {} + } + } + out +} + +/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to +/// hundredths), its link's path and relative path, and its pixels (RGBA). +fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::NodeKind; + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| { + let p = im.xf * vectorcraft_geom::Point::new(x, y); + ((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0) + }); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw()); + out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height)); + } + }); + out +} + +/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the +/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy; +/// the linked image keeps its path and its path relative to the document's folder. +#[test] +fn images_come_back_from_the_editing_copy() { + let dir = tmp("ai-images"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(format!("{dir}/art")).unwrap(); + let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { + let mut out = vec![]; + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + }; + let linked = format!("{dir}/art/linked.png"); + std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }])); + s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap(); + // The placed image is selected. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("file.place", &json!({"path": linked, "link": true})).unwrap(); + let path = format!("{dir}/images.ai"); + s.execute("document.save", &json!({"path": path})).unwrap(); + let before = image_outline(&s.doc().unwrap().doc); + assert_eq!(before.len(), 2, "{before:#?}"); + assert!(before[1].contains("art/linked.png"), "{before:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("image"), "{r}"); + let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings); + assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings); + assert_eq!(image_outline(©.doc), before, "{opts}"); + } +} + +/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of +/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose +/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and +/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a +/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`. +fn gradient_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| { + id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) + }; + let three = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": "#ff0000", "midpoint": 0.3}, + {"offset": 0.4, "color": "#00ff00", "opacity": 0.5}, + {"offset": 1, "color": "#0000ff"} + ], "start": [20, 40], "end": [60, 17]}); + let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap(); + let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap()); + let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}], + "start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]}); + s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap(); + let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0); + let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]}); + s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap(); + let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap(); + let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap(); + // Turned 30° and scaled to half about (140, 90). + let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5); + let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c]; + s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap(); + let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0); + let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0); + let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap()); + let mixed = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": {"gray": 0.8}}, + {"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7}, + {"offset": 1, "swatch": "Ink", "tint": 70} + ]}); + s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap(); + let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]}); + s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap(); + s +} + +/// Gradients and patterns come back from the editing copy for other apps alone (the native +/// document left out), with every save option that writes the copy; where the file has PDF pages, +/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each +/// gradient. +#[test] +fn gradients_and_patterns_come_back_from_the_editing_copy() { + let mut s = gradient_session(); + let before = (*s.doc().unwrap().doc).clone(); + let want = paint_outline(&before); + assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}"); + assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}"); + assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}"); + let copy = editing_copy(&b64(&r)); + assert_eq!(paint_outline(©), want, "{opts}"); + } + let path = tmp("gradients.ai"); + let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); + let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + for f in files.iter().filter(|f| !f.ends_with("-2.ai")) { + assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}"); + } + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap(); + let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap(); + // Each gradient the art paints with, by its kind and its stops' places and colors to 5% (version + // 7 writes a gradient stroke as its filled outline, so the objects differ, and a spot color's + // tint through its CMYK equivalent, 2% off here). + let gradients = |doc: &vectorcraft_doc::Document| { + let mut all = std::collections::BTreeSet::new(); + doc.walk(|node| { + for it in node.appearance.items.iter() { + if let vectorcraft_color::Paint::Gradient(g) = it.paint() { + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| format!("{:.3} {:?}", s.offset, s.color.to_rgb().map(|v| (v * 20.0).round() * 5.0))) + .collect(); + all.insert(format!("{:?} {stops:?}", g.gradient.kind)); + } + } + }); + all + }; + assert_eq!(gradients(&legacy.doc), gradients(&before)); +} diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 0c01844463..80001476a4 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> { None } +#[test] +fn raster_export_defaults_to_document_resolution() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap(); + assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0); + for format in ["png", "psd"] { + for (options, size, ppi) in [ + (json!({}), (300, 150), 300.0), + (json!({"scale": 1}), (72, 36), 72.0), + (json!({"scale": 2}), (144, 72), 144.0), + (json!({"ppi": 150, "scale": 2}), (150, 75), 150.0), + ] { + let mut params = options; + params["format"] = json!(format); + let bytes = b64(&s.execute("document.export", ¶ms).unwrap()); + assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}"); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{params}"); + } + } +} + +#[test] +fn raster_export_default_uses_the_sanitised_document_resolution() { + // A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the + // document reports (72 when not finite, else clamped), not at a zero, huge or failed size. + for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": width, "height": height})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored; + for format in ["png", "psd"] { + let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap()); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi"); + } + } +} + #[test] fn png_options_resolution_background_interlace_and_anti_aliasing() { let mut s = session(40.0, 30.0, 1); @@ -183,7 +221,7 @@ fn formats_list_the_raster_options() { assert!(opts("png").get(k).is_some(), "png lists {k}"); } assert_eq!(opts("png")["antiAlias"]["default"], "art"); - assert_eq!(opts("png")["ppi"]["default"], 72); + assert_eq!(opts("png")["ppi"]["default"], Value::Null); assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none()); assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none()); } diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index d4f18f3857..52a9002890 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -151,11 +151,16 @@ impl FlattenOptions { /// Whether colorized image `n`, art of `d`, counts as transparency by itself. With /// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale - /// or 1-bit doesn't: the EPS writer draws it in that paint. + /// or 1-bit doesn't: the EPS writer draws it in that paint. An image whose pixels don't take + /// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized. pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return true }; + let blob = d.image_blob(im); + if blob.is_some_and(|b| !b.takes_colorize()) { + return false; + } let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })); - !self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none()) + !self.keeps_colorize || !solid || blob.is_some_and(|b| b.gray_source().is_none()) } /// `n` shows an image whose see-through pixels count as transparency. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 585cd8a793..efe9786287 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -2,7 +2,7 @@ //! another everywhere or in the selection, and selecting the text that uses a font. Also the fonts //! available (the bundled and installed ones) and rescanning the installed fonts. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; @@ -64,18 +64,19 @@ pub fn specs() -> Vec { } /// Text objects in scope: the selection's (and their descendants') or the whole document's. -fn scope(s: &Session, selection_only: bool) -> Result> { +fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result> { let st = s.doc()?; let mut v = vec![]; + let mut seen = HashSet::new(); let mut add = |n: &vectorcraft_doc::Node| { n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) && !v.contains(&c.id) { + if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) { v.push(c.id); } }) }; if selection_only { - for id in &st.selection.objects { + for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { add(n); } @@ -97,7 +98,7 @@ fn being_edited(d: &Document, name: &str) -> bool { /// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a /// hidden or locked group of the art. Returned as (all of them, those shown by instances the /// Selection tool can reach: not hidden or locked, as `Document::editable` says). -fn selected_symbols(s: &Session) -> Result<(BTreeSet, BTreeSet)> { +fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet, BTreeSet)> { fn open_instances(n: &Node, out: &mut BTreeSet) { if !n.visible || n.locked { return; @@ -123,7 +124,7 @@ fn selected_symbols(s: &Session) -> Result<(BTreeSet, BTreeSet)> let st = s.doc()?; let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new()); let editable = st.doc.editable(); - for id in &st.selection.objects { + for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { n.walk(&mut |c| { if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { @@ -482,12 +483,66 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> { } fn fonts(s: &mut Session, p: &Value) -> Result { - let selection_only = bool_or(p, "selectionOnly", false); - let ids = scope(s, selection_only)?; + if bool_or(p, "selectionOnly", false) { + let selected = s.doc()?.selection.objects.clone(); + font_inventory(s, Some(&selected)) + } else { + font_inventory(s, None) + } +} + +impl Session { + /// List the fonts in the document, or in the given objects and their symbols. + pub fn font_inventory(&self, selected: Option<&[NodeId]>) -> Result { + font_inventory(self, selected) + } + + /// List text currently unavailable to a Replace Font request in its original selection. + pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result> { + let (family, style) = font_param(params, "from", "text.replaceFont")?; + let selection_only = bool_or(params, "selectionOnly", false); + let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?; + let d = &self.doc()?.doc; + let other: Vec = { + let editable = d.editable(); + scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect() + }; + let uses = |t: &TextObject| { + t.runs.iter().any(|r| { + r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name)) + }) + }; + let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::>(); + fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &n.kind + && (!open || closed) + && uses(t) + { + ids.push(n.id); + } + for child in n.children().map(Vec::as_slice).unwrap_or_default() { + visit(child, open, closed, uses, ids); + } + } + for symbol in d + .symbols + .iter() + .filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name))) + { + let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name)); + visit(&symbol.art, true, closed, &uses, &mut ids); + } + Ok(ids) + } +} + +fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result { + let ids = scope(s, selected.is_some(), selected)?; let d = &s.doc()?.doc; let db = vectorcraft_text::FontDb::global(); // The type in the art of the symbols in scope too: all of them, or those the selection shows. - let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None }; + let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None }; let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect(); texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t)); let mut found: BTreeMap = BTreeMap::new(); @@ -536,6 +591,21 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option)> { Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string))) } +fn skipped_font_texts( + d: &Document, + other: &[NodeId], + symbols: &[(&TextObject, bool)], + closed: &BTreeSet, + uses: &impl Fn(&TextObject) -> bool, +) -> usize { + let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count(); + skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count(); + if !closed.is_empty() { + skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count(); + } + skipped +} + fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "text.replaceFont"; let (ff, fs) = font_param(p, "from", C)?; @@ -567,7 +637,7 @@ fn replace(s: &mut Session, p: &Value) -> Result { // With selectionOnly: the symbols the selection shows; those shown only by hidden or locked // instances keep their type, counted in `skipped`. let (symbols, closed) = if selection_only { - let (all, open) = selected_symbols(s)?; + let (all, open) = selected_symbols(s, None)?; let closed: BTreeSet = all.difference(&open).cloned().collect(); (Some(open), closed) } else { @@ -579,13 +649,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { let (ids, skipped, in_symbols) = { let d = &s.doc()?.doc; let editable = d.editable(); - let (ids, other): (Vec, Vec) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id)); - let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count(); + let (ids, other): (Vec, Vec) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id)); let texts = symbol_texts(d, symbols.as_ref()); - skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count(); - if !closed.is_empty() { - skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count(); - } + let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses); // The text that changes: when none does, the document and its undo history stay as they are. let ids: Vec = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect(); let in_symbols = texts.iter().any(|(t, open)| *open && changes(t)); @@ -646,7 +712,7 @@ const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't fn select_font(s: &mut Session, p: &Value) -> Result { let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string(); let style = str_param(p, "style").map(str::to_string); - let ids = scope(s, false)?; + let ids = scope(s, false, None)?; let d = &s.doc()?.doc; // Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group // or layer, or on a locked artboard. diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 23f1be1906..b19206c397 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -10,7 +10,10 @@ //! //! An overlap area is a face of the planar arrangement of what the members paint (their fills and //! strokes, type outlined; other objects by their bounds): the part where two or more of them -//! overlap, split wherever a member's edge crosses it. +//! overlap, split wherever a member's edge crosses it. The area a member is raised in is that +//! face grown a little ([`SEAM`]) into the parts where only that member paints ([`raised_area`]), +//! so its edge does not lie on the edge of the member it passes over: there, both edges would be +//! anti-aliased and the member below would show through as a hairline (#5337). //! //! Behaviour: (Make, //! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward @@ -23,7 +26,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; use vectorcraft_pathops as po; -use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces, faces_in, is_intertwine, nonempty}; +use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas}; use super::edit::selected_roots; use super::pathops::Beside; @@ -302,13 +305,46 @@ fn tiers(order: &[usize]) -> Vec<(usize, usize)> { .collect() } +/// How far (pt) the area a member is raised in reaches past its overlap face, into the parts only +/// that member paints ([`raised_area`]). +const SEAM: f64 = 2.0; + +/// The area member `i` is raised in for `face`: the face, and the parts within [`SEAM`] of it +/// where only `i` paints (`areas`: what each member paints, [`painted_areas`]). Drawing `i` again +/// there changes nothing, and the edge of the area then lies inside `i`, not on the edge of a +/// member it passes over (where the anti-aliased edges of both would let that member show +/// through as a hairline). +fn raised_area(face: &PathData, i: usize, areas: &[Option]) -> PathData { + let Some(own) = areas.get(i).and_then(Option::as_ref) else { return face.clone() }; + let ring = po::offset_path(face, SEAM, po::Join::Round, 4.0); + let Some(near) = ring.bounds() else { return face.clone() }; + let mut paths = vec![(&ring, FillRule::NonZero), (own, FillRule::NonZero)]; + paths.extend( + areas + .iter() + .enumerate() + .filter(|(k, _)| *k != i) + .filter_map(|(_, a)| a.as_ref()) + .filter(|a| a.bounds().is_some_and(|b| b.overlaps(near))) + .map(|a| (a, FillRule::NonZero)), + ); + let only = po::boolean_n(&paths, |inside| inside.first() == Some(&true) && inside.get(1) == Some(&true) && !inside.iter().skip(2).any(|b| *b)); + if only.is_empty() { + return face.clone(); + } + nonempty(po::boolean(face, FillRule::NonZero, &only, FillRule::NonZero, po::BoolOp::Union)).unwrap_or_else(|| face.clone()) +} + /// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they -/// are. -fn arrange_face(children: &mut [Arc], face: &Face, order: &[usize]) { +/// are (`areas`: what each member paints, [`painted_areas`]). +fn arrange_face(children: &mut [Arc], face: &Face, order: &[usize], areas: &[Option]) { for (i, tier) in tiers(order) { - if let Some(c) = children.get_mut(i) { - set_tier(Arc::make_mut(c), &face.path, tier); + let Some(c) = children.get_mut(i) else { continue }; + // A member drawn in its own order there with no areas has nothing to change. + if tier == 0 && c.extras().intertwine.is_none() && c.extras().intertwine_tiers.is_empty() { + continue; } + set_tier(Arc::make_mut(c), &raised_area(&face.path, i, areas), tier); } } @@ -379,7 +415,8 @@ fn arrange(s: &mut Session, p: &Value) -> Result { Some(m) => Some(children.iter().position(|c| c.id == m).ok_or_else(|| bad(C, format!("object {} is not in this Intertwine group", m.0)))?), None => None, }; - let all = faces(&children); + let painted = painted_areas(&children); + let all = faces_of(&painted); let found = match (at, &lasso) { (Some(p), _) => face_at(&all, p).into_iter().collect(), (None, Some(l)) => faces_in(&all, l), @@ -423,7 +460,7 @@ fn arrange(s: &mut Session, p: &Value) -> Result { let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?; let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) }; for (face, new) in &plans { - arrange_face(children, face, new); + arrange_face(children, face, new, &painted); } Ok(()) })?; diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index ff4e3d0fbd..c85fe7e370 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -100,7 +100,31 @@ pub enum ItemKind { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LibraryColor { pub name: String, + /// The colour; a spot colour's full-strength ink (its swatch's colour), without the tint. pub color: Color, + /// A spot colour's ink (its swatch's name): using it adds the document's spot swatch of that + /// name and links the paint to it (#5812). Files written before spot colours have none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spot: Option, + /// A spot colour's tint (0..1; 1 for a process colour). + #[serde(default = "full_tint", skip_serializing_if = "is_full_tint")] + pub tint: f32, +} + +fn full_tint() -> f32 { + 1.0 +} + +fn is_full_tint(t: &f32) -> bool { + *t >= 1.0 +} + +/// A library colour as `library.add` reads it from the selection or params. +struct NewColor { + name: String, + color: Color, + spot: Option, + tint: f32, } /// A graphic: the art as a native document (its own resources included) and its thumbnail. @@ -369,6 +393,13 @@ impl Library { fn sanitize(&mut self) { clip(&mut self.name); self.colors.truncate(MAX_ITEMS); + for c in &mut self.colors { + if let Some(ink) = &mut c.spot { + clip(ink); + } + c.spot = c.spot.take().filter(|ink| !ink.trim().is_empty()); + c.tint = if c.spot.is_some() && c.tint.is_finite() { c.tint.clamp(0.0, 1.0) } else { 1.0 }; + } self.gradients.retain_mut(|g| clean_gradient(&mut g.gradient)); self.gradients.truncate(MAX_ITEMS); self.patterns.truncate(MAX_ITEMS); @@ -598,7 +629,7 @@ pub fn specs() -> Vec { "Library", [], None, - "{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}", + "{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color, spot: ink name or null, tint: 0..1}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}", always, get ), @@ -643,7 +674,7 @@ pub fn specs() -> Vec { "Add to Library", [], None, - "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", + "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint; with `color`, the spot swatch it is, kept as a spot colour), tint?: 0..100 (with `color` and a spot `swatch`: its %), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke), a colour linked to a spot swatch kept as a spot colour (the swatch's name, its colour and the tint); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", has_doc, add ), @@ -652,7 +683,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -782,7 +813,7 @@ fn get(s: &mut Session, p: &Value) -> Result { "id": id, "name": lib.name, "graphics": lib.graphics.iter().map(|g| json!({"id": g.id, "name": g.name, "width": g.width, "height": g.height, "thumbnail": g.thumbnail})).collect::>(), - "colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::>(), + "colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color, "spot": c.spot, "tint": c.tint})).collect::>(), "gradients": lib.gradients.iter().map(|g| json!({"name": g.name, "gradient": g.gradient})).collect::>(), "patterns": lib.patterns.iter().map(|p| json!({"name": p.name, "pattern": p.pattern, "thumbnail": p.thumbnail})).collect::>(), "charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::>(), @@ -856,13 +887,14 @@ fn add(s: &mut Session, p: &Value) -> Result { lib.graphics.push(g); placed(lib, &place, ItemRef { kind: item_kind, item: key }, v)? } - Item::Color((name, color)) => { + Item::Color(NewColor { name, color, spot, tint }) => { full(lib.colors.len())?; - if let Some(old) = lib.colors.iter().find(|o| o.color == color) { + // A spot colour is its ink: one of another ink (or a process colour) is another item. + if let Some(old) = lib.colors.iter().find(|o| o.color == color && o.spot == spot && o.tint == tint) { return Ok(json!({ "name": old.name, "existing": true })); } let name = unique(&given.clone().unwrap_or(name), |n| lib.colors.iter().any(|o| o.name == n)); - lib.colors.push(LibraryColor { name: name.clone(), color }); + lib.colors.push(LibraryColor { name: name.clone(), color, spot, tint }); placed(lib, &place, ItemRef { kind: item_kind, item: name.clone() }, json!({ "name": name, "existing": false }))? } Item::Gradient(mut g) => { @@ -925,7 +957,7 @@ fn placed(lib: &mut Library, place: &Placement, r: ItemRef, mut v: Value) -> Res enum Item { Graphic(LibraryGraphic), - Color((String, Color)), + Color(NewColor), Gradient(LibraryGradient), Pattern(LibraryPattern), Style(bool, Map), @@ -942,7 +974,7 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result { if roots.is_empty() { return Err(bad(cmd, "select the art to add first")); } - let clip = Clipboard::copy(st, &roots); + let clip = Clipboard::copy(st, &roots, false); let bounds = clip.bounds().ok_or_else(|| bad(cmd, "the selection draws nothing"))?; let mut doc = clip.to_document(); let board = bounds.inflate(1.0, 1.0); @@ -963,23 +995,38 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result { } /// The first selected object's solid fill (`stroke`: stroke) colour, else the default one, with a -/// name: its swatch's, else its hex. -fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<(String, Color)> { - // A colour given (a swatch dropped on the panel). +/// name: its swatch's, else its hex. A colour linked to a spot swatch keeps the ink (the swatch's +/// name and full-strength colour) and its tint. +fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result { + // A colour given (a swatch dropped on the panel), with its spot swatch's name when it has one. if let Some(c) = p.get("color").filter(|v| !v.is_null()) { let color = color_value(c).ok_or_else(|| bad(cmd, "bad colour"))?; - return Ok((color.to_hex(), color)); + let swatch = str_param(p, "swatch").map(str::to_string); + let tint = super::paint::tint_param(p, cmd)?.unwrap_or(1.0); + let given = NewColor { name: color.to_hex(), color, spot: None, tint: 1.0 }; + return Ok(spot_color(s, given, swatch, tint)); } match selected_paint(s, p, stroke)? { - Paint::Solid { color, swatch, .. } => { - let name = swatch.filter(|n| !n.is_empty()).unwrap_or_else(|| color.to_hex()); - Ok((name, color)) + Paint::Solid { color, swatch, tint } => { + let swatch = swatch.filter(|n| !n.is_empty()); + let name = swatch.clone().unwrap_or_else(|| color.to_hex()); + Ok(spot_color(s, NewColor { name, color, spot: None, tint: 1.0 }, swatch, tint)) } Paint::None => Err(bad(cmd, if stroke { "the selection has no stroke colour" } else { "the selection has no fill colour" })), _ => Err(bad(cmd, "only solid colours can be added (not gradients or patterns)")), } } +/// `c` as the spot colour of the active document's spot swatch `swatch` at `tint` (0..1), when +/// there is one: named after it, with its full-strength colour; else `c` as it is. +fn spot_color(s: &Session, c: NewColor, swatch: Option, tint: f32) -> NewColor { + let Some(doc) = s.active().map(|st| &st.doc) else { return c }; + let Some(name) = swatch else { return c }; + let Some(ink) = doc.swatch(&name).filter(|w| w.spot).and_then(|w| w.paint.color()) else { return c }; + let tint = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 1.0 }; + NewColor { name: name.clone(), color: ink, spot: Some(name), tint } +} + /// The first selected object's (or `ids`') fill (`stroke`: stroke) paint (type's: its first /// character's, as the proxy shows it), else the default one. fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result { @@ -989,11 +1036,13 @@ fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result { None => st.selection.objects.clone(), }; let from_art = ids.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| { - let (paint, to_doc, _) = n.proxy_paint(stroke, None)?; + let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?; // Type's characters paint in its own space: a gradient there takes its placement in the // document, so that it keeps the direction it shows. - match (paint, n.proxy_gradient(stroke, None)) { - (Paint::Gradient(g), Some((_, geom))) if to_doc != vectorcraft_geom::Affine::IDENTITY => { + match paint { + Paint::Gradient(g) if to_doc != vectorcraft_geom::Affine::IDENTITY => { + let mut geom = g.resolve(bounds); + geom.transform(to_doc, g.gradient.kind); Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() }))) } _ => Some(paint.clone()), @@ -1100,7 +1149,10 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillColor | Kind::StrokeColor => { let c = lib.colors.iter().find(|c| c.name == item).ok_or_else(missing)?; - json!({ "color": c.color }) + match &c.spot { + Some(ink) => json!({ "color": c.color, "spot": ink, "tint": c.tint }), + None => json!({ "color": c.color }), + } } Kind::FillGradient | Kind::StrokeGradient => { let g = lib.gradients.iter().find(|g| g.name == item).ok_or_else(missing)?; @@ -1143,7 +1195,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result { Kind::FillColor | Kind::StrokeColor => { let stroke = to_stroke(p, kind)?; let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?; - s.execute(if stroke { "paint.setStroke" } else { "paint.setFill" }, &json!({ "color": color }))?; + let set = if stroke { "paint.setStroke" } else { "paint.setFill" }; + match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) { + Some(ink) => use_spot(s, set, ink, &color, &data)?, + None => { + s.execute(set, &json!({ "color": color }))?; + } + } Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } })) } Kind::FillGradient | Kind::StrokeGradient => { @@ -1185,6 +1243,32 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } } +/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its +/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of +/// that name: the one it has when it is the same colour, else a new one (a name taken by another +/// colour gets a number), one undo step (#5812). +fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> { + const C: &str = "library.use"; + let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?; + let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0)); + let doc = &s.doc()?.doc; + let have = doc.swatch(ink).is_some_and(|w| w.spot && w.paint.color() == Some(c)); + in_one_step(s, |s| { + let swatch = if have { + ink.to_string() + } else { + let r = s.execute("swatch.new", &json!({ "name": ink, "color": color, "spot": true, "keepModel": true }))?; + r.get("name").and_then(Value::as_str).ok_or_else(|| bad(C, "the spot colour couldn't be added"))?.to_string() + }; + let mut p = json!({ "swatch": swatch }); + if tint < 1.0 { + p["tint"] = json!(tint * 100.0); + } + s.execute(set, &p)?; + Ok(()) + }) +} + /// The `to` param of `library.use`: whether the item paints the stroke (default: the kind's). fn to_stroke(p: &Value, kind: Kind) -> Result { match str_param(p, "to") { diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index c874a70ee9..5b5a6aa48a 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -2,7 +2,7 @@ //! subfolders (`links.findFiles`, searched on separate threads: [`super::findfiles`]). A file with //! a linked file's name, in any letter case, is ranked by what the link saved //! ([`vectorcraft_doc::LinkInfo`]): the same file (its size and hash), the same size (when the link -//! saved no hash, or the file is larger than 1 GB and isn't hashed), or the name only. +//! saved no hash, or the file is larger than 1 GiB and isn't hashed), or the name only. use std::collections::HashMap; use std::path::{Component, Path, PathBuf}; @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "Find Linked Files", [], None, - "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", + "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", always, find )] @@ -176,10 +176,29 @@ fn find(s: &mut Session, p: &Value) -> Result { } /// How many folder names the file at `found` has in common with the saved path `saved` (whichever -/// system's separators it uses), counted from the innermost out up to the first that differs, -/// compared in lowercase. +/// system's separators it uses, [`vectorcraft_doc::links::path_separators`]), counted from the +/// innermost out up to the first that differs, compared in lowercase. The saved path's parent +/// components are resolved first: `..` in a `/` or `\` path, and each colon after the first in a +/// run of colons in a classic Mac OS path (`Disk:Projects:Art::photo.png` is in `Projects`). fn shared_folders(saved: &str, found: &Path) -> usize { - let saved = saved.rsplit(['/', '\\']).skip(1).filter(|c| !c.is_empty()); + let separators = vectorcraft_doc::links::path_separators(saved); + let classic = separators == [':']; + let mut up = 0usize; + let saved = saved.rsplit(separators).skip(1).filter(move |c| { + let parent = if classic { c.is_empty() } else { *c == ".." }; + if parent { + up += 1; + return false; + } + if c.is_empty() || *c == "." && !classic { + return false; + } + if up > 0 { + up -= 1; + return false; + } + true + }); let found = found.parent().into_iter().flat_map(|p| p.components().rev()).map_while(|c| match c { Component::Normal(n) => n.to_str(), _ => None, diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 441249b05b..bcda11c2bd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { /// Per linked image in the layers of `st`: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). -fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { +pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) { let (status, found) = probe(g, st.path.as_deref()); @@ -1349,12 +1349,11 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va let doc_path = st.path.as_deref(); let path = fileio::document_path(&l.path, doc_path).ok(); let stamp = path.as_deref().and_then(file_stamp); - let folder_len = l.path.len().saturating_sub(l.name().len()); out["status"] = json!(status.as_str()); note_refused(out, l, doc_path); out["path"] = json!(l.path); out["fileName"] = json!(l.name()); - out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\'])); + out["location"] = json!(l.folder()); for (k, v) in [ ("page", l.page.map(u64::from)), ("fileSize", stamp.map(|s| s.0).or(l.size)), diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 73f0922145..e8b3941202 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -1,3 +1,5 @@ +use std::collections::BTreeSet; + use super::common::{ DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of, spacing_param, starts_param, wrap, @@ -180,6 +182,17 @@ fn finite_point(p: &Value, cmd: &str) -> Result { if q.x.is_finite() && q.y.is_finite() && q.x.abs() < 1e9 && q.y.abs() < 1e9 { Ok(q) } else { Err(bad(cmd, "x and y must be finite")) } } +/// Most spine points `with` names. +const MAX_SPINE_POINTS: usize = 10_000; + +/// The optional `with` list of spine point indexes (empty when absent). +fn spine_points_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("with").filter(|v| !v.is_null()) else { return Ok(vec![]) }; + let wrong = || bad(cmd, "`with` must be a list of at most 10000 spine point indexes"); + let list = v.as_array().filter(|l| l.len() <= MAX_SPINE_POINTS).ok_or_else(wrong)?; + list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect() +} + pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { const C: &str = "object.blend.spine.moveAnchor"; let index = index_param(p, "anchor", C)?; @@ -191,6 +204,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let with = spine_points_param(p, C)?; + if handle.is_some() && !with.is_empty() { + return Err(bad(C, "`with` moves points, not a handle")); + } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { @@ -198,9 +215,13 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { return Ok(()); } let delta = q - a.p; - a.translate(delta); - // The key objects on the point move with it. - for (k, _) in anchors.iter().enumerate().filter(|(_, a)| **a == index) { + // The other points selected with it (#5285) move as far. + let moved: BTreeSet = with.iter().copied().chain([index]).collect(); + for &i in &moved { + sp.anchors.get_mut(i).ok_or_else(|| bad(C, "no such spine point"))?.translate(delta); + } + // The key objects on the points move with them. + for (k, _) in anchors.iter().enumerate().filter(|(_, a)| moved.contains(*a)) { if let Some(key) = keys.get_mut(k) { Arc::make_mut(key).transform(Affine::translate(delta), false); } diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 99c813fa3e..abd88c3777 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on the point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 211905166b..390f6ef499 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -732,7 +732,7 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option Vec { "Convert to Text", [], None, - "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them; in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", + "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, convert_list_to_text ), @@ -207,7 +207,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect(); - let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art) }; + let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) }; let copied = clip.nodes.len(); if cut { s.edit("Cut Artboard", |d, sel| { @@ -876,8 +876,23 @@ fn move_editing_selection( fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { const C: &str = "text.convertListToText"; use vectorcraft_doc::text::ParaList; - let ids = super::typecmd::text_targets(s, p, C)?; let range = super::typecmd::TextRange::parse(p, C)?; + // After Select All in a frame of threaded text, a call that names no type and no range takes + // every paragraph of the story's editable frames; its locked and hidden frames stay as they are + // whichever way they are named. + let full = super::textedit::editing_story(s); + let story: Vec = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect(); + let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let ids = if !story.is_empty() && !named && range.is_none() { + story.clone() + } else { + super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect() + }; + // The selected story's locked and hidden frames: no paragraph whose text starts in one is + // converted, and none of their paragraphs is restyled. + let held: Vec = full.iter().copied().filter(|f| !story.contains(f)).collect(); + // Converting the whole story leaves it selected. + let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f)); let editing = match super::textedit::editing_range(s)? { Some((id, _, _)) => { let options = s.tool_options(); @@ -909,6 +924,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let mut converted = 0; for story in &stories { let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect(); + let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id)); let mut paras: Vec = vec![]; let mut named_parts = vec![]; let plains: Vec = frames.iter().map(|t| t.plain_text()).collect(); @@ -934,7 +950,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } for (i, named) in named_parts { if let Some(para) = paras.get_mut(i) { - let listed = para.main_part().is_some_and(|p| p.list.is_some()); + let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame)); para.converts |= named && listed; } } @@ -1021,7 +1037,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' }; style.tabs.insert(i, tab); } - for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) { + for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) { if let Some((stops, _)) = frame_edits.get_mut(part.frame) { stops.push((part.index, style.clone())); } @@ -1058,7 +1074,8 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - if let Some(editing) = editing { + // A whole story selected by Select All stays selected, with the characters inserted. + if let Some(editing) = editing.filter(|_| !whole_story) { move_editing_selection(s, editing, &story_before, &insertions)?; } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 2def5ce9ea..27cba98b5c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -10,8 +10,8 @@ use super::create::anchor_from_json; use super::draw2::usize_opt; use super::pathops::Beside; use super::{ - CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selection, - id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, + CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path, + has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, }; use crate::EngineError; @@ -77,7 +77,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}", - has_doc, + has_selected_path, reverse ), cmd!( @@ -86,7 +86,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+J"), "{ids?: [path, ...] (default: the selected paths; a compound path ID expands to its open member paths), subpaths?: [usize, usize] (which subpaths to join), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, for two paths/subpaths; default without ids: direct-selected ends if any, else the nearest pair; default with ids: the nearest pair), to?: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours)} join two or more open paths/subpaths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead", - has_selection, + has_selected_path, join ), cmd!( @@ -95,7 +95,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+Alt+J"), "{axis?: \"horizontal\"|\"vertical\"|\"both\"}", - has_selection, + has_selected_path, average ), cmd!( @@ -104,7 +104,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+Alt+Shift+J"), "{to: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours), ids?: [path, ...] (default: the selection; a compound path ID expands to its open member paths)} move two open path ends to their midpoint and join them there, as one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in ids or the selection (or both ends of one open path, closing it) → the joined path stays selected", - has_selection, + has_selected_path, average_join ), cmd!( diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index e1fecc6da3..5fd0f54434 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -15,8 +15,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp}; use super::edit::selected_roots; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param, - switch_or, + CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, + number_or, str_param, switch_or, }; pub fn specs() -> Vec { @@ -153,7 +153,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{tolerance?: pt (1), level?: 0..100 (the Simplify slider, in place of tolerance: 0 fewest anchor points, 50 is 1 pt, every 10 levels halves or doubles it), auto?: bool (Auto-Simplify: the lowest level whose tolerance is at most 1/400 of the selection's longer side, or 100 when that side is under 12.5 pt), cornerAngle?: deg (30), straightLines?: bool, wholePaths?: bool (false: a path with segments direct-selected, or between direct-selected anchors, simplifies only each run of them between its end anchors, which stay as they are, and keeps the runs selected; true simplifies those paths whole)} → {ids, before, after} anchor counts, and the level used with level or auto", - has_selection, + has_selected_path, simplify ), cmd!( @@ -162,17 +162,17 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: smoothed along its length by up to 5% of it and refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step; without ids, a path with anchor points or segments direct-selected smooths only the sections between them, which stay selected → {ids, before, after} anchor counts, and the level used", - has_selection, + has_selected_path, smooth ), - cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selection, add_anchor_points), + cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selected_path, add_anchor_points), cmd!( "object.path.divideObjectsBelow", "Divide Objects Below", ["Object", "Path"], None, "{} cut the objects below with the selected path (which is removed) → {ids}", - has_selection, + has_selected_path, divide_objects_below ), cmd!( @@ -181,7 +181,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{rows?: 2, columns?: 2, gutter?: pt (12; rowGutter?, columnGutter?: one of the two), totalHeight?, totalWidth?: pt (the grid's size; the selected paths' when left out), height?, width?: pt (each row's and column's size, which then sets the total), addGuides?: false (ruler guides along the row and column edges)} one grid of rectangles over the selected paths replaces them, painted as the topmost one → {ids, guides: count}", - has_selection, + has_selected_path, split_into_grid ), cmd!( @@ -770,7 +770,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let Some((path, rule)) = node_path(l) else { continue }; paths = true; let base = if matches!(l.kind, NodeKind::Compound { .. }) && path.is_closed() { po::normalize(&path, rule) } else { path }; - let off = po::offset_path(&base, delta, join, miter); + let off = match po::try_offset_path(&base, delta, join, miter) { + Ok(p) => p, + Err(po::PathOpsError::NonFinite) => continue, + Err(po::PathOpsError::TooComplex) => { + return Err(EngineError::Other("Offset Path: the path is too complex to offset".into())); + } + Err(e) => return Err(EngineError::Other(format!("Offset Path: {e}"))), + }; if off.is_empty() { continue; } @@ -890,6 +897,8 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br return None; } let (path, rule) = node_path(l)?; + // A fill belongs to the source path, whether open or closed. Converting its stroke + // preserves that fill on a separate copy (including compound member geometry). let mut parts: Vec = vec![]; let mut fills: Vec = vec![]; for item in &l.appearance.items { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 34592575c3..3d1c4be89b 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -452,27 +452,66 @@ impl DocState { pub fn current_layer(&self) -> Option { self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer())) } + /// Where new art is inserted: the isolation container (or its parent if the container cannot hold + /// the art type), else the active layer. pub fn insertion_parent(&self) -> Option { - // Ids are reused after undo (the id counter is part of the document), so a remembered - // layer or isolated group must still be one: a pasted group must never land in a path. - if let Some(i) = self.isolation - && self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) - { - return Some(i); + self.insertion_parent_for(false) + } + + /// Where new path art is inserted. When a compound path is isolated, returns the compound path + /// so new paths become members of the compound path. + pub fn insertion_parent_for_path(&self) -> Option { + self.insertion_parent_for(true) + } + + fn insertion_parent_for(&self, for_path: bool) -> Option { + if let Some(i) = self.isolation { + if self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) { + return Some(i); + } + if for_path && self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + return Some(i); + } } - // A single object isolated: new art goes beside it, in its group or layer. - if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i)) - && self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) - { - return Some(p); + if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i)) { + if self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) { + return Some(p); + } + if for_path && self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + return Some(p); + } + } + // Non-path art created while a compound path is isolated goes into the compound's parent container: + if let Some(iso) = self.isolation { + let compound = if self.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + Some(iso) + } else { + self.doc.parent_of(iso).filter(|p| self.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + }; + if let Some(c) = compound + && let Some(p) = self.doc.parent_of(c) + && self.doc.is_editable(p) + { + return Some(p); + } } // A sublayer takes new art only while it and the layers around it are shown and unlocked. self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer()) && self.doc.is_editable(*l)).or_else(|| self.doc.default_layer()) } + /// [`Self::insertion_parent`] for new art, which a locked or hidden layer never takes: an error /// when no layer is shown and unlocked, so the art is refused rather than hidden or locked away. pub fn target_parent(&self) -> Result> { - match self.insertion_parent() { + self.target_parent_for(false) + } + + /// [`Self::insertion_parent_for_path`] for new path art. + pub fn target_parent_for_path(&self) -> Result> { + self.target_parent_for(true) + } + + fn target_parent_for(&self, for_path: bool) -> Result> { + match self.insertion_parent_for(for_path) { Some(p) if !self.doc.is_editable(p) => Err(EngineError::Other("the target layer is locked or hidden".into())), parent => Ok(parent), } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ec3ccaf98..812a6282f2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -109,6 +109,7 @@ mod paintproxy; mod panelcmds; mod paragraphs; mod params; +mod path_menu_enabled; mod pathops; mod pathtype; mod pattern; diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 5db598a197..90e60bbb93 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -66,6 +66,34 @@ fn a_spine_point_added_and_moved_bends_the_blend() { assert!(center(&steps(&s, g)[1]).distance(Point::new(55.0, 5.0)) < 1e-6); } +/// #5285: `with` moves other spine points by as much as the one dragged, and the key objects on +/// them along, in one undo step; it can't go with a handle or name a point the spine lacks. +#[test] +fn spine_points_move_together() { + let mut s = session(); + let (a, b, g) = blend(&mut s); + s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap(); + let before = spec(&s, g); + assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [9]})).is_err()); + assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2], "handle": "in"})).is_err()); + assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": "2"})).is_err()); + assert_eq!(spec(&s, g), before, "refused requests change nothing"); + s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2, 1]})).unwrap(); + let sp = spec(&s, g).spine.unwrap(); + let pts: Vec = sp.subpaths[0].anchors.iter().map(|x| x.p).collect(); + let want = [Point::new(5.0, 5.0), Point::new(55.0, 45.0), Point::new(105.0, 45.0)]; + assert!(pts.len() == 3 && pts.iter().zip(want).all(|(p, w)| p.distance(w) < 1e-9), "{pts:?}"); + let keys = match node(&s, g).kind { + NodeKind::Blend { children, .. } => children, + _ => panic!("not a blend"), + }; + let at = |id: NodeId| keys.iter().find(|k| k.id == id).map(|k| center(k)).unwrap(); + assert!(at(b).distance(Point::new(105.0, 45.0)) < 1e-9, "the key on the point went along: {:?}", at(b)); + assert!(at(a).distance(Point::new(5.0, 5.0)) < 1e-9, "the other stayed: {:?}", at(a)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g), before, "one undo step"); +} + /// #2544: an Anchor Point drag on a blend spine must create two symmetric /// handles, not bend the adjacent segment and leave one handle behind. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c6bd07ecff..b4be82c2ec 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -830,6 +830,39 @@ fn shape_builder_drag_from_a_merged_shape_over_a_line_under_its_edge_makes_one_r assert!(left_half_gone(&s, h)); } +#[test] +fn shape_builder_removes_the_stretch_of_every_line_under_a_merged_edge() { + // Two lines along the same stretch, under the bottom edge of the merged top row: merging the + // row with the cell below takes the stretch between them from both lines. + for erase in [false, true] { + let mut s = session(); + let h1 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let h2 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let v = line(&mut s, (200.0, 100.0), (200.0, 300.0)); + let sq = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + s.edit("t", |d, _| { + for id in [h1, h2, v, sq] { + d.node_mut(id).unwrap().appearance.set_fill(Paint::None); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [h1.0, h2.0, v.0, sq.0]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[150, 150], [250, 150]]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[250, 150], [150, 250]], "erase": erase})).unwrap(); + let d = &s.doc().unwrap().doc; + let left: Vec = d + .children(d.default_layer()) + .into_iter() + .flatten() + .filter(|n| !outline(n).0.is_closed()) + .filter_map(|n| n.geometric_bounds()) + .filter(|b| b.height() < 1e-6 && (b.y0 - 200.0).abs() < 1e-6 && b.x0 < 199.0) + .collect(); + assert!(left.is_empty(), "erase {erase}: {left:?}"); + } +} + #[test] fn shape_builder_alt_deletes_a_region_or_a_line_piece() { let mut s = session(); diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index bcd590c2d4..2dab48c9f0 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -411,6 +411,27 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); } +/// A linked image showing the missing-link placeholder draws uncolorized, so its colorize paint +/// doesn't flatten it in EPS or PDF 1.3 export. +#[test] +fn a_colorized_missing_link_placeholder_is_not_flattened() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let flattened = + |out: &serde_json::Value| out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")); + let eps = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(!flattened(&eps), "{}", eps["warnings"]); + let pdf = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + assert!(!flattened(&pdf), "{}", pdf["warnings"]); + assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0))), "the image keeps its paint"); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index f8d49b0b4d..1af4ac40f0 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -386,10 +386,11 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } -/// With Keep selected off, the path a stroke draws or continues is not selected afterwards, the -/// rest of the selection stays, and the stroke is one undo step. +/// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too, +/// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is +/// deselected and the rest of the selection stays. The stroke is one undo step. #[test] -fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() { +fn pencil_with_keep_selected_off_leaves_nothing_selected() { let mut s = session(); let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0); let selected = |s: &Session| s.doc().unwrap().selection.objects.clone(); @@ -401,7 +402,7 @@ fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() { let off = s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false})).unwrap(); let off = NodeId(off["id"].as_u64().unwrap()); assert!(s.doc().unwrap().doc.node(off).is_some()); - assert_eq!(selected(&s), vec![r]); + assert!(selected(&s).is_empty(), "a new stroke with Keep selected off leaves nothing selected, the rectangle included"); assert_eq!(undo_steps(&s), undo + 1); // Continuing a selected open path deselects it and keeps the rest. let l = line(&mut s, 100.0, 300.0, 200.0, 300.0); @@ -1342,6 +1343,54 @@ fn join_tool_joins_endpoints_near_the_scrub_ends() { assert_eq!(p.subpaths[0].anchors[1].p, Point::new(202.5, 100.0)); } +/// #5844: scrubbing over the ends of two crossing open paths that run past the crossing trims +/// those ends and joins the paths there with a corner, rather than drawing a segment between the +/// ends. +#[test] +fn join_tool_trims_crossing_paths_and_joins_them_at_the_crossing() { + let mut s = session(); + let a = line(&mut s, 100.0, 300.0, 400.0, 300.0); + let b = line(&mut s, 300.0, 100.0, 300.0, 380.0); + s.execute("select.all", &json!({})).unwrap(); + drag(&mut s, "join", &[(380.0, 285.0), (285.0, 365.0)], Mods::default()); + let ps = paths(&s); + assert_eq!(ps.len(), 1, "one path is left: {ps:?}"); + let (id, p) = &ps[0]; + assert!(*id == a || *id == b); + assert_eq!(p.subpaths.len(), 1); + let mut got: Vec = p.subpaths[0].anchors.iter().map(|x| x.p).collect(); + if got.first() != Some(&Point::new(100.0, 300.0)) { + got.reverse(); + } + let near = |q: Point, r: Point| q.distance(r) < 1e-6; + assert_eq!(got.len(), 3, "{got:?}"); + assert!(near(got[0], Point::new(100.0, 300.0)) && near(got[1], Point::new(300.0, 300.0)) && near(got[2], Point::new(300.0, 100.0)), "{got:?}"); + assert!(!p.subpaths[0].closed); + assert_eq!(s.doc().unwrap().selection.objects.len(), 1); +} + +/// #5844: a curve with a hook past a straight line (the report's case) is trimmed at the crossing +/// and joined to the line's kept part; nothing of either overhang is left. +#[test] +fn join_tool_trims_a_curve_hooking_past_a_line() { + let mut s = session(); + line(&mut s, 0.0, 300.0, 480.0, 300.0); + s.execute("path.create", &json!({"anchors": [{"x": 260, "y": 0, "out": [290, 150]}, {"x": 378, "y": 368, "in": [310, 380]}]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + drag(&mut s, "join", &[(470.0, 280.0), (420.0, 330.0), (370.0, 380.0)], Mods::default()); + let ps = paths(&s); + assert_eq!(ps.len(), 1, "{ps:?}"); + let sp = &ps[0].1.subpaths[0]; + assert!(!sp.closed); + // Every anchor is on the kept sides: the line left of the crossing, the curve above it. + let joint = sp.anchors.iter().find(|x| (x.p.y - 300.0).abs() < 1e-6 && x.p.x > 100.0).expect("an anchor at the crossing"); + for x in &sp.anchors { + assert!(x.p.y <= 300.0 + 1e-6 && x.p.x <= joint.p.x + 1e-6, "{x:?} is past the crossing at {joint:?}"); + } + let bounds = ps[0].1.bounds().unwrap(); + assert!(bounds.y1 <= 300.0 + 1e-6 && bounds.x1 <= joint.p.x + 1e-6, "{bounds:?}"); +} + #[test] fn line_family_tools_draw_and_click_asks_dialog() { let mut s = session(); @@ -2708,6 +2757,42 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap(); } +#[test] +fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() { + // #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor, + // and its bounding box's handles scale the object; Direct Selection is back on the release. + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.select_tool("directSelection", v).unwrap(); + assert_eq!(s.lent_tool_id(&none), None); + assert_eq!(s.lent_tool_id(&cmd), Some("selection")); + // The path selected whole: the bottom-right handle scales it. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(s.cursor(Point::new(200.0, 200.0), cmd, v), vectorcraft_tools::Cursor::ResizeNwSe); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + for at in [250.0, 300.0] { + s.pointer(&PointerEvent::new(PointerKind::Drag, at, at).with_mods(cmd), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap(); + assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 300.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "{b:?}"); + // An anchor selected: a Cmd drag inside moves the whole path and the anchor stays selected. + gesture(&mut s, &[(300.0, 300.0)], none); + let picked = s.doc().unwrap().selection.anchors.clone(); + assert!(!picked.is_empty(), "Direct Selection picked the anchor"); + let before: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect(); + gesture(&mut s, &[(150.0, 150.0), (160.0, 160.0), (170.0, 150.0)], cmd); + let after: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(after, before.iter().map(|p| *p + kurbo::Vec2::new(20.0, 0.0)).collect::>()); + assert_eq!(s.doc().unwrap().selection.anchors, picked, "the anchor is still selected"); + assert_eq!(s.tool_id(), "directSelection"); +} + #[test] fn the_pen_drops_the_new_path_asterisk_once_a_path_is_started() { // The Pen's asterisk means a click starts a new path: it shows until the first anchor is diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index 6895d74a07..ecb9742a30 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -82,6 +82,28 @@ fn clicking_an_overlap_brings_the_object_below_to_the_front_there_only() { assert_eq!(hit(&s, 50.0, 70.0), Some(b)); } +/// #5337: where A is brought over B, the edges of B that cross A leave no blue hairline in A. +#[test] +fn the_object_brought_over_shows_no_seam_of_the_one_below() { + let mut s = session(); + intertwined(&mut s); + arrange(&mut s, json!({"at": [50, 30]})); + let zoom = 8.0; + let r = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 800, 800, Affine::scale(zoom), &Default::default()); + let mut worst = 0; + for y in 160..360 { + for x in 320..480 { + let (px, py) = ((x as f64 + 0.5) / zoom, (y as f64 + 0.5) / zoom); + // Well inside ring A's 8 pt stroke (radius 21 to 29), A covers every pixel. + let d = ((px - 35.0).powi(2) + (py - 50.0).powi(2)).sqrt(); + if (22.0..28.0).contains(&d) { + worst = worst.max(r.pixel(x, y)[2]); + } + } + } + assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})"); +} + #[test] fn clicking_the_same_overlap_again_swaps_back() { let mut s = session(); diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index a9bafc540b..d232b26767 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -111,6 +111,69 @@ fn colours_come_from_the_selection_and_paint_it() { assert!(s.execute("library.use", &json!({"library": lib, "kind": "fillColor", "item": "#nope"})).is_err()); } +/// The spot swatch of object `id`'s fill: its name, whether it is spot, the paint's tint. +fn spot_of(s: &Session, id: &Value) -> (String, bool, f32) { + match paint_of(s, id, false) { + vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } => { + let spot = s.doc().unwrap().doc.swatch(&name).is_some_and(|w| w.spot); + (name, spot, tint) + } + other => panic!("not linked to a swatch: {other:?}"), + } +} + +/// A spot colour added to a library keeps its ink, kept in the library's file: used in a new +/// document (or after its own was closed) it adds the spot swatch of that name and colour and +/// links the paint to it, at its tint; one the document has already is reused (#5812). +#[test] +fn a_spot_colour_stays_spot_in_another_document() { + let dir = std::env::temp_dir().join(format!("vc-libraries-spot-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let folder = dir.to_string_lossy().to_string(); + let mut s = session(); + s.libraries.set_dir(Some(folder.clone())); + let lib = run(&mut s, "library.create", json!({"name": "Inks"}))["id"].as_str().unwrap().to_string(); + let ink = vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0); + run(&mut s, "swatch.new", json!({"name": "Kiss-cut", "color": ink, "spot": true})); + let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Kiss-cut", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["name"], "Kiss-cut"); + // A swatch dropped on the panel: its colour with its spot swatch's name and tint. + let r = run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor", "color": ink, "swatch": "Kiss-cut", "tint": 40, "name": "Light"})); + assert_eq!(r["existing"], false, "a tint is another colour"); + // The same colour as a process colour is another item. + run(&mut s, "paint.setFill", json!({"color": ink, "ids": [a]})); + assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["existing"], false); + run(&mut s, "file.close", json!({})); + + // Another session reads the library's file into a new document. + let mut t = session(); + t.libraries.set_dir(Some(folder)); + let got = run(&mut t, "library.get", json!({"library": "Inks"})); + assert_eq!(got["colors"][0]["spot"], "Kiss-cut"); + assert_eq!(got["colors"][2]["spot"], Value::Null); + let b = run(&mut t, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut t, "select.set", json!({"ids": [b]})); + run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Kiss-cut"})); + assert_eq!(spot_of(&t, &b), ("Kiss-cut".to_string(), true, 1.0)); + let doc = &t.doc().unwrap().doc; + assert_eq!(doc.swatch("Kiss-cut").unwrap().paint.color(), Some(ink), "the ink keeps its values"); + assert!(doc.spot_names().contains(&"Kiss-cut".to_string())); + // Its tint links to the same swatch: none is added again. + let swatches = doc.swatches.len(); + run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Light"})); + let (name, spot, tint) = spot_of(&t, &b); + assert_eq!((name.as_str(), spot), ("Kiss-cut", true)); + assert!((tint - 0.4).abs() < 1e-4, "{tint}"); + assert_eq!(t.doc().unwrap().doc.swatches.len(), swatches); + // One undo step takes back the new swatch along with the paint. + run(&mut t, "edit.undo", json!({})); + run(&mut t, "edit.undo", json!({})); + assert!(t.doc().unwrap().doc.swatch("Kiss-cut").is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// The fill (`stroke`: stroke) paint of object `id`. fn paint_of(s: &Session, id: &Value, stroke: bool) -> vectorcraft_color::Paint { let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); diff --git a/crates/engine/src/tests/linkfiles.rs b/crates/engine/src/tests/linkfiles.rs index 5990b35234..695ea41419 100644 --- a/crates/engine/src/tests/linkfiles.rs +++ b/crates/engine/src/tests/linkfiles.rs @@ -123,6 +123,67 @@ fn files_found_are_ranked_by_what_the_link_saved() { assert_eq!(photo_row["path"], json!(root.join("orig/photo.png"))); } +/// A link saved as a classic Mac OS path (`Disk:Folder:file`) is looked for by its file name, and +/// the files found are ranked by the folder names they share with that path. +#[test] +fn a_classic_mac_path_is_found_by_its_name_and_folders() { + let root = folder("classic"); + let mut s = session_for(&root); + let photo = png(50, 30, BLUE); + write(&root.join("orig/photo.png"), &photo); + let id = placed(&mut s, &root.join("orig/photo.png")); + s.edit("classic path", |d, _| { + if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind { + im.link.as_mut().unwrap().path = "Old Disk:Art:Images:photo.png".into(); + } + Ok(()) + }) + .unwrap(); + std::fs::remove_dir_all(root.join("orig")).unwrap(); + // Other files of the name (a search ends once it finds the same file). + let search = root.join("search"); + let mut changed = photo.clone(); + *changed.last_mut().unwrap() ^= 1; + write(&search.join("a/photo.png"), &changed); + write(&search.join("z/Art/Images/photo.png"), &changed); + s.execute("links.findFiles", &json!({"folder": search})).unwrap(); + let r = finished(&mut s); + assert_eq!(r["state"].as_str(), Some("done"), "{r}"); + let files = [("search/z/Art/Images/photo.png", "name", false), ("search/a/photo.png", "name", false)]; + assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c))); +} + +/// The folders a saved path shares with a file found are counted after its parent components are +/// resolved: `Art::` in a classic Mac OS path and `Art/..` in any other path go back to `Projects`. +#[test] +fn parent_components_in_a_saved_path_are_resolved_before_ranking() { + for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] { + let root = folder(tag); + let mut s = session_for(&root); + let photo = png(50, 30, BLUE); + write(&root.join("orig/photo.png"), &photo); + let id = placed(&mut s, &root.join("orig/photo.png")); + s.edit("saved path", |d, _| { + if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind { + im.link.as_mut().unwrap().path = saved.into(); + } + Ok(()) + }) + .unwrap(); + std::fs::remove_dir_all(root.join("orig")).unwrap(); + let search = root.join("search"); + let mut changed = photo.clone(); + *changed.last_mut().unwrap() ^= 1; + write(&search.join("Art/photo.png"), &changed); + write(&search.join("Projects/photo.png"), &changed); + s.execute("links.findFiles", &json!({"folder": search})).unwrap(); + let r = finished(&mut s); + assert_eq!(r["state"].as_str(), Some("done"), "{saved}: {r}"); + let files = [("search/Projects/photo.png", "name", false), ("search/Art/photo.png", "name", false)]; + assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c)), "{saved}"); + } +} + /// Without `ids`, a search looks for the files that can't be found; with them, for those objects' /// files, whatever their status. #[test] diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 41bc6b8fb8..7cdf43ad7d 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -283,6 +283,44 @@ fn a_missing_link_renders_its_preview_and_relinks() { assert!(s.execute("links.relink", &json!({"ids": [id.0]})).is_err(), "path or folder"); } +/// A link stored as a classic Mac OS path (`Disk:Folder:file`, as older `.ai` files keep them) is +/// named by its last component: the Links panel shows that name and its folder, Relink to Folder +/// looks for that name, and the document's own folder is searched for it. The stored path is kept. +#[test] +fn a_classic_mac_path_is_found_by_its_file_name() { + const CLASSIC: &str = "Macintosh HD:Images:photo.png"; + let dir = Folder::new("classic-mac"); + let pic = dir.file("art/photo.png"); + write(&pic, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + saved_image(&mut v)["link"] = json!({ "path": CLASSIC }); + let doc_path = dir.file("poster.vectorcraft"); + write(&doc_path, &serde_json::to_vec(&v).unwrap()); + let r = open(&mut s, &doc_path); + let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + assert_eq!(r["missingLinks"], json!([{"name": "photo.png", "path": CLASSIC, "ids": [id.0]}])); + let i = s.execute("links.info", &json!({"id": id.0})).unwrap(); + assert_eq!( + (i["fileName"].as_str(), i["location"].as_str(), i["path"].as_str()), + (Some("photo.png"), Some("Macintosh HD:Images"), Some(CLASSIC)), + "{i}" + ); + // Relink to Folder: the file of the link's name there. + let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap(); + assert_eq!(r, json!({"relinked": [], "notFound": ["photo.png"]})); + write(&dir.file("found/photo.png"), &png(600, 300, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap(); + assert_eq!(r, json!({"relinked": [id.0], "notFound": []})); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + // The document's folder: the file of the link's name beside the document. + write(&dir.file("photo.png"), &png(600, 300, RED)); + let r = open(&mut s, &doc_path); + assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}"); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + /// A `w`×`h` PNG of noise cut to half its length: its header reads, its pixels don't. pub(crate) fn cut_png(w: u32, h: u32) -> Vec { let img = image::RgbImage::from_fn(w, h, |x, y| { diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index a9e832bb36..b64736b973 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -414,3 +414,258 @@ fn a_group_shows_its_contents_in_the_proxies() { s.execute("select.none", &json!({})).unwrap(); assert_eq!(s.proxy_paints().0, s.paint.fill); } + +/// The top fill and top stroke of object `id`. +fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) { + let n = node(s, id); + (n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map_or(0.0, |st| st.width)) +} + +/// Apply Fill to Stroke gives each selected object a stroke of its own fill, not the first +/// object's; Apply Stroke to Fill does the other way (#5530). A stroke that had no paint and no +/// width gets the 1 pt Swap Fill and Stroke gives it, and the paint copied from stays. +#[test] +fn each_object_copies_its_own_paint_onto_the_other() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": hex})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("object.setStrokeWidth", &json!({"ids": [id.0], "width": 0})).ok(); + } + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(r["objects"], 2); + for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] { + let (fill, stroke, width) = paints(&s, id); + assert_eq!(fill.color().unwrap().to_hex(), hex, "the fill stays"); + assert_eq!(stroke, fill, "the stroke is the object's own fill"); + assert!(width > 0.0, "and shows: {width}"); + } + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#00ff00"})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert_eq!((fill.color().unwrap().to_hex(), stroke.color().unwrap().to_hex()), ("#00ff00".into(), "#00ff00".into())); + assert_eq!(paints(&s, b).0.color().unwrap().to_hex(), "#0080ff", "an object not aimed at is left alone"); +} + +/// A global swatch at a tint stays linked at that tint, and a gradient keeps its stops and +/// placement: the paint is copied as it is. +#[test] +fn a_linked_swatch_and_a_gradient_copy_as_they_are() { + let mut s = session(); + let a = rect(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#c82828", "global": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert!(matches!(&stroke, Paint::Solid { swatch: Some(name), .. } if name == "Ink"), "{stroke:?}"); + assert_eq!(stroke, fill); + let g = json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "angle": 30}}); + let mut q = g.clone(); + q["ids"] = json!([a.0]); + s.execute("paint.setFill", &q).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert!(matches!(stroke, Paint::Gradient { .. }), "{stroke:?}"); + assert_eq!(stroke, fill, "the same stops and placement"); +} + +/// None copies as None, as Swap moves it; `skipNone` leaves an object whose source is None alone. +#[test] +fn none_copies_unless_skipped() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#123456"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#ff8000"})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({"ids": [a.0, b.0], "skipNone": true})).unwrap(); + assert_eq!(r["objects"], 1, "only the object with a fill changed"); + assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#123456", "skipped: its stroke stays"); + assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#ff8000"); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + assert!(paints(&s, a).1.is_none(), "without skipNone, no fill gives no stroke"); +} + +/// The objects inside a group each copy their own paint, as for Swap Fill and Stroke. +#[test] +fn a_groups_members_each_copy_their_own() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#ff0000"); + assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#00ff00"); +} + +/// Type: each run's stroke takes its own fill, so multi-colour text keeps its colours. +#[test] +fn each_text_run_copies_its_own_fill() { + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#aa0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [id.0]})).unwrap(); + let NodeKind::Text(t) = &node(&s, id).kind else { panic!("not text") }; + for r in &t.runs { + assert_eq!(r.style.stroke, r.style.fill, "{:?}", r.text); + assert!(r.style.stroke_width > 0.0, "a painted stroke is visible"); + } +} + +/// One undo step each; when nothing changes, none, and the document stays unmodified. Bad +/// parameters change nothing, not even the defaults. +#[test] +fn one_undo_step_none_when_nothing_changes_and_bad_params_change_nothing() { + let mut s = session(); + let id = rect(&mut s); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + select_with_a_step_to_redo(&mut s, &[id]); + let before = history(&s); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({})).unwrap(); + assert_eq!(history(&s), before, "the paints were already the same"); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + let before = history(&s); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(history(&s), (before.0 + 1, 0, true), "one step"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Apply Fill to Stroke")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s, id).1.color().unwrap().to_hex(), "#0000ff"); + let defaults = (s.paint.fill.clone(), s.paint.stroke.clone()); + for (cmd, p) in [("addon.color.fillToStroke", json!({"ids": "not an array"})), ("addon.color.strokeToFill", json!({"skipNone": "yes"}))] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), defaults, "the defaults are as they were"); +} + +/// With nothing selected the defaults for new art change the same way: the default stroke takes +/// the default fill, with the weight Swap gives a stroke that had none. +#[test] +fn with_nothing_selected_the_defaults_take_it() { + let mut s = session(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(r["objects"], 0); + assert_eq!(s.paint.stroke, s.paint.fill); + assert!(s.paint.stroke_width > 0.0); + s.execute("paint.setStroke", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({})).unwrap(); + assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#ff00ff"); +} + +/// Copying None onto an item the object doesn't have adds nothing: with no fill and no stroke +/// item at all, neither command records an undo step or touches the object. +#[test] +fn copying_none_onto_a_missing_item_changes_nothing() { + let mut s = session(); + let id = rect(&mut s); + s.edit("No paint items", |d, _| { + d.node_mut(id).unwrap().appearance.items.clear(); + Ok(()) + }) + .unwrap(); + assert_eq!((paints(&s, id).0, paints(&s, id).1), (Paint::None, Paint::None)); + select_with_a_step_to_redo(&mut s, &[id]); + let (before, art) = (history(&s), node(&s, id)); + for cmd in ["addon.color.fillToStroke", "addon.color.strokeToFill"] { + assert_eq!(s.execute(cmd, &json!({})).unwrap()["objects"], 0, "{cmd}"); + assert_eq!(history(&s), before, "{cmd}: no undo step"); + assert_eq!(node(&s, id), art, "{cmd}: no item added"); + } +} + +/// A graph's series and its labels keep the copied paint when the graph is drawn again: the +/// graph takes it in the same undo step, as it does from paint.setFill. +#[test] +fn a_graph_series_and_its_labels_keep_the_copied_paint_when_drawn_again() { + let mut s = session(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let g = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let series = |s: &Session| node(s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let label = |s: &Session| { + let axes = node(s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + axes.children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "4")).unwrap().clone() + }; + let sid = series(&s).id; + s.execute("paint.setFill", &json!({"ids": [sid.0], "color": "#12ab34"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [sid.0], "none": true})).unwrap(); + let lid = label(&s).id; + s.execute("paint.setFill", &json!({"ids": [lid.0], "color": "#e8573f"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("addon.color.fillToStroke", &json!({"ids": [sid.0, lid.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step"); + let kept = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone(); + assert_eq!(kept.series_paints[0].stroke.as_ref().and_then(Paint::color).map(|c| c.to_hex()), Some("#12ab34".into())); + assert_eq!(kept.label_styles.values.as_ref().and_then(|st| st.stroke.color()).map(|c| c.to_hex()), Some("#e8573f".into())); + s.execute("graph.setData", &json!({"id": g.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let marks = series(&s).children().unwrap().to_vec(); + let bars: Vec<_> = marks.iter().filter(|m| matches!(m.kind, NodeKind::Path { .. })).collect(); + assert!(!bars.is_empty()); + for m in bars { + assert_eq!(m.appearance.stroke_paint().color().map(|c| c.to_hex()), Some("#12ab34".into()), "a redrawn mark keeps the stroke"); + } + let redrawn = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + let text = redrawn.children().unwrap().iter().find_map(|c| if let NodeKind::Text(t) = &c.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!(text.runs[0].style.stroke.color().map(|c| c.to_hex()), Some("#e8573f".into()), "a redrawn value label keeps the stroke"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let back = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone(); + assert!( + back.series_paints[0].stroke.as_ref().is_none_or(|p| p.is_none()), + "undo takes the graph's stroke back: {:?}", + back.series_paints[0].stroke + ); +} + +/// A series drawn with a marker design: its own marks copy their paint, but the design's art +/// keeps the design's paint, as paint.setFill leaves it (painting it would last only until the +/// graph is drawn again). +#[test] +fn a_marker_designs_art_in_a_series_keeps_its_paint() { + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [r], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [r], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Square"})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let g = NodeId( + s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Square"})).unwrap(); + let series = node(&s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + // The design's paths sit in groups inside the series; its own marks are its direct children. + let design_strokes = |s: &Session| { + let grp = node(s, series.id); + let mut out = vec![]; + for c in grp.children().unwrap() { + if !matches!(c.kind, NodeKind::Path { .. }) { + c.walk(&mut |n| { + if let NodeKind::Path { .. } = n.kind { + out.push(n.appearance.stroke_paint()); + } + }); + } + } + out + }; + let before = design_strokes(&s); + assert!(!before.is_empty(), "the series draws the design"); + s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap(); + assert_eq!(design_strokes(&s), before, "the design's art keeps its paint"); +} diff --git a/crates/engine/src/tests/path_menu_enabled.rs b/crates/engine/src/tests/path_menu_enabled.rs new file mode 100644 index 0000000000..2b9eb44aae --- /dev/null +++ b/crates/engine/src/tests/path_menu_enabled.rs @@ -0,0 +1,35 @@ +//! Object → Path items that work on paths are disabled while only non-path objects are selected. + +use serde_json::json; + +use crate::*; + +const PATH_ITEMS: [&str; 9] = [ + "path.reverse", + "path.join", + "path.average", + "path.averageJoin", + "object.path.simplify", + "object.path.smooth", + "object.path.addAnchorPoints", + "object.path.divideObjectsBelow", + "object.path.splitIntoGrid", +]; + +fn enabled(s: &Session, id: &str) -> bool { + command_specs().iter().find(|c| c.id == id).is_some_and(|c| (c.enabled)(s).is_ok()) +} + +#[test] +fn path_items_need_a_path_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); + for id in PATH_ITEMS { + assert!(!enabled(&s, id), "{id} enabled for text"); + } + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + for id in PATH_ITEMS { + assert!(enabled(&s, id), "{id} disabled for a path"); + } +} diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 2eaeeb594c..a5bd60490b 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -459,6 +459,26 @@ fn outline_stroke_of_line() { assert!((area_of(&s, r[0]) - 1000.0).abs() < 1.0); } +#[test] +fn outline_stroke_preserves_a_zero_area_fill_without_retaining_a_live_stroke() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 60, "y2": 90})).unwrap(); + s.execute("paint.setFill", &json!({"color":"#ffffff"})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let children = n.children().expect("the original fill and the outlined stroke"); + assert_eq!(children.len(), 2); + assert!(children.iter().all(|n| n.appearance.stroke().is_none())); + assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)), "an invisible fill is not a live stroke"); + assert!(n.appearance.stroke().is_none()); + assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::BLACK))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(node(&s, result[0]).appearance.stroke().is_none()); +} + #[test] fn outline_stroke_with_fill_makes_group() { let mut s = session(); @@ -1076,6 +1096,207 @@ fn trim_merge_and_crop_remove_strokes() { } } +#[test] +fn outline_stroke_preserves_tiny_and_signed_area_canceling_closed_fills() { + for points in [vec![[0.0, 0.0], [100.0, 100.0], [0.0, 100.0], [100.0, 0.0]], vec![[0.0, 0.0], [1e-8, 0.0], [1e-8, 1e-8]]] { + let mut s = session(); + let anchors: Vec = points.into_iter().map(|[x, y]| json!({"x":x,"y":y})).collect(); + s.execute("path.create", &json!({"anchors":anchors,"closed":true})).unwrap(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let retains_fill = n.children().is_some_and(|ch| ch.iter().any(|c| c.appearance.fill_paint() == Paint::solid(Color::WHITE))) + || n.appearance.fill_paint() == Paint::solid(Color::WHITE); + assert!(retains_fill, "a real fill survives independently of its signed area or scale"); + } +} + +#[test] +fn outline_stroke_preserves_bent_open_fill_and_history() { + let mut s = session(); + s.execute("path.create", &json!({"anchors":[{"x":0,"y":0},{"x":60,"y":0},{"x":75,"y":-15},{"x":110,"y":-15}],"closed":false})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let children = n.children().expect("original fill beside the outlined stroke"); + assert_eq!(children.len(), 2); + let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + assert!(!fill.path_data().unwrap().subpaths[0].closed); + assert!(children.iter().all(|n| n.appearance.stroke().is_none())); + let after = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, after); +} + +#[test] +fn outline_stroke_mixed_contours_preserve_all_fill() { + use vectorcraft_geom::{Anchor, Point, SubPath}; + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.edit("mixed contours", |d, _| { + let n = d.node_mut(id).unwrap(); + if let NodeKind::Path { path, .. } = &mut n.kind { + path.subpaths.push(SubPath::new( + vec![Anchor::corner(Point::new(50.0, 0.0)), Anchor::corner(Point::new(80.0, 0.0)), Anchor::corner(Point::new(80.0, 20.0))], + false, + )); + } + Ok(()) + }) + .unwrap(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let outlined = node(&s, result[0]); + let children = outlined.children().unwrap(); + let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + let NodeKind::Path { path, .. } = &fill.kind else { panic!("fill is a path") }; + assert_eq!(path.subpaths.len(), 2); + assert!(path.subpaths[0].closed); + assert!(!path.subpaths[1].closed); +} + +#[test] +fn outline_stroke_keeps_closed_compound_members_editable() { + check_outlined_compound_members(false); +} + +#[test] +fn outline_stroke_keeps_open_compound_contours_and_members() { + check_outlined_compound_members(true); +} + +fn check_outlined_compound_members(mixed: bool) { + use vectorcraft_geom::{Anchor, Point, SubPath}; + let mut s = session(); + let outer = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + let inner = rect(&mut s, 35.0, 35.0, 30.0, 30.0); + let mut members = vec![outer.0, inner.0]; + if mixed { + let open = s.execute("path.create", &json!({"anchors":[{"x":140,"y":10},{"x":170,"y":30},{"x":140,"y":50}]})).unwrap(); + members.push(open["id"].as_u64().unwrap()); + s.edit("Mixed compound member", |d, _| { + let NodeKind::Path { path, .. } = &mut d.node_mut(inner).unwrap().kind else { panic!("path") }; + path.subpaths.push(SubPath::new(vec![Anchor::corner(Point::new(45.0, 80.0)), Anchor::corner(Point::new(70.0, 90.0))], false)); + Ok(()) + }) + .unwrap(); + } + s.execute("select.set", &json!({"ids":members})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Compound member names and rule", |d, _| { + d.node_mut(outer).unwrap().name = Some("outer-member".into()); + d.node_mut(inner).unwrap().name = Some("inner-member".into()); + let NodeKind::Compound { rule, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!("compound") }; + *rule = FillRule::EvenOdd; + Ok(()) + }) + .unwrap(); + let original = node(&s, compound); + let expected: Vec<_> = original + .children() + .unwrap() + .iter() + .map(|child| { + let path = child.path_data().unwrap().clone(); + (child.name.clone(), path) + }) + .collect(); + let before = s.doc().unwrap().doc.layers.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0]; + let group = node(&s, result); + let fill = group.children().unwrap().iter().find(|child| child.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + let NodeKind::Compound { children, rule } = &fill.kind else { panic!("closed fill must retain editable compound members") }; + assert_eq!(*rule, FillRule::EvenOdd); + assert_eq!(children.len(), if mixed { 3 } else { 2 }); + for (child, (name, path)) in children.iter().zip(expected) { + assert_eq!(child.name, name); + assert_eq!(child.path_data().unwrap(), &path); + assert_ne!(child.id, outer); + assert_ne!(child.id, inner); + } + let member = children[0].id; + let sibling = children[1].id; + let member_bounds = children[0].geometric_bounds().unwrap(); + let sibling_before = children[1].clone(); + let after = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, after); + // Group Selection can still address one retained child without moving its sibling. + s.execute("select.set", &json!({"ids":[member.0]})).unwrap(); + s.execute("object.move", &json!({"dx":7,"dy":3})).unwrap(); + assert!(close( + node(&s, member).geometric_bounds().unwrap(), + Rect::new(member_bounds.x0 + 7.0, member_bounds.y0 + 3.0, member_bounds.x1 + 7.0, member_bounds.y1 + 3.0), + 1e-6 + )); + assert_eq!(node(&s, sibling), *sibling_before); +} + +/// Exercise the real Group Selection pointer route, not select.set by id. +#[test] +fn outline_fill_and_stroke_move_independently_with_group_selection() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + for closed in [true, false] { + for move_fill in [false, true] { + for click_first in [false, true] { + let mut s = session(); + s.execute( + "path.create", + &json!({"anchors":[{"x":100,"y":100},{"x":200,"y":100},{"x":200,"y":200},{"x":100,"y":200}],"closed":closed}), + ) + .unwrap(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color":"#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight":10})).unwrap(); + let root = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0]; + let group = node(&s, root); + let children = group.children().expect("fill and outlined stroke stay separate"); + assert_eq!(children.len(), 2); + let fill = children.iter().find(|c| c.appearance.fill_paint().color().is_some_and(|c| c.to_hex() == "#ff0000")).unwrap().id; + let stroke = children.iter().find(|c| c.id != fill).unwrap().id; + group.walk(&mut |n| assert!(n.appearance.stroke().is_none(), "no retained live stroke")); + let moved = if move_fill { fill } else { stroke }; + let other = if move_fill { stroke } else { fill }; + let other_before = node(&s, other); + let bounds_before = bounds(&s, moved); + let layers_before_move = s.doc().unwrap().doc.layers.clone(); + let v = ViewInfo { smart_guides: false, snap_to_point: false, ..ViewInfo::default() }; + s.select_tool("groupSelection", v).unwrap(); + // Start empty, as clicking the art with Group Selection does after deselection. + s.execute("select.none", &json!({})).unwrap(); + let (x, y) = if move_fill { (150.0, 150.0) } else { (150.0, 100.0) }; + let compound_stroke = !move_fill && matches!(node(&s, stroke).kind, NodeKind::Compound { .. }); + for _ in 0..if compound_stroke { + 2 + } else if click_first { + 1 + } else { + 0 + } { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + } + for (kind, x, y) in [(PointerKind::Down, x, y), (PointerKind::Drag, x + 30.0, y + 15.0), (PointerKind::Up, x + 30.0, y + 15.0)] { + s.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } + assert_eq!(node(&s, other), other_before, "sibling unchanged: closed={closed}, fill={move_fill}, click_first={click_first}"); + let b = bounds(&s, moved); + assert!( + close(b, Rect::new(bounds_before.x0 + 30.0, bounds_before.y0 + 15.0, bounds_before.x1 + 30.0, bounds_before.y1 + 15.0), 1e-6), + "moved leaf: {b:?}" + ); + let layers_after_move = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, layers_before_move); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, layers_after_move); + } + } + } +} + /// #1590: an inset larger than the shape leaves nothing, and the error says so rather than asking /// for paths that are selected. #[test] diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 50a429d9e4..dcd1bd6a1b 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1126,8 +1126,8 @@ fn a_drag_from_a_fill_moves_only_the_selected_anchors_of_partly_selected_paths() } /// A path selected whole inside a selected group moves once, with the group, when the selection -/// also holds a direct-selected anchor: a Group Selection drag from the path's fill (which adds -/// the group) and an arrow key move both by 10 pt. +/// also holds a direct-selected anchor: a completed Group Selection click adds the group, then +/// a drag and an arrow key move both by 10 pt. A leaf drag before that click keeps its sibling still. #[test] fn a_path_in_a_selected_group_moves_once_with_selected_anchors() { use vectorcraft_tools::PointerKind::{Down, Drag, Up}; @@ -1142,7 +1142,14 @@ fn a_path_in_a_selected_group_moves_once_with_selected_anchors() { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]); - assert!(s.doc().unwrap().selection.contains(g), "the press added the group"); + assert!(!s.doc().unwrap().selection.contains(g), "the leaf drag keeps its selection"); + assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (160.0, 100.0), 310.0), "the leaf and selected anchor move"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + gesture(&mut s, v, &[(Down, 125.0, 125.0), (Up, 125.0, 125.0)]); + assert!(s.doc().unwrap().selection.contains(g), "the completed click added the group"); + gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]); assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (170.0, 100.0), 310.0), "the drag"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("select.set", &json!({"ids": [g.0, a.0]})).unwrap(); diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index f1b31671e4..c9bad6e60d 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -878,6 +878,31 @@ fn a_handle_drag_keeps_the_opposite_edge_of_the_offset_shape() { } } +#[test] +fn a_hover_checks_the_memo_as_often_however_many_objects_are_selected() { + let checks = |objects: u32| { + let mut s = session(); + for i in 0..objects { + rect(&mut s, f64::from(i), 1.0, 0.0); + } + run(&mut s, "select.all", json!({})); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + // Off the art, so the hover walks every selected object and finds no anchor or center. + let hover = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Move, 350.0, 350.0), v).unwrap(); + s.cursor(Point::new(350.0, 350.0), Mods::default(), v) + }; + hover(&mut s); + let before = s.preview_memo.checks(); + hover(&mut s); + s.preview_memo.checks() - before + }; + let few = checks(3); + assert!(few > 0, "a hover asks the memo"); + assert_eq!(checks(60), few, "a check compares the whole selection: one per object is quadratic"); +} + #[test] fn hovering_over_an_unchanged_document_measures_nothing_again() { // A selected square with Offset Path 10, drawn from 90 to 210, with Use Preview Bounds and Smart diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 9f607d78a3..dde0c4bf5f 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1645,6 +1645,173 @@ fn select_all_in_one_frame_selects_only_its_text_once_the_caret_moves() { assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": "x"})).is_err()); } +/// A story of bulleted paragraphs threaded from area type `a` into frame `b`, each frame holding +/// paragraph returns, with the Type tool editing `b` at its start. +fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, String) { + let mut s = session(); + let story = "Alpha beta.\n".repeat(12); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "bullet"})).unwrap(); + let (a, b) = (NodeId(a), NodeId(b)); + for id in [a, b] { + let t = obj(&s, id); + assert!(t.plain_text().contains('\n'), "frame {} holds paragraph returns", id.0); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list", id.0); + } + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + (s, a, b, story) +} + +#[test] +fn remove_breaks_takes_the_whole_story_that_select_all_selected() { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "every frame's returns go, each between words as a space"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); + assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n')); +} + +#[test] +fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + assert!(obj(&s, a).plain_text().ends_with('\n'), "the first frame ends with a paragraph return"); + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "the return at the end of the first frame becomes a space"); +} + +#[test] +fn remove_breaks_in_one_frames_selection_leaves_the_other_frames() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + let (in_a, b_len) = (obj(&s, a).plain_text(), obj(&s, b).plain_text().len()); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": b_len})); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(obj(&s, a).plain_text(), in_a, "the first frame keeps its returns"); + assert!(!obj(&s, b).plain_text().contains('\n'), "the edited frame's returns go"); +} + +#[test] +fn convert_to_text_takes_the_whole_story_that_select_all_selected() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("text.convertListToText", &json!({})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + for id in [a, b] { + let t = obj(&s, id); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none()), "frame {} leaves its list", id.0); + assert!(t.plain_text().contains("\u{2022}\t"), "frame {} holds its bullets as characters", id.0); + } + assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b] { + let t = obj(&s, id); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list again", id.0); + } +} + +#[test] +fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() { + // Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story. + for named in [false, true] { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("object.lock", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + // The first frame ends with a paragraph return, so the paragraph that starts the locked + // frame takes in the first frame's empty last part and starts its text there. + let in_a = obj(&s, a).plain_text(); + assert!(in_a.ends_with('\n')); + let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count(); + let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})"); + assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert"); + assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0))); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted"); + let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count(); + assert_eq!(markers, own, "the locked frame's first paragraph keeps its list"); + // The converted text is longer, so the story flows on into the locked frame; its own + // paragraphs stay a list. + let last = tb.paragraph_count() - 2; + assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})"); + assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n")); + assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); + } +} + +#[test] +fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() { + for named in [false, true] { + let mut s = session(); + let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40)); + let a = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let b = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 900})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap(); + let in_a = obj(&s, a).plain_text(); + assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second"); + s.execute("object.lock", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})"); + // The two paragraphs that start in the editable frame, and the empty one that ends the story. + assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert"); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was"); + assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list"); + assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list"); + assert!(!tb.plain_text().starts_with('\u{2022}')); + assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2); + } +} + +#[test] +fn convert_to_text_of_named_frames_ends_the_story_selection() { + let (mut s, _, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("text.convertListToText", &json!({"ids": [b.0]})).unwrap(); + assert!(obj(&s, b).plain_text().contains("\u{2022}\t")); + assert!(s.tool_options().get("story").is_none(), "the Type tool's selection moves past the characters inserted"); +} + +#[test] +fn convert_to_text_in_one_frame_leaves_the_other_frames() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + let in_a = obj(&s, a).plain_text(); + s.execute("text.convertListToText", &json!({})).unwrap(); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert_eq!(ta.plain_text(), in_a, "the first frame's text is as it was"); + assert!(ta.para_at(0).list.is_some(), "the first frame stays a list"); + assert!((0..tb.paragraph_count()).all(|k| tb.para_at(k).list.is_none()), "the edited frame leaves its list"); + assert!(tb.plain_text().contains("\u{2022}\t"), "the edited frame holds its bullets as characters"); +} + #[test] fn a_frame_dragged_with_the_type_tools_is_the_dragged_rectangle() { for tool in ["type", "verticalType"] { @@ -2823,9 +2990,11 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { let glyphs = vectorcraft_text::layout(db, &obj(&s, open)).glyphs; let fallback = db.face_by_id(glyphs[0].font_id).expect("the fallback face"); assert_ne!(fallback.id(), requested.id()); - let (ka, sign) = (fallback.glyph_for('क'), fallback.glyph_for('\u{93F}')); + let ka = fallback.glyph_for('क'); let drawn: Vec<_> = glyphs.iter().map(|g| (g.gid, g.byte)).collect(); - assert_eq!(drawn, [(sign, 0), (ka, 0)], "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY})", fallback.family); + // A face may draw the vowel sign with a glyph other than its own, so only its place is checked. + let sign_first = matches!(drawn[..], [(sign, 0), (k, 0)] if sign != 0 && sign != ka && k == ka); + assert!(sign_first, "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY}): {drawn:?}", fallback.family); let query = s.execute("text.glyphAlternates", &json!({"id": open.0, "start": 0})).unwrap(); assert_eq!(query["chosen"], json!(ka), "the fallback face's glyph for Ka"); @@ -2834,3 +3003,28 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { let query = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": 0})).unwrap(); assert_eq!(query["chosen"], json!(ka), "an overflowing Ka reports the fallback face's glyph for Ka"); } + +/// Apply Fill to Stroke with characters selected with the Type tool: only those characters take +/// a stroke of their own fill, as one undo step (#5530). +#[test] +fn apply_fill_to_stroke_with_characters_selected_changes_only_them() { + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + click(&mut s, 50.0, 300.0); + let id = s.doc().unwrap().selection.objects[0]; + s.tool_text("Sample Text", v).unwrap(); + // All of it red, then the first word green: a stroke on the rest would show. + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 6})); + s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + let t = obj(&s, id); + assert_eq!(t.runs[0].text, "Sample"); + assert_eq!(t.runs[0].style.stroke, t.runs[0].style.fill, "the selected characters take their fill as a stroke"); + assert!(t.runs[0].style.stroke_width > 0.0); + assert!(t.runs[1].style.stroke.is_none(), "the rest of the type keeps its stroke"); + let labels = undo_labels(&s); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke"))); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 18e8da3d59..66d84a925b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -154,6 +154,8 @@ impl Session { /// Direct Selection to the tools that edit anchors (the Pen) and Selection to the others. /// Cmd+Alt lends Group Selection while Direct Selection is active. Cmd still lends the last /// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract). + /// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the + /// object (#3901; ). /// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane. /// None for the other selection tools and the view tools. fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> { @@ -161,8 +163,8 @@ impl Session { if matches!(id, "hand" | "zoom" | "rotateView") { return None; } - if id == "directSelection" && mods.cmd && mods.alt { - return Some("groupSelection"); + if id == "directSelection" && mods.cmd { + return Some(if mods.alt { "groupSelection" } else { "selection" }); } if id == "perspectiveSelection" && mods.cmd && mods.alt { return None; @@ -173,6 +175,16 @@ impl Session { Some(self.last_selection_tool.unwrap_or(if edits_anchors(id) { "directSelection" } else { "selection" })) } + /// The selection tool a press with `mods` would borrow from the active tool + /// ([`Self::lend_selection_tool`]), as [`Self::cursor`] shows it: the canvas also shows what + /// that tool shows (Direct Selection with Cmd held shows the bounding box). + pub fn lent_tool_id(&self, mods: &Mods) -> Option<&'static str> { + if !mods.cmd || self.lender.is_some() { + return None; + } + self.lent_tool(self.tool.id(), mods) + } + /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, /// not Select Behind). The tool lent to stays as it was, unaware, until the release. diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b8b360b804..42970aa160 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -239,6 +239,10 @@ fn structured_junk() { ("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})), ("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})), ("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})), + ("addon.select.byLinkStatus", json!({"status": ["linked", "missing", null, 7, {"a": 1}], "ids": [2, u64::MAX, -1, "x", 1.5]})), + ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), + ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), + ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), ("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})), ("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})), ("object.transform", json!({"matrix": [1, 2, 3]})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index cbe713e444..46ca4a0781 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2763,6 +2763,10 @@ fn editing_text() -> String { "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceCMYK XN\n[ 4 0 0 4 10 30 ] 2 1 0 Xh\n[ 4 0 0 4 10 30 ] 0 0 2 1 2 1 8 4 1 0 0 0 4 4 0 0\n\ %%BeginData: 18\rXI\nff000000000000ff80ff\n%%EndData\nXH\n%AI5_EndRaster\nN" .into(), + // A 9 × 2 1-bit image mask (ImageMask 1) colorized by the global fill before it, in hex. + "0 0 0 1 (Black global) 0.4 0 Xk\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceGray XN\n[ 4 0 0 4 10 30 ] 9 2 0 Xh\n\ + [ 4 0 0 4 10 30 ] 0 0 9 2 9 2 1 1 0 0 0 1 4 4 0 0\n%%BeginData: 8\rXI\n6080ff00\n%%EndData\nXH\n%AI5_EndRaster\nN" + .into(), ] .join("\n"); let layer = |name: &str, visible: u8, body: &str| { @@ -2849,6 +2853,23 @@ fn the_editing_fixture_reads_its_cmyk_image_with_its_mask() { assert!(layers && found.contains(&(Some(vec![255, 0, 0, 0, 0, 0, 0, 255]), true)), "{found:?} {warnings:?}"); } +/// The fuzzed editing data, as it is, reads its 1-bit image mask as an image colorized with the +/// global color before it. +#[test] +fn the_editing_fixture_reads_its_image_mask_colorized() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat(); + let (doc, warnings, layers) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0); + let mut found = vec![]; + doc.visit_images(|n, im| { + if let Some(vectorcraft_color::Paint::Solid { swatch, .. }) = n.extras().colorize.as_deref() { + found.push((swatch.clone(), im.width, im.height, doc.images[&im.key].coverage().map(|c| c.2))); + } + }); + // Clear bits (black) show the color; set bits (white) are transparent. + let cover = vec![255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255]; + assert!(layers && found == [(Some("Black global".to_string()), 9, 2, Some(cover))], "{found:?} {warnings:?}"); +} + /// The text document of a story of centred type with two styles, as an editing copy keeps it. fn text_document_text() -> String { "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 3 4 ] >> >> >> ] >> >>\n\ @@ -3291,7 +3312,7 @@ proptest! { #[test] fn ai_line_widths_never_panic( width in prop::sample::select(vec!["0", "0.0", "-0", "-1", "1e308", "1e-308", "nan", "inf", "2"]), - render in prop::sample::select(vec!["0", "1", "2", "5", "6", "7", "-1", "99"]), + render in prop::sample::select(vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "4.5", "-1", "99"]), cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', 'w', 'B', 'S', 'T'])), 0..8), ) { @@ -3307,6 +3328,88 @@ proptest! { survive("hostile .ai line widths", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose pattern definition (a marked tile box, a gradient placed by `Bg`'s matrix) and + /// pattern fill are damaged or hostile. + #[test] + fn ai_pattern_definitions_never_panic( + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', 'n', 'E', 'p', 'B'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let gradient = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let pattern = "%AI3_BeginPattern: (P)\n(P) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n%_10 0 L\n%_10 -10 L\n%_0 -10 L\n%_0 0 L\n%_n\n\ + %_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n%_2 -2 m\n%_8 -2 L\n%_8 -8 L\n%_2 -8 L\n%_Bb\n\ + %_0.1 0.2 45 0.3 Bh\n%_1 (G) 0.1 0.2 0 1.5 3 0 0 3 0 0 1 Bg\n%_3 0 0 3 -8000 8000 Bm\n%_f\n%_0 BB\nE\n%AI3_EndPattern\n"; + let art = format!("(P) 0 0 1 1 0 0 0 0 0 [0.5 0.2 -0.2 0.5 3 -4] p\n{}f\n", ai::rect(20.0, 20.0, 80.0, 80.0)); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{gradient}{pattern}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai patterns", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose gradients and patterns have names with newlines (blank before one, several, + /// repeated, one shown like another's numbered name), used by fills and a palette, damaged or + /// hostile. + #[test] + fn ai_global_names_with_newlines_never_panic( + names in prop::collection::vec(prop::sample::select(vec!["Sky\\n1", "Sky\\n2", "Sky", "Sky 2", "\\n3", "\\n", "Sky\\n\\n1", "\\012x"]), 1..6), + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['\\', 'n', '(', ')', ' ', '\n', 'B', 'p', 'E', '%'])), 0..10), + ) { + use vectorcraft_testkit::ai; + let mut setup = String::new(); + let mut art = String::new(); + let mut cells = String::new(); + for name in &names { + setup.push_str(&format!( + "%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\ + %AI3_BeginPattern: ({name})\n({name}) 0 0 6 6\n%_0 A\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_0 0 0 1 k\n%_f\nE\n%AI3_EndPattern\n" + )); + art.push_str(&format!("Bb\n1 ({name}) 0 0 0 50 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", ai::rect(10.0, 10.0, 40.0, 40.0))); + art.push_str(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", ai::rect(50.0, 50.0, 90.0, 90.0))); + cells.push_str(&format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\n")); + } + setup.push_str(&format!("%AI5_BeginPalette\n0 0 Pb\n{cells}PB\n%AI5_EndPalette\n")); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{setup}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai global names", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose images (binary samples with an alpha channel, the operators that end a raster, + /// then a name and an opacity mask) and placed file (an empty relative folder, a preview) are + /// damaged or hostile, bytes of the samples included. + #[test] + fn ai_images_and_placed_files_never_panic( + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec![b'0', b'1', b'9', b' ', b'\r', b'\n', b'(', b')', b'[', b']', b'%', b'_', b'N', b'X', b'~', 0u8, 255u8])), 0..12), + ) { + use vectorcraft_testkit::ai; + let raster = "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 2 1 0 Xh\n[10 0 0 10 20 -30] 0 0 2 1 2 1 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 10\nXI\n@@%%EndData\nXH\n\ + %AI17_Begin_Content_if_version_gt:24 17\n72 72 Xr\n%AI17_End_Versioned_Content\n%AI5_EndRaster\nN\n\ + %_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_0 0 m\n%_5 0 l\n%_5 -5 l\n%_f\n%_X+\n%_ (Art) ,\n%_; (AI9_Mask) ,\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + let place = "%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -8000 8000] 8000 8000 8002 8001 4 4 0\n(/tmp/p.png)`\n%%IncludeFile:/tmp/p.png\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n()\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n\ + %AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n2 1 8 32 17 @@\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"; + let text = ai::editing_data(100.0, 100.0, &ai::layer("L", &format!("{raster}{place}"))); + let samples: &[u8] = &[255, 0, 0, 0, 0, 255, 128, 0]; + let preview: &[u8] = &[255, 255, 0, 0, 0, 0, 0, 0]; + let mut data = Vec::new(); + for (i, part) in text.split("@@").enumerate() { + if i > 0 { + data.extend_from_slice(if i == 1 { samples } else { preview }); + } + data.extend_from_slice(part.as_bytes()); + } + for &(i, b) in &edits { + let n = data.len(); + if n > 0 { + data[i % n] = b; + } + } + data.truncate(cut.min(data.len())); + let private = [b"%AI24_ZStandard_Data".as_slice(), &ruzstd::encoding::compress_to_vec(data.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)].concat(); + survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + /// A `.ai` whose variable library is damaged or hostile: the library is counted for the warning /// whether the layers are read or not (an inserted `Z` can make an operator the reader doesn't /// handle, and then the layers aren't read). @@ -3420,6 +3523,7 @@ proptest! { ], 0..12), ended in any::(), objects in prop::collection::vec((prop_oneof![arb_num(), prop::sample::select(vec!["1".to_string(), "6".into(), "9".into()])], prop::sample::select(vec!["A", "B", "", "Caf\u{e9}", "Missing"]), any::()), 0..6), + unit in prop::sample::select(vec![1.0, 2.0, 0.0, -1.0, f64::NAN, f64::INFINITY]), ) { use vectorcraft_testkit::ai; let style = |name: &str| { @@ -3448,6 +3552,11 @@ proptest! { survive("style lists and links", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; let eps = ai::eps(data.as_bytes(), ai::page_ps()); survive("style lists and links in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + // A graphic style library: the styles and their list, no layers. + let library = ai::editing_data(200.0, 100.0, &header); + survive("style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, unit).0))?; + let eps = ai::eps(library.as_bytes(), ai::page_ps()); + survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; } /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of @@ -3512,6 +3621,114 @@ proptest! { Some(d) })?; } + + /// A `.ai` whose symbols are damaged or hostile: their definitions, the symbol list and the + /// instances (on the page and in a symbol's art), cut short or edited. + #[test] + fn ai_symbols_never_panic(cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', 'u', 'U', 'A', 'Z'])), 0..12)) { + let text = mutate_text(&symbols_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } +} + +/// Editing data with two symbols (S2's art holds an instance of S1), the symbol list and a layer of +/// instances, as the format writes them. +fn symbols_text() -> String { + use vectorcraft_testkit::ai; + let def = |name: &str, art: &str, reg: u32| { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{reg} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) + }; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{m} /RTransformMatrix\n;\n9 () XW\n"); + let defs = def("S1", "0 1 1 0 1 0 0 Xa\n-2 -2 m\n2 -2 L\n2 2 L\n-2 2 L\nf\n", 5) + &def("S2", &inst("S1", "1 0 0 -1 -8081 8237"), 1); + let list = "%AI24_BeginSymbolList\n(S2)\n(S1)\n%AI24_EndSymbolList\n"; + let page = ai::layer( + "L", + &format!( + "1 Xw\n{}0 Xw\n{}1 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}10 10 m\n30 10 L\n30 30 L\nh\nW\nn\nQ\n", + inst("S1", "1 0 0 -1 20 50"), + inst("S2", "2 0 0 -2 100 50"), + inst("S1", "1 0 0 -1 20 20") + ), + ); + let data = ai::editing_data( + 200.0, + 100.0, + &format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n%AI5_Begin_NonPrinting\n{list}%AI5_End_NonPrinting--\n{page}"), + ); + data.replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1) +} + +/// The data [`ai_symbols_never_panic`] damages, as it is, opens with its symbols and instances live. +#[test] +fn the_symbols_fuzz_data_opens_live() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&symbols_text())].concat(); + let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["S2", "S1"]); + let mut instances = 0; + doc.walk(|n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 3); +} + +/// Symbols the reader must stop at: sections that don't end, references and matrices it can't +/// use, definitions nested deeper than it reads, and symbols that hold each other. +#[test] +fn ai_symbol_limits_never_panic() { + use vectorcraft_testkit::ai; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n{name} /SymbolRef ,\n{m} /RTransformMatrix\n;\n"); + let def = |name: &str, art: &str| format!("%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%AI10_EndSymbol\n"); + let mut nested = String::new(); + for i in 0..400 { + nested.push_str(&format!("%AI14_BeginSymbol\n(N{i})\n0 Ae\nu\n")); + } + for _ in 0..400 { + nested.push_str("U\n%AI10_EndSymbol\n"); + } + let mut chain = String::new(); + for i in 0..300 { + chain.push_str(&def(&format!("C{i}"), &inst(&format!("(C{})", i + 1), "1 0 0 -1 0 0"))); + } + let cases = [ + format!("%AI14_BeginSymbol\n(Open)\n0 Ae\nu\n{}", ai::layer("L", &inst("(Open)", "1 0 0 -1 20 50"))), + format!("%AI24_BeginSymbolList\n(A)\n(B)\n{}", ai::layer("L", "")), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer("L", &(inst("", "1 0 0 -1 20 50") + &inst("/SymbolRef", "1 0 0 -1 20 50") + &inst("(S)", ""))) + ), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer( + "L", + &(inst("(S)", "1 0 0") + &inst("(S)", "1 0 0 -1 20 50 7") + &inst("(S)", "1e400 0 0 -1 20 50") + &inst("(S)", "0 0 0 0 20 50")) + ) + ), + format!("{nested}{}", ai::layer("L", &inst("(N0)", "1 0 0 -1 20 50"))), + format!("{chain}{}", ai::layer("L", &inst("(C0)", "1 0 0 -1 20 50"))), + format!( + "{}{}{}", + def("S1", &inst("(S2)", "1 0 0 -1 0 0")), + def("S2", &inst("(S1)", "1 0 0 -1 0 0")), + ai::layer("L", &inst("(S1)", "1 0 0 -1 20 50")) + ), + format!("{}{}", def("S1", &inst("(S2)", "1 0 0 -1 0 0")), def("S2", &inst("(S1)", "1 0 0 -1 0 0"))), + ]; + for body in cases { + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0)) + .unwrap(); + survive("hostile .ai symbols, trusted", || { + Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0) + }) + .unwrap(); + } } /// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group. @@ -3657,6 +3874,19 @@ proptest! { let text = mutate_text(&fixture, cut, &edits); survive("mutated PostScript-form .ai with placed files", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; } + + /// The same file with linked images in the version 7 form (`XG`, then `XF` with no samples), + /// one with an embedded image between its `XG` and `XF`, damaged. + #[test] + fn ps_form_ai_with_linked_images_never_panics(cut in 0usize..1_400, edits in prop::collection::vec((0usize..1_400, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', 'X', 'F', 'G'])), 0..12)) { + let linked = "%AI5_File:\n%AI5_BeginRaster\n(a.tif) 0 XG\n[ 2 0 0 3 10 80 ] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n\ + %AI5_File:\n%AI5_BeginRaster\n(b.tif) 1 XG\n[ 1 0 0 1 0 100 ] 0 0 1 1 1 1 8 3 0 0 0 0 XI\n%FF0000\n%AI5_EndRaster\n\ + [ 0 1 -1 0 50 50 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n"; + let fixture = NAMED_PROLOG_AI.replacen("0 Ap\nu\n", &format!("0 Ap\n{linked}u\n"), 1); + prop_assert!(fixture.contains("(a.tif)")); + let text = mutate_text(&fixture, cut, &edits); + survive("mutated PostScript-form .ai with linked images", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } } /// A `.ai` in the legacy format without layers (Illustrator 3) whose prolog is included: its @@ -3722,6 +3952,47 @@ proptest! { } } +/// Area type in the version 7 form (§15.5.3) whose story flows through two linked areas: a small +/// one, and one a quarter turn round, each area's characters after its `TP`. +const LINKED_AREAS: &str = "1 To\n1 0 0 1 120 90 0 Tp\n120 60 m\n120 90 L\n180 90 L\n180 60 L\n120 60 L\nn\nTP\n0 Tr\n0 g\n/_Helvetica 9 Tf\n\ + (one two three four five six seven eight nine ten ) Tx\n0 1 -1 0 190 10 0 Tp\n130 10 m\n130 55 L\n190 55 L\n190 10 L\n130 10 L\nn\nTP\n\ + (eleven twelve thirteen fourteen fifteen) Tx\n(\\r) TX\nTO\n"; + +/// [`NAMED_PROLOG_AI`] with `text` on its layer. +fn linked_areas_ai(text: &str) -> String { + NAMED_PROLOG_AI.replace("u\n0.5 g\n", &format!("{text}u\n0.5 g\n")) +} + +/// The fixture, as it is, opens with its area type as two threaded frames, the story flowing from +/// the first into the second. +#[test] +fn the_linked_areas_fixture_opens_as_threaded_frames() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", linked_areas_ai(LINKED_AREAS).as_bytes()).unwrap(); + let [thread] = &l.doc.text_threads[..] else { panic!("one thread: {:?} {:?}", l.doc.text_threads, l.warnings) }; + let texts: Vec = thread + .iter() + .map(|id| match &l.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + k => panic!("type: {k:?}"), + }) + .collect(); + let [first, second] = texts.as_slice() else { panic!("two frames: {texts:?}") }; + assert!(!first.is_empty() && !second.is_empty(), "the story flows on into the second frame: {texts:?}"); + assert_eq!(format!("{first}{second}"), "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen"); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its linked areas damaged (their text paths, frames and characters): read, or + /// refused. + #[test] + fn ps_form_ai_linked_areas_never_panic(cut in 0usize..400, edits in prop::collection::vec((0usize..400, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '\\', 'T', 'p', 'P', 'O', 'o', 'x', 'X', 'm', 'L', 'n'])), 0..12)) { + let text = linked_areas_ai(&mutate_text(LINKED_AREAS, cut, &edits)); + survive("PostScript-form .ai with damaged linked areas", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + /// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or /// anything else. fn arb_layer_operand() -> impl Strategy { @@ -3784,6 +4055,12 @@ fn arb_ai_token() -> impl Strategy { "*U", "q", "Q", + // Several clipping paths in one clipping group or layer clip to their intersection (AI7 spec §5.6.2), each + // nesting a clipping group. + "0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W f", + "q 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n 0 0 m 5 5 L 0 5 L f Q", + "u 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n U", + "q 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n", "LB", "Lb", "Ln", @@ -3816,6 +4093,12 @@ fn arb_ai_token() -> impl Strategy { "\n%AI3_Note:\n", "\n%AI5_NoteMore:more\n", "\n%%Note:old\n", + // Object tags (version 7 §7). + "XT", + "/AdobeURL (https://example.com) XT", + "/tag () XT", + "/ (x) XT", + "(x) (y) XT", "w", "J", "j", @@ -3854,6 +4137,12 @@ fn arb_ai_token() -> impl Strategy { "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 3 2 3 2 1 4 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 99999 99999 99999 99999 1 1 0 0 0 0", + // A linked image in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF`. + "XG", + "(a.tif) 0 XG", + "XF", + "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 0 0 0 0 XF", + "[ 1e308 0 0 1e308 0 0 ] 0 0 1e6 1e6 1e6 1e6 8 3 0 0 0 0 XF", "[", "]", "/Name", @@ -3906,7 +4195,17 @@ fn arb_ai_token() -> impl Strategy { "(\\r) TX", "() Tj", "(x) Tx", + "(\\t) 1 TS", + "() /x TS", + "Te", + "0 0 1e308 -1e308 Te", + "TM", "7 Tr", + "4 Tr", + "9 Tr", + "4.5 Tr", + "*w", + "*W", "-1e308 Ts", "1e308 0 Tz", "1e308 Tt", @@ -3922,10 +4221,23 @@ fn arb_ai_token() -> impl Strategy { "7 Tq", "1 1 1e308 -1e308 4e9 Th", "1 1 (2) 3 4 Th", + "36 2 Xb", + "Xb", + "0 0 4 1e308 Xe", + "0 0 2 -1e308 Xe", + "0 0 3 72 Xe", + "0 0 1e308 72 Xe", + "(x) /y Xe", + "XB", "[39/quotesingle 128/Euro/eacute/nosuch 300/x TE", "[1e308/a -1/b TE", "\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n", "\n%AI3_BeginEncoding:\n", + "[ 39/quotesingle 1e308/a -1/b 200/eacute\n/_Helvetica/Helvetica 0 0 1 [0.5 1e308] TZ", + "/_ 0 TZ", + "[ ] ] [ /a /b (c) TZ", + "\n%AI3_EndEncoding AdobeType\n", + "\n%%BeginEncoding: _x x\n[ 39/grave\n/_x/x 0 1 TZ\n%%EndEncoding\n", "800 Ar", "frobnicate", "\n%AI5_BeginLayer\n", @@ -4125,6 +4437,15 @@ fn arb_ai_token() -> impl Strategy { "\n%\n", "\n%AI5_EndPlace\n", "\n%%PageTrailer\n", + "\n%AI14_BeginSymbol\n(S1)\n0 A 0 Xw 0 Ae\n", + "\n%AI10_EndSymbol\n", + "\n%AI24_BeginSymbolList\n(S1)\n", + "\n%AI24_EndSymbolList\n", + "/SymbolInstance :", + "(S1) /SymbolRef ,", + "/RTransformMatrix", + "5 /Int (AI13PatternRegistrationType) ,", + "; (AI19SymbolAppearanceMap) ,", ]) .prop_map(str::to_string), ] @@ -4343,8 +4664,9 @@ proptest! { /// Art styles with a Distort & Transform effect (Transform, Free Distort, Pucker & Bloat, Roughen, /// Tweak, Twist, Zig Zag) whose dictionary holds any of its entries, and unknown ones, as any kind, - /// with any value (huge, tiny, not a number, a string), repeated or left out, on a path and on type, - /// on the whole object or on its fill. + /// with any value (huge, tiny, not a number, a string), repeated or left out, on a path, on type and + /// on a group nested any number of levels around a curved path, stroked or not, on the whole object + /// or on its fill. #[test] fn ai_distort_effects_never_panic( name in prop::sample::select(vec![ @@ -4371,6 +4693,8 @@ proptest! { ], ), 0..24), on_fill in any::(), + depth in 0usize..300, + stroked in any::(), ) { use vectorcraft_testkit::ai; let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); @@ -4385,10 +4709,15 @@ proptest! { }; let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n"); let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let paint = if stroked { "0 0 1 0 K\n2 w\nB\n" } else { "f\n" }; + let curve = format!("0 0 1 0 k\n20 70 m\n20 90 80 90 80 70 c\n80 50 20 50 20 70 c\n{paint}"); + let nested = format!("0 Ae\n{}{curve}{}", "u\n".repeat(depth + 1), "U\n".repeat(depth + 1)).replace('\n', "\n%_"); let art = format!( - "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n\ + 0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{nested}1 (Fx) XW\n", ai::rect(20.0, 20.0, 80.0, 60.0), - ai::rect(100.0, 20.0, 180.0, 60.0) + ai::rect(100.0, 20.0, 180.0, 60.0), + ai::rect(20.0, 50.0, 80.0, 90.0) ); let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); survive("distort art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index 50a6fbd86d..3b7fb79e94 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -202,3 +202,24 @@ fn cut_direct_selected_anchors_retains_anchor_deletion() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3); assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c)); } + +#[test] +fn clear_explicit_ids_preserves_unrelated_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r1 = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + let r2 = NodeId(s.execute("shape.rectangle", &json!({"x": 50, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [r1.0, r2.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![r1, r2]); + + // Clearing r1 explicitly should remove r1 from doc and from selection, keeping r2 selected. + s.execute("edit.clear", &json!({"ids": [r1.0]})).unwrap(); + assert!(s.active().unwrap().doc.node(r1).is_none()); + assert!(s.active().unwrap().doc.node(r2).is_some()); + assert_eq!(s.active().unwrap().selection.objects, vec![r2]); + + // Parameterless clear clears the rest of the selection. + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(r2).is_none()); + assert!(s.active().unwrap().selection.is_empty()); +} diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs new file mode 100644 index 0000000000..d34b342934 --- /dev/null +++ b/crates/engine/tests/it/copy_direct_selection.rs @@ -0,0 +1,806 @@ +//! Direct-selection Copy and Cut tests (#2122). + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::FillRule; +use vectorcraft_testkit::invariants::check_session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()) +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 of the rectangle. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_none(), "extracted partial path must not retain live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_and_paste_direct_selected_adjacent_anchors_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 0 and 1. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_single_anchor_of_rect_copies_three_anchors_with_two_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select only anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + // Copying a single anchor on a closed path copies the anchor and both its incident segments. + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.segment_count(), 2); +} + +#[test] +fn copy_disjoint_segments_does_not_copy_unselected_segment_in_between() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Rectangle has 4 segments (0, 1, 2, 3). Select disjoint segments 0 and 2. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + // Two separate open path pieces should be created, each with 2 anchors. + assert_eq!(ids.len(), 2); + for id in ids { + let node = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + } +} + +#[test] +fn cut_direct_selected_segment_cuts_source_and_pastes_segment() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 and cut it. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.cut", json!({})); + + // Source rectangle should now have segment 0 removed, turning it into an open path. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed); + + // Paste the cut segment: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let pasted_path = pasted_node.path_data().unwrap(); + assert_eq!(pasted_path.subpaths.len(), 1); + assert!(!pasted_path.subpaths[0].closed); + assert_eq!(pasted_path.subpaths[0].anchors.len(), 2); +} + +#[test] +fn copy_compound_path_direct_selected_segment_inherits_appearance() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + + // Select segment 0 of the inner member. + run(&mut s, "select.segments", json!({"id": inner.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let compound_node = s.doc().unwrap().doc.node(compound).unwrap(); + assert_eq!(pasted_node.appearance, compound_node.appearance); +} + +#[test] +fn direct_selection_copy_preserves_fill_rule_and_attributes() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + run(&mut s, "path.setFillRule", json!({"rule": "evenOdd"})); + + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + assert!(matches!(pasted_node.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. })); +} + +#[test] +fn pen_tool_drawing_copies_whole_path_not_single_anchor() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Start drawing with Pen tool + s.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 50})); + + // Pen tool has the last anchor in sel.anchors, but active tool is pen + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + // The whole 3-point path must be copied, not just the last anchor! + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 1 and 2 of the 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Cut placed 1 segment on the clipboard (anchors 1 to 2). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].segment_count(), 1); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + + // Remaining source path must have the remaining 3 segments (segments 0, 2, 3), not 1. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths[0].segment_count(), 3); + assert_eq!(src_path.subpaths[0].anchors.len(), 4); + assert!(!src_path.subpaths[0].closed); + + // Sum of segments in clipboard + remaining = 1 + 3 = 4 (the original 4 segments). + assert_eq!(clip_path.subpaths[0].segment_count() + src_path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_rect_copies_full_object() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select non-adjacent anchors 1 and 3 of the 4-anchor rectangle. + // Incident segments for anchor 1 are segments 0 and 1; for anchor 3 are segments 2 and 3. + // Together they cover all 4 segments, so the path is copied whole. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "copying all segments keeps live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert!(path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_five_point_path_extracts_selected_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 50})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 30, "y": 80})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 10, "y": 50})); + run(&mut s, "path.close", json!({"id": id.0})); + + // Path has 5 anchors (0..4) and 5 segments (0..4). + // Select non-adjacent anchors 1 and 3. + // Anchor 1 gives segments 0, 1. Anchor 3 gives segments 2, 3. Segment 4 is unselected. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); + assert_eq!(path.subpaths[0].anchors.len(), 5); +} + +#[test] +fn copy_when_all_segments_selected_preserves_live_shape() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select all 4 segments explicitly (like Select > Object > Direction Handles). + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 1], [0, 2], [0, 3]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "all segments selected preserves live shape"); + } +} + +#[test] +fn compound_member_selected_whole_with_direct_selection_promotes_member() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = rect(&mut s, 120.0, 10.0, 50.0, 50.0); + + // Select outer compound member whole, and direct-select anchor 0 on standalone. + let outer_anchors: Vec> = (0..4).map(|i| vec![0, i]).collect(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + // outer is selected whole, standalone is partially selected. + assert!(s.active().unwrap().selection.partial(outer).is_none()); + assert!(s.active().unwrap().selection.partial(standalone).is_some()); + + run(&mut s, "edit.copy", json!({})); + // Clipboard should have: + // 1. The compound path (outer promoted to compound #786) + // 2. The extracted segment piece from standalone + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); +} + +#[test] +fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_piece() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = NodeId(run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + + let outer_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + run(&mut s, "edit.cut", json!({})); + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); + + // Compound was removed because member was selected whole + let doc = &s.doc().unwrap().doc; + assert!(doc.node(compound).is_none(), "compound path must be removed on cut"); + // Standalone has cut pieces remaining + assert!(doc.node(standalone).is_some(), "partially cut standalone path remains"); +} + +#[test] +fn cut_direct_selected_only_path_in_layer_preserves_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Create a new layer + let layer_id = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + // Create a path inside the layer + let rect = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(rect), Some(layer_id)); + + // Direct-select all 4 anchors of rect and cut + let all_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run(&mut s, "select.anchors", json!({"id": rect.0, "anchors": all_anchors, "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // The rect was cut, but the layer must NOT be deleted + let doc = &s.doc().unwrap().doc; + assert!(doc.node(rect).is_none(), "rect was cut"); + assert!(doc.node(layer_id).is_some(), "layer must remain even when empty"); + assert_eq!(doc.node(layer_id).unwrap().children().unwrap().len(), 0); +} + +#[test] +fn copy_and_paste_path_in_compound_path_isolation_adds_member_to_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // In isolation mode, select member `inner` whole. + run(&mut s, "select.set", json!({"ids": [inner.0]})); + run(&mut s, "edit.copy", json!({})); + + // Clipboard copies the selected member path, NOT the entire compound path. + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].id, inner); + + // Paste in isolation mode: the pasted path must be inserted into the compound path, + // not as a new path beside the compound path. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "pasted path must be added to the compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3, "compound path now has 3 member paths"); +} + +#[test] +fn cut_and_paste_direct_selected_anchors_in_compound_path_isolation() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Direct-select anchor 0 of `inner` and cut. + run(&mut s, "select.anchors", json!({"id": inner.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Clipboard holds the cut segment piece. + assert_eq!(s.clipboard.nodes.len(), 1); + + // Paste inside isolation mode: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "cut and pasted anchors must be inserted into compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3); + check_session(&s).unwrap(); +} + +#[test] +fn paste_non_path_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let a = rect(&mut s, 10.0, 10.0, 40.0, 40.0); + let b = rect(&mut s, 60.0, 10.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let _group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + + // Copy the group to the clipboard. + run(&mut s, "edit.copy", json!({})); + + // Create a compound path on the layer. + let c1 = rect(&mut s, 10.0, 100.0, 80.0, 80.0); + let c2 = rect(&mut s, 30.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [c1.0, c2.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let layer_id = s.doc().unwrap().doc.parent_of(compound).unwrap(); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // Generic insertion parent inside compound isolation resolves to the layer, not the compound. + assert_eq!(s.doc().unwrap().insertion_parent(), Some(layer_id)); + + // Paste the group while in compound path isolation. + // The group cannot be inserted into the compound path; it must be pasted into the layer beside the compound. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_group = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_group), Some(layer_id), "pasted group must be added to layer, not compound"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path must keep only its 2 path children"); + + // All document invariants (including compound children being paths only) must hold. + check_session(&s).unwrap(); +} + +#[test] +fn shape_creation_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = rect(&mut s, 10.0, 10.0, 80.0, 80.0); + let inner = rect(&mut s, 30.0, 30.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Draw a new rectangle while isolating the compound path. + let new_rect = rect(&mut s, 40.0, 40.0, 20.0, 20.0); + + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(new_rect), Some(compound), "new shape path is placed outside compound path in layer"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path maintains original member paths"); + + check_session(&s).unwrap(); +} + +#[test] +fn paste_compound_into_isolated_compound_preserves_child_order() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 300})); + let r1 = rect(&mut s, 10.0, 10.0, 10.0, 10.0); + let r2 = rect(&mut s, 30.0, 10.0, 10.0, 10.0); + let r3 = rect(&mut s, 50.0, 10.0, 10.0, 10.0); + run(&mut s, "select.set", json!({"ids": [r1.0, r2.0, r3.0]})); + let src_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Copy src_compound (contains [r1, r2, r3] in order) + run(&mut s, "select.set", json!({"ids": [src_compound.0]})); + run(&mut s, "edit.copy", json!({})); + + // Create target compound + let t1 = rect(&mut s, 100.0, 100.0, 80.0, 80.0); + let t2 = rect(&mut s, 120.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [t1.0, t2.0]})); + let target_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate target compound and select member t1 so paste-in-front targets index 1 + run(&mut s, "object.isolate", json!({"id": target_compound.0})); + run(&mut s, "select.set", json!({"ids": [t1.0]})); + + // Paste in front of t1 + let pasted = run(&mut s, "edit.pasteInFront", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 3, "unpacked all 3 children"); + + let doc = &s.doc().unwrap().doc; + let target_node = doc.node(target_compound).unwrap(); + let children = target_node.children().unwrap(); + assert_eq!(children.len(), 5); + + // Verify the 3 pasted children appear in children in exact forward order [r1_copy, r2_copy, r3_copy] + let child_ids: Vec = children.iter().map(|c| c.id.0).collect(); + let pos0 = child_ids.iter().position(|&id| id == ids[0]).unwrap(); + let pos1 = child_ids.iter().position(|&id| id == ids[1]).unwrap(); + let pos2 = child_ids.iter().position(|&id| id == ids[2]).unwrap(); + assert_eq!(pos1, pos0 + 1, "child 1 must immediately follow child 0"); + assert_eq!(pos2, pos1 + 1, "child 2 must immediately follow child 1"); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_open_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 20})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 100, "y": 80})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4.0})); + + // Select segment 0 of the open path (from (10, 20) to (60, 20)). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + + // Paste in place: position and appearance must be preserved. + let pasted = run(&mut s, "edit.pasteInPlace", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(pasted_node.appearance, src_node.appearance, "appearance (stroke & fill) must match source"); + + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.segment_count(), 1); + assert_eq!(sp.anchors.len(), 2); + assert_eq!(sp.anchors[0].p.x, 10.0); + assert_eq!(sp.anchors[0].p.y, 20.0); + assert_eq!(sp.anchors[1].p.x, 60.0); + assert_eq!(sp.anchors[1].p.y, 20.0); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_two_non_adjacent_segments_of_open_path_pastes_two_paths() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 40, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 120, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 160, "y": 10})); + + // Path has 5 anchors (0..4) and 4 segments (0..3). + // Select disjoint/non-adjacent segments 0 and 2. + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 2, "two non-adjacent segments paste as two independent paths"); + + for node_id in ids { + let node = s.doc().unwrap().doc.node(NodeId(node_id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 1); + assert_eq!(path.subpaths[0].anchors.len(), 2); + } + + check_session(&s).unwrap(); +} + +#[test] +fn copy_all_anchors_of_open_path_copies_whole_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 40})); + + // Select all 3 anchors. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 2); + assert_eq!(path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_single_anchor_on_open_path_and_lone_point_states_what_is_pasted() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + + // 1. Single interior anchor of an open path: + // Path: (10, 10) -> (50, 10) -> (90, 50). + // Selecting interior anchor 1 selects both incident segments (0 and 1). + // Stated behavior: pasting pastes an open path containing the anchor and both its incident segments (3 anchors, 2 segments). + let p1 = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 90, "y": 50})); + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted1 = run(&mut s, "edit.paste", json!({})); + let ids1: Vec = pasted1["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids1.len(), 1); + let path1 = s.doc().unwrap().doc.node(NodeId(ids1[0])).unwrap().path_data().unwrap(); + assert!(!path1.subpaths[0].closed); + assert_eq!(path1.subpaths[0].anchors.len(), 3); + assert_eq!(path1.subpaths[0].segment_count(), 2); + + // 2. Single endpoint anchor of an open path: + // Selecting endpoint anchor 0 selects its single incident segment (segment 0). + // Stated behavior: pasting pastes an open path for that segment (2 anchors, 1 segment). + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted2 = run(&mut s, "edit.paste", json!({})); + let ids2: Vec = pasted2["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids2.len(), 1); + let path2 = s.doc().unwrap().doc.node(NodeId(ids2[0])).unwrap().path_data().unwrap(); + assert!(!path2.subpaths[0].closed); + assert_eq!(path2.subpaths[0].anchors.len(), 2); + assert_eq!(path2.subpaths[0].segment_count(), 1); + + // 3. A lone point path (a path with only 1 anchor and 0 segments): + // Selecting the lone anchor on a single-point path copies the object whole. + // Stated behavior: pasting pastes a standalone lone-point path (1 anchor, 0 segments). + let p_lone = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 100, "y": 100}]}))["id"].as_u64().unwrap()); + run(&mut s, "select.anchors", json!({"id": p_lone.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted_lone = run(&mut s, "edit.paste", json!({})); + let ids_lone: Vec = pasted_lone["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids_lone.len(), 1); + let path_lone = s.doc().unwrap().doc.node(NodeId(ids_lone[0])).unwrap().path_data().unwrap(); + assert_eq!(path_lone.subpaths[0].anchors.len(), 1); + assert_eq!(path_lone.subpaths[0].segment_count(), 0); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_anchor_of_closed_path_opens_it_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the anchor. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source rectangle opens: 1 open subpath with 3 anchors remaining. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed, "cutting anchor of closed path opens the path"); + assert_eq!(src_path.subpaths[0].anchors.len(), 3); + assert_eq!(src_path.subpaths[0].segment_count(), 2); + + // Clipboard holds the cut portion (the anchor and its two incident segments: 3 anchors). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert!(!clip_path.subpaths[0].closed); + assert_eq!(clip_path.subpaths[0].anchors.len(), 3); + assert_eq!(clip_path.subpaths[0].segment_count(), 2); + + // Verify undo restores the closed path in one step. + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(r).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1); + assert!(restored_path.subpaths[0].closed, "undo restores closed path"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4); + assert_eq!(restored_path.subpaths[0].segment_count(), 4); + + // Verify redo re-applies the cut. + run(&mut s, "edit.redo", json!({})); + let redone_node = s.doc().unwrap().doc.node(r).unwrap(); + let redone_path = redone_node.path_data().unwrap(); + assert!(!redone_path.subpaths[0].closed); + assert_eq!(redone_path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 90, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 130, "y": 10})); + + // Open path has 4 anchors (0, 1, 2, 3) and 3 segments (0, 1, 2). + // Direct-select middle segment 1 (between anchor 1 and 2). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 1]]})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the middle segment. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source path should now be split into two surviving open runs. + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 2, "two open paths/subpaths remain after cutting middle segment"); + assert!(!src_path.subpaths[0].closed); + assert_eq!(src_path.subpaths[0].anchors.len(), 2); + assert_eq!(src_path.subpaths[0].anchors[0].p.x, 10.0); + assert_eq!(src_path.subpaths[0].anchors[1].p.x, 50.0); + + assert!(!src_path.subpaths[1].closed); + assert_eq!(src_path.subpaths[1].anchors.len(), 2); + assert_eq!(src_path.subpaths[1].anchors[0].p.x, 90.0); + assert_eq!(src_path.subpaths[1].anchors[1].p.x, 130.0); + + // Clipboard holds the cut middle segment: + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + assert_eq!(clip_path.subpaths[0].anchors[0].p.x, 50.0); + assert_eq!(clip_path.subpaths[0].anchors[1].p.x, 90.0); + + // Verify undo restores the original intact path in one step: + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(id).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1, "undo restores single subpath"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4, "undo restores all 4 anchors"); + + // Redo re-applies the split: + run(&mut s, "edit.redo", json!({})); + let redone_path = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap(); + assert_eq!(redone_path.subpaths.len(), 2); + + check_session(&s).unwrap(); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5b9dc39c6c..f17d27e4da 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,6 +13,7 @@ mod artboard_click; mod beyond_canvas; mod clear_commands; mod compound_attributes; +mod copy_direct_selection; mod dimensions; mod eyedropper_sources; mod find_replace_paras; diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 43b82f1272..26293842cc 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -18,11 +18,16 @@ //! `%AI5_ArtFlags`, `%AI5_TargetResolution`, `%AI5_NumLayers`, `%AI5_OpenViewLayers` (a digit for //! each layer, 7 shown and 6 hidden), `%AI7_GridSettings` (§2.1.1), and the version comment //! `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). -//! - Setup: `0 Bn` (no gradient definitions, §3), the color swatches (`%AI5_BeginPalette`, -//! `0 0 Pb`, the Registration swatch, each swatch's color operator and `(name) Pc`, a color group as `0 (name) count Pg` -//! before its swatches, `PB`), then the artboards as the `ArtboardArray` of the `/Document` -//! dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on `%_` -//! lines. +//! - Setup: the gradients the art uses as `n Bn` and a definition of each (§3.5: `%AI5_BeginGradient: +//! (name)`, `(name) type stops Bd`, `[`, each stop on a `%_` line as `color style opacity 6 midpoint +//! rampPoint Bs`, `BD`, `%AI5_EndGradient`), those only the swatches use in a non-printing block +//! (§14: `%AI5_Begin_NonPrinting`, `Np`, `%AI5_End_NonPrinting--`); the patterns the same way +//! (§3.4: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury`, the tile's art on `%_` lines, `E`, +//! `%AI3_EndPattern`); the swatches (`%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each +//! swatch's color operator, gradient instance or pattern operator and `(name) Pc`, a color group as +//! `0 (name) count Pg` before its swatches, `PB`), then the artboards as the `ArtboardArray` of the +//! `/Document` dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on +//! `%_` lines. //! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 //! dimPercent clipping Lb` (14 operands; a color that isn't one of the preset layer colors has the //! index -1; `clipping` is 1 for a clipping layer), `(name) Ln`, the layer's name as an XML id in an @@ -30,10 +35,22 @@ //! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color //! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a //! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint -//! Xs`. Upper case paints the stroke. +//! Xs`; a pattern `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P`), the matrix taking the pattern's +//! space (its tile's lower left corner the origin) to art space. Upper case paints the stroke. +//! - Gradients (§3.5.3): around the painting operator of a path (of a compound path's last path), +//! `Bb` (`1 Bb` for the stroke), a radial gradient's focal point `x y angle fraction Bh`, then +//! `flag (name) x y angle length a b c d tx ty 1 Bg`, which places the gradient on the path: a +//! linear one with the identity matrix, `x` the start and `length` the length as fractions of the +//! path's extent along `angle`; a radial one with the matrix taking the unit circle onto its +//! extent ellipse, `x` and `y` its center as fractions of the path's bounds there and `length` its +//! radius as a multiple of the one the bounds give (`writer::paints::placement`). The imaging data +//! follows (a linear gradient's `a b c d tx ty Xm`, its caps `Bc` and a `Bm` for each pair of +//! stops; a radial one's `Bm`), then the operator and `0 BB` (`2 BB` or `1 BB` when the path is +//! stroked too; a fill's instance ends `2 BB` before a stroke's). In a pattern's tile the matrices +//! are in the canvas's space (y down, from art space's origin there). //! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as -//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the -//! path, `(N) *` (`(n) *` when closed). +//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are the path +//! followed by `(N) *` (`(n) *` when closed), without the `(N) *` that §6 also puts before it. //! - Transparency: `mode opacity isolate knockout shape Xy` (the blending mode's number, Knockout //! Group 0 off, 1 on, 2 neutral), written when it changes: in a path's paint after its colors, //! before a guide, and after a group's end (`U` or `Q`) followed by `0 0 Xd` and `6 () XW`; a @@ -45,19 +62,42 @@ //! - Opacity masks: an `AI9_Mask` entry in the object's `/ArtDictionary`, a `/Mask` dictionary //! holding the mask's art between `X=` and `X+` on `%_` lines, `(Art) ,`, and `Clipping`, //! `Inverted`, `Disabled` and `Linked` as `/Bool` entries. +//! - Embedded images (§8): `%AI5_File:`, `%AI5_BeginRaster`, `() 1 XG`, the color space +//! (`/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`) with `XN`, `[matrix] w h 0 Xh`, `[matrix] 0 0 +//! w h w h 8 type alpha flags 1 0 4 4 0 0` (type 1 gray, 3 RGB, 4 CMYK; alpha 1 with an alpha +//! channel; flags 0 gray, 1 RGB, 2 CMYK, 16 more with an alpha channel), `%%BeginData:` counting +//! `XI`, its line end and the color samples, `XI`, the samples in binary (8 bits, rows from the +//! top, CMYK images with their ink amounts) followed by the alpha channel, `%%EndData`, `XH`, +//! `%AI5_EndRaster`, `N`. The matrix (to ten decimals) is an art-space matrix applied to the +//! pixels with their rows running downwards. In a part on `%_` lines, `XI` and the samples are +//! not, and `%_%%EndData` ends them. +//! - Linked images (version 7 specification §16, with the newer sections): `%AI5_BeginPlace`, +//! `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and `(path)` with `` ` ``, `%%IncludeFile:`, +//! the folder relative to the document's between `%AI28_BeginPlacedRelativePath` and its end, +//! a preview of at most 256 pixels a side between `%AI26_BeginPlacedObjectPreview` and its end +//! (`w h rowBytes 32 17 `, then rows of premultiplied ARGB), each in versioned content, `~`, +//! `%AI5_EndPlace`. The box is the file's pixels at art space's origin on the canvas; the matrix +//! takes it into art space. In opacity masks and pattern tiles, linked images are embedded. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the //! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and //! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such -//! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their -//! tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path, +//! loss a warning: type as its outlines and its inline graphics' art, freeform gradients, gradients +//! along or across a stroke and gradients without stops, with more than 256 stops or without extent +//! as their average color +//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked +//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past +//! the tile or is painted with patterns as their tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path, //! and the clipping groups inside them, as their art cut to that object (its fill cut too, its -//! stroke not), images as their outlines filled with -//! their average color, symbols and live objects as their art (symbol art past +//! stroke not; an image in a clipping group of the region it is cut to), images that can't be +//! decoded or have more than 33,554,432 pixels as their outlines filled mid gray, images of 16 bits +//! a channel at 8 bits, linked images in opacity masks and pattern tiles as embedded images, +//! symbols and live objects (placed documents included) as their art (symbol art past //! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw -//! as their filled outlines, several fills or strokes as a group of a path for each, gradient and -//! pattern swatches, the opacity and blending modes of single fills and strokes, opacity masks on +//! as their filled outlines, several fills or strokes as a group of a path for each, freeform +//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as +//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on //! layers and opacity masks nested too deep, and live effects other than geometry effects left out. //! //! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with @@ -160,10 +200,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result Result Vec { s.replace('\n', "\r\n").into_bytes() } +/// `text` with each payload's mark (`\u{1}`, its index in `payloads`, `\u{1}`) replaced by its +/// bytes. Strings are written with that byte escaped, so a mark is never part of one. +fn splice(text: &[u8], payloads: &[Vec]) -> Vec { + let mark = writer::PAYLOAD as u8; + if payloads.is_empty() { + return text.to_vec(); + } + let mut out = Vec::with_capacity(text.len() + payloads.iter().map(Vec::len).sum::()); + let mut parts = text.split(|b| *b == mark); + if let Some(first) = parts.next() { + out.extend_from_slice(first); + } + // The parts alternate: an index, then the text up to the next mark. + while let (Some(index), Some(rest)) = (parts.next(), parts.next()) { + let payload = std::str::from_utf8(index).ok().and_then(|i| i.parse::().ok()).and_then(|i| payloads.get(i)); + if let Some(p) = payload { + out.extend_from_slice(p); + } + out.extend_from_slice(rest); + } + out +} + /// `doc` with its geometry effects and group paint baked ([`vectorcraft_effects::bake_document`]), /// in its symbols' art and its patterns' tile art too (which instances and pattern fills are /// written as); `None` when nothing changes. @@ -305,7 +373,7 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, first: Re s.push('\n'); s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n"); - // Linked images aren't embedded (the data holds no images). + // Linked files aren't included (their previews are). s.push_str("%AI7_ImageSettings: 0\n"); let spots = w.spot_swatches(); for (i, (name, _)) in spots.iter().enumerate() { diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index dcf928df56..529c54a5fa 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -602,8 +602,8 @@ fn hidden_layers_open_hidden() { assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); } -/// A 200 × 100 document of what the data holds as plain paths: a gradient fill, a compound path, -/// an image, type and a symbol instance. +/// A 200 × 100 document of a gradient fill, a compound path and an image, and what the data holds +/// as plain paths: type and a symbol instance. fn unsupported() -> Document { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; @@ -665,7 +665,7 @@ fn paths(nodes: &[Arc], out: &mut Vec) { fn art_the_slice_does_not_cover_is_written_as_plain_paths() { let doc = unsupported(); let out = export_ai_editing(&doc, &opts()).unwrap(); - for w in [writer::GRADIENTS, writer::IMAGES, writer::TYPE, writer::LIVE] { + for w in [writer::TYPE, writer::LIVE] { assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); } let back = read_back(&doc); @@ -676,17 +676,19 @@ fn art_the_slice_does_not_cover_is_written_as_plain_paths() { NodeKind::Path { .. } => "path", NodeKind::Group { .. } => "group", NodeKind::Compound { .. } => "compound", + NodeKind::Image(_) => "image", _ => "other", }) .collect(); - assert_eq!(kinds, ["path", "compound", "path", "group", "group"]); + assert_eq!(kinds, ["path", "compound", "image", "group", "group"]); let mut all = vec![]; - paths(layer, &mut all); + paths(&layer[3..], &mut all); assert!(all.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); - // The gradient as its average color. - assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); - // The image's outline filled with its pixels' average. - assert_eq!(paint(layer[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5)))); + // The gradient as a gradient, drawing as it did. + let bounds = Rect::new(10.0, 10.0, 30.0, 30.0); + let original = doc.layers[0].children().unwrap()[0].appearance.items[0].paint(); + assert_eq!(drawn(&back, layer[0].appearance.items[0].paint(), bounds), drawn(&doc, original, bounds)); + // The image as an image. assert_eq!(layer[2].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); } @@ -914,11 +916,10 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((50.0, 20.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); let back = read_back(&doc); - let mut all = vec![]; - paths(back.layers[0].children().unwrap(), &mut all); - let fill = paint(all[0].appearance.items[0].paint()); - assert_ne!(fill, paint(&solid(Color::gray(0.5))), "the adjusted image is found"); - assert_ne!(fill, paint(&solid(Color::rgb(0.0, 0.0, 0.0))), "the image is adjusted"); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert_eq!(found.len(), 1, "the adjusted image is found"); + assert!(!found[0].ends_with("rgba [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]"), "the image is adjusted: {found:?}"); } #[test] @@ -937,19 +938,24 @@ fn a_group_fill_in_a_pattern_tile_is_written() { doc.insert(Some(layer), usize::MAX, filled).unwrap(); let back = read_back(&doc); let mut all = vec![]; - paths(back.layers[0].children().unwrap(), &mut all); + paths(&back.pattern("Dots").unwrap().art, &mut all); let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); - assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tiles keep their group's fill"); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tile keeps its group's fill"); } -/// A pattern fill that would place more tiles than a fill places is written as the shape filled -/// gray, as a pattern that isn't found is, instead of as nothing. +/// A pattern fill written as its tiles (its tiles aren't a grid) that would place more tiles than +/// a fill places is written as the shape filled gray, as a pattern that isn't found is, instead of +/// as nothing. #[test] fn a_pattern_fill_of_too_many_tiles_is_written_gray() { let mut doc = Document::new(1200.0, 1200.0); let layer = doc.layers[0].id; let dot = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 0.5, 0.5)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); - let tiny = vectorcraft_doc::PatternDef { tile: Rect::new(0.0, 0.0, 1.0, 1.0), ..vectorcraft_doc::PatternDef::new("Tiny", vec![Arc::new(dot)]) }; + let tiny = vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 1.0, 1.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Tiny", vec![Arc::new(dot)]) + }; doc.patterns.push(tiny); let filled = Node::path( doc.alloc_id(), @@ -978,6 +984,24 @@ fn artboard_display_marks_are_written() { assert!(ab.show_center_mark && !ab.show_cross_hairs && ab.show_video_safe_areas); } +/// A guide is its path followed by `(n) *` (closed) or `(N) *` (open), with no `(N) *` before +/// it, and reads back as the same guide. +#[test] +fn guides_are_their_path_then_the_guide_operator() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let line = shapes::line(vectorcraft_geom::Point::new(10.0, 80.0), vectorcraft_geom::Point::new(150.0, 80.0)); + for path in [shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), line] { + let g = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + } + let p = program(&doc); + let (closed, open) = (p.matches("\n(n) *\n").count(), p.matches("\n(N) *\n").count()); + assert_eq!((closed, open), (1, 1), "{p}"); + assert!(p.contains("0 Xw\n10 -10 m\n") && p.contains("10 -10 L\n(n) *\n10 -80 m\n150 -80 L\n(N) *\nLB\n"), "{p}"); + assert_eq!(lines(&read_back(&doc)), lines(&doc)); +} + #[test] fn effects_on_a_fill_are_reported_left_out() { let mut doc = Document::new(200.0, 100.0); @@ -992,26 +1016,15 @@ fn effects_on_a_fill_are_reported_left_out() { } #[test] -fn images_too_large_to_average_are_mid_gray() { +fn images_of_more_pixels_than_the_reader_reads_are_mid_gray() { let mut png = vec![]; - image::GrayImage::new(5000, 4000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - assert_eq!(image_average_of(&png), paint(&solid(Color::gray(0.5)))); - let mut small = vec![]; - image::GrayImage::new(50, 40).write_to(&mut std::io::Cursor::new(&mut small), image::ImageFormat::Png).unwrap(); - assert_eq!(image_average_of(&small), paint(&solid(Color::rgb(0.0, 0.0, 0.0)))); -} - -/// The fill an image of `png` is written with, as the reader reads it. -fn image_average_of(png: &[u8]) -> String { + image::GrayImage::new(6000, 6000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; - let blob = ImageBlob::new("image/png", png.to_vec()); - let key = blob.content_key(); - doc.images.insert(key.clone(), blob); - let im = ImageObject { key, width: 10, height: 10, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; - let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + let im = image_node(&mut doc, ImageBlob::png(png), (10, 10), Affine::IDENTITY, None); doc.insert(Some(layer), usize::MAX, im).unwrap(); - paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()) + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::IMAGES]); + assert_eq!(paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); } #[test] @@ -1368,11 +1381,9 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); - let g = Gradient::new( - GradientKind::Linear, - vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], - ); - clip.appearance = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0).into(); + // Two fills: a path paints one. + let fills = [Color::rgb(0.5, 0.5, 0.5), Color::rgb(1.0, 0.0, 0.0)].map(|c| AppearanceItem::Fill(FillLayer::new(solid(c)))); + clip.appearance = Appearance { items: fills.to_vec(), ..Appearance::default() }.into(); clip.opacity = 0.5; let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); let g = group(&mut doc, vec![clip, inside], true); @@ -1391,21 +1402,42 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let out = export_ai_editing(&masked, &opts()).unwrap(); assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); // Two fills at the clipping path's 50% are a group at 50% of the two at 100%, as the canvas - // draws them together. - let mut two = doc.clone(); - if let Some(c) = Arc::make_mut(&mut two.layers[0]).children_mut() - && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) - { - let clip = Arc::make_mut(&mut children[0]); - let mut items = clip.appearance.items.clone(); - items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(1.0, 0.0, 0.0))))); - clip.appearance = Appearance { items, ..Appearance::default() }.into(); - } - let back = read_back(&two); + // draws them together, under the art. + let back = read_back(&doc); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; let fills = &children[1]; assert!(matches!(fills.kind, NodeKind::Group { clip: false, .. }) && fills.opacity == 0.5, "{fills:?}"); assert_eq!(fills.children().unwrap().iter().map(|c| c.opacity).collect::>(), [1.0, 1.0]); + let colors: Vec = fills.children().unwrap().iter().map(|c| paint(c.appearance.items[0].paint())).collect(); + assert_eq!(colors, [paint(&solid(Color::rgb(0.5, 0.5, 0.5))), paint(&solid(Color::rgb(1.0, 0.0, 0.0)))]); + assert!(matches!(children[2].kind, NodeKind::Path { .. }) && children.len() == 3, "the art over the fills"); + // One fill a path can't paint (a brick pattern, written as its tiles) is written under the art + // at the clipping path's opacity. + let mut brick = doc.clone(); + let dot = square(&mut brick, Rect::new(0.0, 0.0, 2.0, 2.0), Color::rgb(1.0, 0.0, 0.0)); + brick.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 4.0, 4.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + if let Some(c) = Arc::make_mut(&mut brick.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + let fill = Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }; + Arc::make_mut(&mut children[0]).appearance = Appearance::basic(fill, Paint::None, 0.0).into(); + } + let out = export_ai_editing(&brick, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS) && out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let back = read_back(&brick); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.len(), 3, "the clipping path, its fill, the art"); + assert_eq!(children[1].opacity, 0.5); + let mut tiles = vec![]; + paths(std::slice::from_ref(&children[1]), &mut tiles); + let painted: Vec<&Node> = tiles.iter().filter(|t| !t.appearance.items.is_empty()).collect(); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(!painted.is_empty() && painted.iter().all(|t| t.opacity == 1.0 && paint(t.appearance.items[0].paint()) == red), "{painted:?}"); + assert_eq!(paint(children[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.0, 0.0, 1.0))), "the art over the fill"); // A locked clipping path's fill is locked too, the art it clips not. let mut locked = doc.clone(); if let Some(c) = Arc::make_mut(&mut locked.layers[0]).children_mut() @@ -1416,12 +1448,6 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let back = read_back(&locked); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; assert_eq!(children.iter().map(|c| c.locked).collect::>(), [true, true, false]); - let back = read_back(&doc); - let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; - // The clipping path, its fill as a path under the art, the art. - let fill = &children[1]; - assert!(matches!(fill.kind, NodeKind::Path { clipping: false, .. })); - assert_eq!((fill.opacity, paint(fill.appearance.items[0].paint())), (0.5, paint(&solid(Color::rgb(0.5, 0.5, 0.5))))); } /// A clipping path's stroke that a plain line can't draw goes over the clipped art, its fill under it. @@ -1430,14 +1456,10 @@ fn a_clipping_paths_other_stroke_goes_over_the_art() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); - let g = Gradient::new( - GradientKind::Linear, - vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], - ); let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 4.0); stroke.dash = Some(Dash { pattern: vec![2.0, 2.0], offset: 0.0, align_corners: true }); clip.appearance = Appearance { - items: vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(g))))), AppearanceItem::Stroke(stroke)], + items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.5, 0.5, 0.5)))), AppearanceItem::Stroke(stroke)], ..Appearance::default() } .into(); @@ -1447,7 +1469,7 @@ fn a_clipping_paths_other_stroke_goes_over_the_art() { let back = read_back(&doc); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; let colors: Vec = children.iter().skip(1).map(|c| paint(c.appearance.items.first().map_or(&Paint::None, |i| i.paint()))).collect(); - // The fill (its average) under the blue art, the red stroke's dots over it. + // The fill under the blue art, the red stroke's dots over it. assert_eq!(colors.first(), Some(&paint(&solid(Color::rgb(0.5, 0.5, 0.5)))), "{colors:?}"); assert_eq!(colors.get(1), Some(&paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), "{colors:?}"); assert!(colors.len() > 2 && colors.iter().skip(2).all(|c| *c == paint(&solid(Color::rgb(1.0, 0.0, 0.0)))), "{colors:?}"); @@ -1674,3 +1696,1351 @@ fn transparency_of_single_fills_and_layer_masks_is_reported_left_out() { let out = export_ai_editing(&doc, &opts()).unwrap(); assert!(out.warnings.iter().any(|x| x == writer::ITEM_TRANSPARENCY), "{:?}", out.warnings); } + +// ---------- gradients and patterns ---------- + +const INK: Color = Color::Cmyk { c: 0.0, m: 0.6, y: 1.0, k: 0.0 }; + +/// A gradient of `kind` through `stops` (offset, color, opacity, midpoint). +fn ramp(kind: GradientKind, stops: &[(f32, Color, f32, f32)]) -> Gradient { + let stops = + stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect(); + Gradient::new(kind, stops) +} + +/// The three-stop linear gradient of the `Sunset` swatch: its middle stop half opaque, its first +/// midpoint at 30%. +fn sunset() -> Gradient { + ramp( + GradientKind::Linear, + &[(0.0, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.3), (0.4, Color::rgb(0.0, 1.0, 0.0), 0.5, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)], + ) +} + +fn gradient_paint(g: Gradient, geom: Option, swatch: Option<&str>) -> Paint { + Paint::Gradient(Box::new(GradientPaint { geom, swatch: swatch.map(Into::into), ..GradientPaint::new(g) })) +} + +fn painted(doc: &mut Document, path: PathData, items: Vec) -> Node { + Node::path(doc.alloc_id(), path, Appearance { items, ..Appearance::default() }) +} + +/// A 300 × 200 document of gradients and patterns. Swatches: the linear gradient `Sunset`, the radial +/// gradient `Glow` that nothing uses, the spot color `Ink`, the pattern `Dots` (a 10-point grid tile of +/// a red square and a circle filled with a gradient) and `Checks`, which nothing uses. Art, bottom +/// first: a rectangle filled with `Sunset` +/// placed at 30° over part of it and stroked black; an ellipse filled with a radial gradient half as +/// high as wide whose focal point is off its center; a rectangle filled yellow and stroked with a +/// gradient; one filled and stroked with gradients; an even-odd compound path filled with a +/// gradient; an open path filled with a gradient; a rectangle filled with a gradient of a gray, a +/// CMYK color and `Ink` at 70%; a rectangle filled with `Dots` turned, scaled and moved; and a +/// rectangle stroked 8 points with `Dots`. +fn gradients_and_patterns() -> Document { + use vectorcraft_color::gradient::GradientGeom; + let mut doc = Document::new(300.0, 200.0); + let glow = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.1, 0.2, 0.8), 1.0, 0.5)]); + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // The pattern art. + let red = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + let ball = painted( + &mut doc, + shapes::ellipse(Rect::new(5.0, 5.0, 9.0, 9.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(two.clone(), None, None)))], + ); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(red), Arc::new(ball)]); + dots.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut checks = vectorcraft_doc::PatternDef::new("Checks", vec![Arc::new(check)]); + checks.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.extend([dots, checks]); + let swatch = |name: &str, paint: Paint, spot: bool| Swatch { name: name.into(), paint, global: spot, spot }; + let mut swatches: Vec = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect(); + swatches.extend([ + swatch("Sunset", gradient_paint(sunset(), None, None), false), + swatch("Glow", gradient_paint(glow.clone(), None, None), false), + swatch("Ink", solid(INK), true), + swatch("Dots", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, false), + swatch("Checks", Paint::Pattern { pattern: "Checks".into(), xf: Affine::IDENTITY }, false), + ]); + doc.swatches = swatches.into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let placed = GradientGeom { start: (20.0, 40.0).into(), end: (60.0, 17.0).into(), aspect: 1.0, focal: None }; + let mut oval = GradientGeom { start: (140.0, 30.0).into(), end: (180.0, 30.0).into(), aspect: 0.5, focal: None }; + oval.set_focal(Some((150.0, 25.0).into())); + let mut nodes = vec![ + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![fill(gradient_paint(sunset(), Some(placed), Some("Sunset"))), stroke(solid(Color::BLACK), 2.0)], + ), + painted(&mut doc, shapes::ellipse(Rect::new(100.0, 10.0, 180.0, 50.0)), vec![fill(gradient_paint(glow.clone(), Some(oval), None))]), + painted( + &mut doc, + shapes::rectangle(Rect::new(190.0, 10.0, 280.0, 50.0)), + vec![fill(solid(Color::rgb(1.0, 1.0, 0.0))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 110.0)), + vec![fill(gradient_paint(sunset(), None, Some("Sunset"))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + ]; + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 70.0, 180.0, 110.0)), Appearance::default()); + let hole = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(120.0, 80.0, 160.0, 100.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance { items: vec![fill(gradient_paint(two.clone(), None, None))], ..Appearance::default() }.into(); + nodes.push(ring); + let mut open = shapes::line((190.0, 110.0).into(), (280.0, 70.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((200.0, 70.0).into())); + sp.closed = false; + } + nodes.push(painted(&mut doc, open, vec![fill(gradient_paint(two, None, None))])); + let mixed = ramp( + GradientKind::Linear, + &[(0.0, Color::gray(0.2), 1.0, 0.5), (0.5, Color::cmyk(1.0, 0.0, 0.0, 0.0), 1.0, 0.5), (1.0, INK.tinted(0.7), 1.0, 0.5)], + ); + let mut mixed_paint = gradient_paint(mixed, None, None); + if let Paint::Gradient(g) = &mut mixed_paint + && let Some(s) = g.gradient.stops.last_mut() + { + s.set_color(INK.tinted(0.7), Some(("Ink".into(), 0.7))); + } + nodes.push(painted(&mut doc, shapes::rectangle(Rect::new(10.0, 130.0, 90.0, 170.0)), vec![fill(mixed_paint)])); + let turned = Affine::translate((103.0, 127.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(0.5); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(100.0, 130.0, 180.0, 170.0)), + vec![fill(Paint::Pattern { pattern: "Dots".into(), xf: turned })], + )); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(195.0, 135.0, 235.0, 165.0)), + vec![stroke(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 8.0)], + )); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// A gradient paint's swatch link in `doc`: the gradient swatch it names, `-` for none, and +/// `not a gradient swatch: name` when it names a swatch of other paint. A link that names no swatch +/// of `doc` at all is `-` too: the reader links every gradient instance to its definition's name, +/// and a definition of a gradient that isn't a swatch has a name no swatch has. +fn link(doc: &Document, swatch: &Option) -> String { + match swatch.as_deref().map(|s| (s, doc.swatch(s))) { + Some((s, Some(w))) if matches!(w.paint, Paint::Gradient(_)) => s.to_string(), + Some((s, Some(_))) => format!("not a gradient swatch: {s}"), + Some((_, None)) | None => "-".into(), + } +} + +/// Paint `p` as it draws on `bounds`: a gradient by its kind, stops (place, color, opacity, +/// midpoint, link) and its parameter at the corners, edge midpoints and center of `bounds`; a +/// pattern by its name and matrix. +fn drawn(doc: &Document, p: &Paint, bounds: Rect) -> String { + match p { + Paint::Gradient(g) => { + let geom = g.resolve(bounds); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + format!( + "{} {} {} {} {:?}", + r3(f64::from(s.offset)), + color(&s.color), + r3(f64::from(s.opacity)), + r3(f64::from(s.midpoint)), + s.swatch + ) + }) + .collect(); + let (x, y) = ([bounds.x0, bounds.center().x, bounds.x1], [bounds.y0, bounds.center().y, bounds.y1]); + let at: Vec = + x.iter().flat_map(|x| y.iter().map(move |y| (*x, *y))).map(|(x, y)| r3(geom.param_at(g.gradient.kind, (x, y).into()))).collect(); + format!("{:?} [{}] link={} at {}", g.gradient.kind, stops.join(", "), link(doc, &g.swatch), at.join(" ")) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(r3)), + other => paint(other), + } +} + +/// What each object of `nodes` draws: its kind, bounds and paint. +fn paints_of(doc: &Document, nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let bounds = n.geometric_bounds().unwrap_or(Rect::ZERO); + let mut s = format!("{depth} {} {:?}", n.kind_label(), [bounds.x0, bounds.y0, bounds.x1, bounds.y1].map(r3)); + // Items that paint nothing aren't written. + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &match it { + AppearanceItem::Fill(f) => format!(" fill({})", drawn(doc, &f.paint, bounds)), + AppearanceItem::Stroke(st) => format!(" stroke({} w={})", drawn(doc, &st.paint, st.paint_bounds(bounds)), r3(st.width)), + }; + } + out.push(s); + // A compound path's paint is its own, not its members'. + if !matches!(n.kind, NodeKind::Compound { .. }) { + paints_of(doc, n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } +} + +/// What `doc`'s art, patterns and gradient and pattern swatches draw. +fn gradient_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1].map(r3))); + paints_of(doc, &p.art, 1, &mut out); + } + for s in doc.swatches_iter() { + match &s.paint { + Paint::Gradient(g) => { + out.push(format!("swatch {} {}", s.name, drawn(doc, &Paint::Gradient(Box::new(GradientPaint::new(g.gradient.clone()))), Rect::ZERO))) + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", s.name)), + _ => {} + } + } + out +} + +#[test] +fn gradients_and_patterns_are_read_back() { + let doc = gradients_and_patterns(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +#[test] +fn gradients_and_patterns_write_the_same_bytes_again() { + let doc = gradients_and_patterns(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + same_lines( + &String::from_utf8(again.program).unwrap().lines().map(str::to_string).collect::>(), + &String::from_utf8(first.program).unwrap().lines().map(str::to_string).collect::>(), + ); +} + +#[test] +fn gradients_and_patterns_are_written_in_their_forms() { + let text = program(&gradients_and_patterns()); + // The gradients the art uses, then the one only the palette uses; then the patterns. + let setup = text.split("%%BeginSetup\n").nth(1).and_then(|s| s.split("%AI5_BeginPalette").next()).unwrap(); + let markers: Vec<&str> = setup.lines().filter(|l| l.starts_with("%AI") || l.ends_with(" Bn")).collect(); + assert_eq!( + markers, + [ + "4 Bn", + "%AI5_BeginGradient: (Sunset)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 2)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 3)", + "%AI5_EndGradient", + "%AI5_Begin_NonPrinting", + "1 Bn", + "%AI5_BeginGradient: (Glow)", + "%AI5_EndGradient", + "%AI5_End_NonPrinting--", + "%AI3_BeginPattern: (Dots)", + "%AI3_EndPattern", + "%AI5_Begin_NonPrinting", + "%AI3_BeginPattern: (Checks)", + "%AI3_EndPattern", + "%AI5_End_NonPrinting--", + ] + ); + // A linear gradient's stops from the last; RGB with its CMYK equivalent, style 2, opacity, 6, + // midpoint, place on the ramp. + assert!(text.contains("(Sunset) 0 3 Bd\n[\n%_"), "{setup}"); + assert!( + setup.contains(" 0 0 1 2 1 6 50 100 Bs\n") && setup.contains(" 0 1 0 2 0.5 6 50 40 Bs\n") && setup.contains(" 1 0 0 2 1 6 30 0 Bs\n"), + "{setup}" + ); + // Gray, CMYK, and a spot color at 70%. + assert!( + setup.contains("%_0.8 0 1 6 50 0 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n") + || setup.contains("(Ink) 0.3 3 1 6 50 100 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n%_0.8 0 1 6 50 0 Bs\n"), + "{setup}" + ); + // The tile in the pattern's space, y up, the art on `%_` lines. + assert!(setup.contains("%AI3_BeginPattern: (Dots)\n(Dots) 0 -10 10 0\n%_"), "{setup}"); + assert!(!setup.contains("%_E\n") && setup.contains("\nE\n%AI3_EndPattern\n"), "{setup}"); + // The swatches. + assert!(text.contains("Bb\n2 (Sunset) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sunset) Pc\n"), "{text}"); + assert!(text.contains("Bb\n0 0 0 0 Bh\n2 (Glow) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Glow) Pc\n"), "{text}"); + assert!(text.contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots) Pc\n"), "{text}"); + // The instances: the stroked rectangle's fill placed at 29.9° from 0.15 of the rectangle's extent + // that way, 0.52 of it long, with `Xm`, caps and a `Bm` for each pair of stops, `b` and `2 BB`; the + // stroke's `1 Bb`; the radial's focal point and `Bm`. + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n1 (Sunset) 0.1529 0 29.8989 0.5167 1 0 0 1 0 0 1 Bg\n") && art.contains(" Xm\n"), "{art}"); + let sunset_instance = art.split("Bb\n1 (Sunset)").nth(1).unwrap(); + let ops: Vec<&str> = sunset_instance.lines().take(7).map(|l| l.rsplit(' ').next().unwrap_or(l)).collect(); + assert_eq!(ops, ["Bg", "Xm", "Bc", "Bm", "Bm", "Bc", "b"], "{sunset_instance}"); + assert!(sunset_instance.contains("\nb\n2 BB\n"), "{sunset_instance}"); + assert!(art.contains("1 Bb\n1 (Gradient 2) "), "{art}"); + assert!(art.contains("2 BB\n1 Bb\n"), "fill and stroke: {art}"); + // The radial (40 wide, 20 high) as the unit circle through its matrix: the focal point 10 right of + // the center and 5 up, at 45° and 0.35 of the radius on that circle. + assert!(art.contains("Bb\n10 5 45 0.3536 Bh\n1 (Gradient) 0 0 0 1 40 0 0 20 0 0 1 Bg\n40 0 0 -20 140 -30 Bm\nf\n0 BB\n"), "{art}"); + // The tile's box first in a pattern's definition. + assert!(setup.contains("(Dots) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n"), "{setup}"); + assert!(setup.contains("%_n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"), "{setup}"); + assert!(art.contains("F\n0 BB\n"), "the open path: {art}"); + assert!(art.contains(" p\n") && art.contains(" P\n"), "{art}"); +} + +/// A clipping path filled with a gradient keeps it: the reader reads it as the clipping path and +/// its fill as a path of its own under the art. +#[test] +fn a_clipping_path_keeps_its_gradient() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(gradient_paint(sunset(), None, None), Paint::None, 0.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\nBb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let fill = &children[1]; + let bounds = Rect::new(10.0, 10.0, 90.0, 60.0); + let want = drawn(&doc, &gradient_paint(sunset(), None, None), bounds); + assert_eq!(drawn(&back, fill.appearance.items[0].paint(), bounds), want); +} + +#[test] +fn freeform_gradients_are_written_as_their_average_color() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); +} + +/// A gradient that dithers or mixes perceptually is written as a classic one; a stop linked to a +/// global process color is written as its color; each with a warning. +#[test] +fn gradient_options_and_links_the_data_cant_hold_are_reported() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut g = sunset(); + g.dither = true; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX]); + // A swatch of such a gradient that nothing uses. + let mut swatch_only = Document::new(200.0, 100.0); + let mut dithered = sunset(); + dithered.dither = true; + let mut swatches: Vec = swatch_only.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Dithered".into(), paint: gradient_paint(dithered, None, None), global: false, spot: false }); + swatch_only.swatches = swatches.into(); + let out = export_ai_editing(&swatch_only, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_MIX), "{:?}", out.warnings); + // A gradient along a stroke: the stroke's outline in its average color. + let mut along = Document::new(200.0, 100.0); + let layer = along.layers[0].id; + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + let n = painted(&mut along, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]); + along.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&along, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }); + doc.swatches = swatches.into(); + let mut g = sunset(); + g.method = vectorcraft_color::gradient::GradientMethod::Perceptual; + if let Some(s) = g.stops.first_mut() { + s.set_color(BRAND, Some(("Brand".into(), 1.0))); + } + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX, writer::STOP_LINKS]); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; + assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None)); +} + +/// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition +/// would cut its art off at the tile's edge. +#[test] +fn a_pattern_whose_art_reaches_past_its_tile_is_written_as_its_tiles() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = square(&mut doc, Rect::new(-2.0, -2.0, 6.0, 6.0), Color::rgb(1.0, 0.0, 0.0)); + let mut over = vectorcraft_doc::PatternDef::new("Over", vec![Arc::new(big)]); + over.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(over); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Over".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern")); +} + +/// A pattern fill in another pattern's tile is written there as its tiles cut to the shape; the +/// outer pattern is defined and fills the shape. +#[test] +fn a_pattern_fill_in_a_pattern_tile_is_written_as_its_tiles() { + let mut doc = gradients_and_patterns(); + let layer = doc.layers[0].id; + let inner = painted( + &mut doc, + shapes::rectangle(Rect::new(2.0, 2.0, 18.0, 18.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }))], + ); + let mut nest = vectorcraft_doc::PatternDef::new("Nest", vec![Arc::new(inner)]); + nest.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + doc.patterns.push(nest); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(250.0, 130.0, 290.0, 170.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Nest".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("%AI3_BeginPattern: (Nest)") && text.contains("%AI3_BeginPattern: (Dots)")); + let back = read_back(&doc); + let filled = back.layers[0].children().unwrap().last().unwrap(); + assert!(matches!(filled.appearance.items[0].paint(), Paint::Pattern { pattern, .. } if pattern == "Nest")); + // Nest's tile: the dots' tiles (a red square, a gradient circle) cut to its square. + let mut all = vec![]; + paths(&back.pattern("Nest").unwrap().art, &mut all); + assert!(all.len() > 2, "{}", all.len()); + assert!(all.iter().all(|p| !matches!(p.appearance.items[0].paint(), Paint::Pattern { .. }))); + assert!(all.iter().any(|p| paint(p.appearance.items[0].paint()) == paint(&solid(Color::rgb(1.0, 0.0, 0.0))))); +} + +/// A 200 × 100 document with one object of `items` on `path`, and only the None swatch. +fn one_object(path: PathData, items: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect::>().into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let n = painted(&mut doc, path, items); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// What `doc`'s art draws (a palette of only the None swatch reads back as the default swatches). +fn art_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + out +} + +fn swatches_plus(doc: &mut Document, more: Vec) { + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.extend(more); + doc.swatches = swatches.into(); +} + +/// `Bg` places each gradient on its path: a radial one 30 right of and 10 above the middle of a +/// 120 × 60 rectangle, 20 in radius, by its unit circle's matrix, its center's place as fractions of +/// the bounds and its radius as a multiple of √((1.5² + 2²) / 2) (the center's distances to the +/// right side and to the bottom in that circle's units); and a linear one at −45° on a triangle, +/// from a quarter of the triangle's extent that way, half of it long. In a pattern's tile the same +/// two are placed mirrored top to bottom: the radial's center 10 below the middle, its radius a +/// multiple of √((1.5² + 1²) / 2), and the linear one at 45°. +#[test] +fn bg_places_gradients_on_their_paths() { + use vectorcraft_color::gradient::GradientGeom; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let off_center = GradientGeom { start: (90.0, 20.0).into(), end: (110.0, 20.0).into(), aspect: 1.0, focal: None }; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial.clone(), Some(off_center), None))]); + let layer = doc.layers[0].id; + let mut triangle = shapes::line((130.0, 10.0).into(), (190.0, 10.0).into()); + if let Some(sp) = triangle.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((130.0, 40.0).into())); + sp.closed = true; + } + let turned = GradientGeom { start: (145.0, 10.0).into(), end: (160.0, 25.0).into(), aspect: 1.0, focal: None }; + let n = painted(&mut doc, triangle.clone(), vec![fill(gradient_paint(sunset(), Some(turned), None))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let in_tile = painted(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial, Some(off_center), None))]); + let slant = painted(&mut doc, triangle, vec![fill(gradient_paint(sunset(), Some(turned), None))]); + let mut tile = vectorcraft_doc::PatternDef::new("Tile", vec![Arc::new(in_tile), Arc::new(slant)]); + tile.tile = Rect::new(0.0, 0.0, 200.0, 60.0); + doc.patterns.push(tile); + swatches_plus( + &mut doc, + vec![Swatch { name: "Tile".into(), paint: Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }, global: false, spot: false }], + ); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(130.0, 50.0, 190.0, 90.0)), + vec![fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY })], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n0 0 0 0 Bh\n1 (Gradient) 0.25 -0.1667 0 0.5657 20 0 0 20 0 0 1 Bg\n"), "{art}"); + assert!(art.contains("Bb\n1 (Gradient 2) 0.25 0 -45 0.5 1 0 0 1 0 0 1 Bg\n"), "{art}"); + let setup = text.split("%AI3_BeginPattern: (Tile)").nth(1).unwrap(); + assert!(setup.contains("%_Bb\n%_0 0 0 0 Bh\n%_1 (Gradient) 0.25 0.1667 0 0.7845 20 0 0 20 0 0 1 Bg\n"), "{setup}"); + assert!(setup.contains("%_Bb\n%_1 (Gradient 2) 0.25 0 45 0.5 1 0 0 1 0 0 1 Bg\n"), "{setup}"); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// A definition of a gradient that isn't a swatch takes a name that no swatch and no pattern has, +/// so that its instances don't read back linked to another swatch. +#[test] +fn gradient_definitions_skip_the_names_of_swatches_and_patterns() { + let mut doc = gradients_and_patterns(); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 2", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus( + &mut doc, + vec![ + Swatch { name: "Gradient".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }, + Swatch { + name: "Gradient 2".into(), + paint: Paint::Pattern { pattern: "Gradient 2".into(), xf: Affine::IDENTITY }, + global: false, + spot: false, + }, + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + assert_eq!(names, ["(Sunset)", "(Gradient 3)", "(Gradient 4)", "(Gradient 5)", "(Glow)"]); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// Each search for a new gradient name starts after the last name given, so naming many gradients +/// tries each name once. +#[test] +fn gradient_names_are_searched_from_the_last_one_given() { + let mut taken: std::collections::HashSet = ["Gradient 2", "Gradient 5"].map(String::from).into(); + let (mut next, mut tries) = (1, 0); + let mut names = vec![]; + for _ in 0..1000 { + let name = writer::free_gradient_name(&mut next, |name| { + tries += 1; + taken.contains(name) + }); + taken.insert(name.clone()); + names.push(name); + } + assert_eq!(names[..4], ["Gradient", "Gradient 3", "Gradient 4", "Gradient 6"]); + assert_eq!(names.last().map(String::as_str), Some("Gradient 1002")); + assert_eq!(tries, 1002); + assert_eq!(next, 1003); +} + +/// Many gradients that no swatch names each get their own name, in order, skipping the names of +/// swatches and patterns, and the same names when the document is written again. +#[test] +fn many_gradient_definitions_take_distinct_names_in_order() { + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![]); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 7", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus(&mut doc, vec![Swatch { name: "Gradient 3".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }]); + let layer = doc.layers[0].id; + for i in 0..300u16 { + let shade = f32::from(i) / 300.0; + let g = ramp(GradientKind::Linear, &[(0.0, Color::rgb(shade, 0.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let x = f64::from(i % 20) * 10.0; + let y = f64::from(i / 20) * 6.0; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(x, y, x + 8.0, y + 5.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + let expected: Vec = + std::iter::once("(Gradient)".to_string()).chain((2..=302).filter(|&i| i != 3 && i != 7).map(|i| format!("(Gradient {i})"))).collect(); + assert_eq!(names, expected); + assert_eq!(text, program(&doc)); +} + +/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, +/// and reads back with each stop on its side. +#[test] +fn a_linear_gradient_with_every_stop_at_one_place_keeps_its_sides() { + let edge = ramp(GradientKind::Linear, &[(0.3, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.4), (0.3, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.7)]); + let doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(edge, None, None)))], + ); + let text = program(&doc); + let (blue, red) = (text.find(" 0 0 1 2 1 6 70 30 Bs\n").unwrap(), text.find(" 1 0 0 2 1 6 40 30 Bs\n").unwrap()); + assert!(blue < red, "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// Gradients without stops or with more than 256, without a ramp's length or flattened to a line +/// are written as their average color with a warning that says so, not the one for freeform +/// gradients. +#[test] +fn gradients_that_cant_be_placed_are_reported_as_such() { + use vectorcraft_color::gradient::GradientGeom; + let point = GradientGeom { start: (20.0, 20.0).into(), end: (20.0, 20.0).into(), aspect: 1.0, focal: None }; + let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None }; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // More stops than the `.ai` reader reads. + let many: Vec<(f32, Color, f32, f32)> = (0..257).map(|i| (i as f32 / 256.0, Color::gray(i as f32 / 256.0), 1.0, 0.5)).collect(); + for p in [ + gradient_paint(sunset(), Some(point), None), + gradient_paint(radial, Some(flat), None), + gradient_paint(Gradient::new(GradientKind::Linear, vec![]), None, None), + gradient_paint(ramp(GradientKind::Linear, &many), None, None), + ] { + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Fill(FillLayer::new(p.clone()))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_SHAPES], "{p:?}"); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].appearance.items[0].paint(), Paint::Solid { .. }), "{p:?}"); + } +} + +/// A gradient across a stroke is written as the stroke's outline in its average color, with the +/// warning. +#[test] +fn a_gradient_across_a_stroke_is_its_average_color() { + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Across; + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Stroke(st)]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + assert!(!program(&doc).contains("Bb\n")); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + assert!(!all.is_empty() && all.iter().all(|p| p.appearance.items.iter().all(|i| matches!(i.paint(), Paint::Solid { .. }))), "{all:?}"); +} + +/// Patterns whose tiles are hexagons or bricks are written as their tiles cut to the shape, with the +/// warning, and aren't defined. +#[test] +fn hex_and_brick_patterns_are_written_as_their_tiles() { + for tile_type in [ + vectorcraft_doc::TileType::HexByRow, + vectorcraft_doc::TileType::HexByColumn, + vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + vectorcraft_doc::TileType::BrickByColumn { offset: 0.5 }, + ] { + let mut doc = one_object( + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Cells".into(), xf: Affine::IDENTITY }))], + ); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type, + ..vectorcraft_doc::PatternDef::new("Cells", vec![Arc::new(dot)]) + }); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{tile_type:?}: {:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern"), "{tile_type:?}"); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "{tile_type:?}"); + } +} + +/// An open path filled and stroked with gradients: the fill's instance ends `1 BB`, the stroke's +/// `1 Bb` follows, and the open path's `B` ends `1 BB`. +#[test] +fn an_open_path_keeps_its_gradient_fill_and_stroke() { + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let mut open = shapes::line((20.0, 80.0).into(), (100.0, 20.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((150.0, 70.0).into())); + sp.closed = false; + } + let doc = one_object( + open, + vec![ + AppearanceItem::Fill(FillLayer::new(gradient_paint(sunset(), None, None))), + AppearanceItem::Stroke(StrokeLayer::new(gradient_paint(two, None, None), 3.0)), + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("\n1 BB\n1 Bb\n1 (Gradient 2) ") && text.contains("\nB\n1 BB\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A clipping path stroked with a gradient keeps it. +#[test] +fn a_clipping_path_keeps_its_gradient_stroke() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(Paint::None, gradient_paint(sunset(), None, None), 3.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\n1 Bb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let mut want = vec![]; + paints_of(&doc, doc.layers[0].children().unwrap(), 0, &mut want); + let mut got = vec![]; + paints_of(&back, back.layers[0].children().unwrap(), 0, &mut got); + let strokes = |v: &[String]| { + v.iter().filter(|l| l.contains(" stroke(Linear")).map(|l| l.split(" stroke(").nth(1).unwrap_or_default().to_string()).collect::>() + }; + assert_eq!(strokes(&got), strokes(&want), "{got:#?}"); +} + +/// In a CMYK document the gradient's CMYK stops are written as CMYK and read back the same. +#[test] +fn a_cmyk_documents_gradients_keep_their_stops() { + let cmyk = ramp(GradientKind::Linear, &[(0.0, Color::cmyk(0.0, 0.6, 1.0, 0.0), 1.0, 0.5), (1.0, Color::cmyk(1.0, 0.0, 0.0, 0.2), 0.5, 0.25)]); + let mut doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(cmyk, None, None)))], + ); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let text = program(&doc); + assert!(text.contains("%AI9_ColorModel: 2\n"), "{text}"); + assert!(text.contains("%_1 0 0 0.2 1 0.5 6 25 100 Bs\n%_0 0.6 1 0 1 1 6 50 0 Bs\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A compound path's gradient instance is on its last subpath only. +#[test] +fn a_compound_paths_gradient_is_on_its_last_subpath() { + let text = program(&gradients_and_patterns()); + let compound = text.split("*u\n").nth(1).and_then(|s| s.split("*U\n").next()).unwrap(); + assert_eq!(compound.matches("Bb\n").count(), 1, "{compound}"); + let last_subpath = compound.rfind(" m\n").unwrap(); + assert!(compound.find("Bb\n").unwrap() > last_subpath, "{compound}"); + assert_eq!(compound.matches(" m\n").count(), 2, "{compound}"); +} + +/// Freeform gradient swatches and swatches of patterns that can't be defined are left out with the +/// warning; a color group counts only the swatches written. +#[test] +fn swatches_the_data_cant_hold_are_left_out() { + let mut doc = gradients_and_patterns(); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + let free = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let swatch = |name: &str, paint: Paint| Swatch { name: name.into(), paint, global: false, spot: false }; + doc.swatch_groups = vec![SwatchGroup { + name: "Mixed".into(), + swatches: vec![ + swatch("Free", gradient_paint(free.clone(), None, None)), + swatch("Dawn", gradient_paint(sunset(), None, None)), + swatch("Brick", Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }), + swatch("Dots 2", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }), + ], + }] + .into(); + swatches_plus(&mut doc, vec![swatch("Free 2", gradient_paint(free, None, None))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCHES], "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("0 (Mixed) 2 Pg\n"), "{text}"); + for name in ["(Free) Pc", "(Free 2) Pc", "(Brick) Pc", "%AI3_BeginPattern: (Brick)"] { + assert!(!text.contains(name), "{name}"); + } + let back = read_back(&doc); + let group = back.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(group.swatches.iter().map(|s| s.name.as_str()).collect::>(), ["Dawn", "Dots 2"]); +} + +/// A pattern swatch that moves, turns or scales its pattern is written with its pattern, and the +/// placement is reported left out. +#[test] +fn a_pattern_swatchs_own_placement_is_reported_left_out() { + let mut doc = gradients_and_patterns(); + let moved = Paint::Pattern { pattern: "Dots".into(), xf: Affine::scale(2.0) }; + swatches_plus(&mut doc, vec![Swatch { name: "Big Dots".into(), paint: moved, global: false, spot: false }]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCH_PLACEMENT]); + assert!(program(&doc).contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Big Dots) Pc\n")); +} + +// ---------- images and placed files ---------- + +/// `img` as PNG bytes. +fn png_of(img: image::DynamicImage) -> Vec { + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png +} + +/// An image object of `blob`'s pixels (`w` × `h`) placed by `xf`, its blob kept in `doc`. +fn image_node(doc: &mut Document, blob: ImageBlob, (w, h): (u32, u32), xf: Affine, link: Option) -> Node { + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: w, height: h, xf, link, placement: Default::default(), pixels: None }; + Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))) +} + +/// A 3 × 2 RGB image, every pixel a different color. +fn rgb_png() -> Vec { + let px = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [12, 34, 56]]; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(px[(y * 3 + x) as usize])))) +} + +/// A 200 × 100 document of images: on a layer `Pictures`, an RGB image `Photo` turned, scaled and +/// moved, at half opacity in Multiply; a locked RGBA image whose pixels are see-through in part; a +/// hidden gray image; a CMYK image; a clipping group of the RGB image cut by a rectangle; a square +/// whose opacity mask is a gray image. On a layer `Links`, a linked image in a folder next to the +/// document's. +fn images_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let turned = Affine::translate((40.0, 30.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(8.0, 6.0); + let mut photo = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), turned, None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.blend = BlendMode::Multiply; + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + let alpha = [0, 128, 255, 200]; + let rgba = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([200, 100, (x * 50) as u8, alpha[(y * 2 + x) as usize]])); + let mut see = image_node(&mut doc, ImageBlob::png(png_of(rgba.into())), (2, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 60.0, 10.0]), None); + see.locked = true; + doc.insert(Some(layer), usize::MAX, see).unwrap(); + let gray = image::GrayImage::from_fn(4, 1, |x, _| image::Luma([(x * 60) as u8])); + let mut gray = image_node(&mut doc, ImageBlob::png(png_of(gray.into())), (4, 1), Affine::new([5.0, 0.0, 0.0, 5.0, 90.0, 60.0]), None); + gray.visible = false; + doc.insert(Some(layer), usize::MAX, gray).unwrap(); + let inks = vectorcraft_doc::cmyk::Inks::new(2, 1, vec![255, 0, 0, 0, 10, 20, 30, 40]).unwrap(); + let cmyk = image_node(&mut doc, ImageBlob::cmyk_tiff(&inks).unwrap(), (2, 1), Affine::new([10.0, 0.0, 0.0, 10.0, 120.0, 10.0]), None); + doc.insert(Some(layer), usize::MAX, cmyk).unwrap(); + let clip = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 25.0)), Appearance::default()); + let inside = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 145.0, 5.0]), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(inside)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let ramp = image::GrayImage::from_fn(3, 3, |x, y| image::Luma([(x * 100 + y * 20) as u8])); + let mask_art = image_node(&mut doc, ImageBlob::png(png_of(ramp.into())), (3, 3), Affine::new([10.0, 0.0, 0.0, 10.0, 10.0, 60.0]), None); + let mut square = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 60.0, 40.0, 90.0)), + Appearance::basic(solid(Color::rgb(0.0, 0.5, 1.0)), Paint::None, 0.0), + ); + // A mask's art is read into a group. + let mask_art = Node::group(doc.alloc_id(), vec![Arc::new(mask_art)]); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let links = Node::layer(doc.alloc_id(), "Links", LayerColor::Preset(1)); + let links_id = links.id; + doc.layers.push(Arc::new(links)); + let pic = image::RgbaImage::from_fn(3, 3, |x, y| image::Rgba([(x * 80) as u8, (y * 80) as u8, 30, 255])); + let mut link = vectorcraft_doc::LinkInfo::new("/Users/someone/Job (1)/art/pic.png"); + link.relative = Some("art/pic.png".into()); + let placed = image_node(&mut doc, ImageBlob::png(png_of(pic.into())), (3, 3), Affine::new([4.0, 1.0, -1.0, 4.0, 60.0, 50.0]), Some(link)); + doc.insert(Some(links_id), usize::MAX, placed).unwrap(); + doc +} + +/// Each image in `nodes` (opacity masks' art included), in order: where it is, its state, size, +/// placement, link and pixels (RGBA, or a CMYK image's ink amounts). +fn pictures(doc: &Document, nodes: &[Arc], path: &str, out: &mut Vec) { + for (i, n) in nodes.iter().enumerate() { + let at = format!("{path}/{i}"); + if let NodeKind::Image(im) = &n.kind { + let blob = doc.image_blob(im).unwrap(); + let pixels = match blob.cmyk() { + Some(inks) if blob.is_cmyk() => format!("cmyk {:?}", inks.data), + _ => format!("rgba {:?}", image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw()), + }; + let xf: Vec = im.xf.as_coeffs().iter().map(|v| r3(*v)).collect(); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + out.push(format!( + "{at} {:?} shown={} locked={} opacity={} {:?} {}x{} [{}] {link:?} {pixels}", + n.name, + n.visible, + n.locked, + r3(f64::from(n.opacity)), + n.blend, + im.width, + im.height, + xf.join(" ") + )); + } + if let Some(m) = &n.extras().mask { + pictures(doc, std::slice::from_ref(&m.art), &format!("{at}/mask"), out); + } + if let Some(c) = n.children() { + pictures(doc, c, &at, out); + } + } +} + +fn images_of(doc: &Document) -> Vec { + let mut out = vec![]; + pictures(doc, &doc.layers, "", &mut out); + out +} + +#[test] +fn images_come_back_with_their_pixels_and_places() { + let doc = images_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + let want = images_of(&doc); + let got = images_of(&back); + assert_eq!(want.len(), 7); + for (g, w) in got.iter().zip(&want) { + assert_eq!(g, w); + } + assert_eq!(got.len(), want.len(), "{got:?}"); + // The clipping group and the masked square are there as themselves. + assert_eq!(lines(&back).len(), lines(&doc).len(), "{:?}", lines(&back)); +} + +#[test] +fn images_are_written_again_as_the_same_bytes() { + let mut doc = images_doc(); + // The default swatches' RGB colors come back a ten-thousandth off in their CMYK equivalents. + doc.swatches.retain(|s| matches!(s.paint, Paint::None)); + doc.swatches.push(Swatch { name: "Gold".into(), paint: solid(GOLD), global: false, spot: false }); + doc.swatch_groups = Default::default(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; + for (a, b) in shown(&again).lines().zip(shown(&first.program).lines()) { + assert_eq!(a, b); + } + assert_eq!(again, first.program); +} + +/// The program of `doc` with LF line ends, and each image's samples (from after `XI` and its line +/// end to `%%EndData`, a `%_` before it kept) and each preview's rows (from after `32 17 ` to the +/// line end before `%AI26_EndPlacedObjectPreview`) shown as ``. +fn program_shown(doc: &Document) -> String { + shown(&export_ai_editing(doc, &opts()).unwrap().program) +} + +/// Program `p` as [`program_shown`] shows it. +fn shown(p: &[u8]) -> String { + let find = |from: usize, what: &[u8]| p.get(from..).and_then(|r| r.windows(what.len()).position(|w| w == what)).map(|i| i + from); + let mut out = Vec::new(); + let mut at = 0; + loop { + let xi = find(at, b"\r\nXI\r\n").map(|i| (i + 6, b"%%EndData".as_slice())); + let pv = find(at, b" 32 17 ").map(|i| (i + 7, b"\r\n%AI26_EndPlacedObjectPreview".as_slice())); + let Some((start, end)) = [xi, pv].into_iter().flatten().min_by_key(|(s, _)| *s) else { break }; + let mut stop = find(start, end).unwrap(); + if end.starts_with(b"%%") && p.get(stop - 2..stop) == Some(b"%_") { + stop -= 2; + } + out.extend_from_slice(&p[at..start]); + out.extend_from_slice(format!("<{} bytes>", stop - start).as_bytes()); + at = stop; + } + out.extend_from_slice(&p[at..]); + String::from_utf8(out).unwrap().replace("\r\n", "\n") +} + +#[test] +fn an_image_is_a_raster_with_binary_samples() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 30.0]), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let p = export_ai_editing(&doc, &opts()).unwrap().program; + // `XI`, CR LF and the 18 samples, which are counted, follow the count's line. + let at = p.windows(17).position(|w| w == b"%%BeginData: 22\r\n").unwrap(); + let samples: Vec = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0, 0, 255, 255, 12, 34, 56]; + let mut want = b"XI\r\n".to_vec(); + want.extend_from_slice(&samples); + want.extend_from_slice(b"%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\r\n"); + assert_eq!(p.get(at + 17..at + 17 + want.len()), Some(want.as_slice())); + let text = program_shown(&doc); + // Art space is y up from the artboard's top-left corner, the pixels' rows run downwards. + assert!( + text.contains( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 3 2 0 Xh\n[10 0 0 10 20 -30] 0 0 3 2 3 2 8 3 0 1 1 0 4 4 0 0\n" + ), + "{text}" + ); +} + +#[test] +fn see_through_gray_and_cmyk_images_have_their_flags() { + let doc = images_doc(); + let text = program_shown(&doc); + // RGBA: the alpha channel follows the color samples, which the count doesn't take in. + assert!(text.contains(" 0 0 2 2 2 2 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 16\nXI\n<16 bytes>%%EndData\n"), "{text}"); + assert!(text.contains("/DeviceGray XN\n"), "{text}"); + assert!(text.contains(" 0 0 4 1 4 1 8 1 0 0 1 0 4 4 0 0\n"), "{text}"); + assert!(text.contains("/DeviceCMYK XN\n"), "{text}"); + assert!(text.contains(" 0 0 2 1 2 1 8 4 0 2 1 0 4 4 0 0\n%%BeginData: 12\nXI\n<8 bytes>%%EndData\n"), "{text}"); + // In an opacity mask: on `%_` lines but for `XI` and its samples. + assert!(text.contains("%_%%BeginData: 13\nXI\n<9 bytes>%_%%EndData\n%_XH\n%_%AI5_EndRaster\n%_N\n"), "{text}"); +} + +#[test] +fn a_linked_image_is_a_placed_file_with_a_preview() { + let doc = images_doc(); + let text = program_shown(&doc); + let begin = text.find("%AI5_BeginPlace\n").unwrap(); + let place = &text[begin..text[begin..].find("%AI5_EndPlace\n").unwrap() + begin]; + let lines: Vec<&str> = place.lines().collect(); + assert_eq!(lines[1], "%%FileType: 1"); + assert!(lines[2].ends_with("] 8091 8141 8094 8144 4 4 0"), "{place}"); + assert_eq!(lines[3], "(/Users/someone/Job \\(1\\)/art/pic.png)`"); + assert_eq!(lines[4], "%%IncludeFile:/Users/someone/Job (1)/art/pic.png"); + assert_eq!( + &lines[5..10], + [ + "%AI17_Begin_Content_if_version_gt:24 12", + "%AI28_BeginPlacedRelativePath", + "(art/)", + "%AI28_EndPlacedRelativePath", + "%AI17_Alternate_Content" + ] + ); + assert_eq!(&lines[11..13], ["%AI17_Begin_Content_if_version_gt:24 5", "%AI26_BeginPlacedObjectPreview"]); + // 3 × 3 pixels of premultiplied ARGB. + assert_eq!(lines[13], "3 3 12 32 17 <36 bytes>"); + assert_eq!(&lines[14..], ["%AI26_EndPlacedObjectPreview", "%AI17_End_Versioned_Content", "~"]); +} + +/// The relative folder goes with the path's file name, so a relative path to a file of another +/// name isn't written. +#[test] +fn a_relative_path_to_a_file_of_another_name_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("/old/original.png"); + link.relative = Some("assets/current.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(!program_shown(&doc).contains("%AI28_BeginPlacedRelativePath")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + let link = im.link.as_ref().unwrap(); + assert_eq!((link.path.as_str(), link.relative.as_deref()), ("/old/original.png", None)); + // Names that differ only in letter case keep the folder where file names ignore case. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\PHOTO.PNG"); + link.relative = Some("art/photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let kept = program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n"); + assert_eq!(kept, cfg!(any(windows, target_os = "macos"))); + // A relative path with `\` separators keeps its folder. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\photo.png"); + link.relative = Some("art\\photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n")); +} + +#[test] +fn a_large_linked_image_has_a_smaller_preview_over_its_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = image::RgbaImage::from_fn(1024, 512, |x, y| image::Rgba([(x / 4) as u8, (y / 2) as u8, 0, 255])); + let xf = Affine::new([0.1, 0.0, 0.0, 0.1, 20.0, 30.0]); + let im = image_node(&mut doc, ImageBlob::png(png_of(big.into())), (1024, 512), xf, Some(vectorcraft_doc::LinkInfo::new("/tmp/big.png"))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("\n256 128 1024 32 17 <131072 bytes>\n")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!((im.width, im.height), (256, 128)); + let bounds = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 256.0, 128.0)); + assert_eq!((r3(bounds.x0), r3(bounds.y0), r3(bounds.x1), r3(bounds.y1)), (r3(20.0), r3(30.0), r3(122.4), r3(81.2))); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("/tmp/big.png")); +} + +/// Samples that hold the bytes of `%%EndData` without a line end after them are read whole. +#[test] +fn samples_holding_the_end_marker_are_read_whole() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // The color samples end `%%En` and the alpha channel starts `dData`. + let rgb = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, b'%'], *b"%En"]; + let alpha = *b"dData"; + let img = image::RgbaImage::from_fn(5, 1, |x, _| { + let [r, g, b] = rgb[x as usize]; + image::Rgba([r, g, b, alpha[x as usize]]) + }); + let im = image_node(&mut doc, ImageBlob::png(png_of(img.into())), (5, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The alpha channel holds the marker, a line end and the operator that follows the samples. + let alpha = *b"%%EndData\r\nXH\r\nZZ"; + let img = image::RgbaImage::from_fn(17, 1, |x, _| image::Rgba([x as u8, 9, 9, alpha[x as usize]])); + let marked = ImageBlob::png(png_of(img.into())); + let im = image_node(&mut doc, marked.clone(), (17, 1), Affine::translate((0.0, 20.0)), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The same image as an opacity mask's art, on `%_` lines. + let art = image_node(&mut doc, marked, (17, 1), Affine::translate((0.0, 40.0)), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 17.0, 41.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let back = read_back(&doc); + assert_eq!(images_of(&back), images_of(&doc)); +} + +/// A preview scaled down mixes no color from pixels that don't show. +#[test] +fn a_smaller_preview_takes_no_color_from_see_through_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let half = image::RgbaImage::from_fn(511, 3, |x, _| if x % 2 == 0 { image::Rgba([255, 0, 0, 0]) } else { image::Rgba([0, 0, 255, 255]) }); + let im = image_node( + &mut doc, + ImageBlob::png(png_of(half.into())), + (511, 3), + Affine::scale(0.2), + Some(vectorcraft_doc::LinkInfo::new("/tmp/half.png")), + ); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!(im.width, 256); + let px = image::load_from_memory(&back.image_blob(im).unwrap().bytes).unwrap().to_rgba8(); + assert!(px.pixels().all(|p| p.0[0] == 0), "{:?}", px.pixels().take(4).collect::>()); + assert!(px.pixels().filter(|p| p.0[3] > 0).count() > 400); +} + +#[test] +fn linked_images_in_masks_and_tiles_are_embedded() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let link = Some(vectorcraft_doc::LinkInfo::new("/tmp/ramp.png")); + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), link); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); + let text = program_shown(&doc); + assert!(!text.contains("BeginPlace") && text.contains("%_%AI5_BeginRaster"), "{text}"); +} + +/// An image in an opacity mask's art inside a pattern's tile is hidden once: its samples end +/// `%_%%EndData`. +#[test] +fn an_image_in_a_mask_in_a_pattern_tile_ends_its_samples_once() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Masked", vec![Arc::new(square)])); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(40.0, 40.0, 100.0, 80.0)), + Appearance::basic(Paint::Pattern { pattern: "Masked".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let text = program_shown(&doc); + assert!(text.contains("XI\n<18 bytes>%_%%EndData\n%_XH\n"), "{text}"); + assert!(!text.contains("%_%_%%EndData"), "{text}"); +} + +#[test] +fn an_image_in_art_cut_to_a_clipping_object_is_clipped_by_that_region() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // Type clips: its art is cut to the glyphs' region, which can't cut an image. + let ring = Node::new( + doc.alloc_id(), + NodeKind::Compound { + children: vec![ + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default())), + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::default())), + ], + rule: FillRule::EvenOdd, + }, + ); + let ring = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring)], clip: false }); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring), Arc::new(im)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert_eq!(found.len(), 1, "{:?}", lines(&back)); + let text = program_shown(&doc); + let at = text.find("%AI5_EndRaster\nN\n").unwrap(); + assert!(text[at..].contains("h\nW\nn\n") && text[..at].contains("q\n"), "{text}"); + // The ring's two subpaths clip as one compound path, not as one cut by the other. + let tail = &text[at..]; + assert!(tail.contains("0 XR\n*u\n") && tail.contains("h\nW\nn\n*U\n"), "{text}"); + fn clipping(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + if let NodeKind::Group { children, clip: true } = &n.kind { + out.extend(children.first().map(|c| match &c.kind { + NodeKind::Path { path, .. } => path.subpaths.len(), + NodeKind::Compound { children, .. } => children.len(), + _ => 0, + })); + } + clipping(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut subpaths = vec![]; + clipping(&back.layers, &mut subpaths); + assert_eq!(subpaths, [2], "{:?}", lines(&back)); +} + +/// Art cut to a region with nothing left in it (two clipping objects that don't overlap) leaves the +/// image out. +#[test] +fn an_image_cut_to_nothing_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let boxed = |doc: &mut Document, r: Rect| { + let p = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + Arc::new(Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(p)], clip: false })) + }; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let far = boxed(&mut doc, Rect::new(50.0, 0.0, 60.0, 10.0)); + let inner = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![far, Arc::new(im)], clip: true }); + let near = boxed(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0)); + let outer = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![near, Arc::new(inner)], clip: true }); + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + assert!(!program_shown(&doc).contains("%AI5_BeginRaster")); +} + +#[test] +fn images_that_cant_be_decoded_are_mid_gray_boxes() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(b"not an image".to_vec()), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); +} + +#[test] +fn sixteen_bit_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let deep = image::ImageBuffer::, Vec>::from_fn(2, 1, |x, _| image::Rgb([65535 * x as u16, 257 * 10, 0])); + let im = image_node(&mut doc, ImageBlob::png(png_of(image::DynamicImage::ImageRgb16(deep))), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert!(found[0].ends_with("rgba [0, 10, 0, 255, 255, 10, 0, 255]"), "{found:?}"); +} + +/// A little-endian, uncompressed CMYK TIFF of 16 bits a sample, `w` × 1 pixels, each pixel's inks +/// `inks[x]`. +fn cmyk16_tiff(inks: &[[u16; 4]]) -> Vec { + let w = inks.len() as u32; + let data: Vec = inks.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + // Tags: width, height, bits (an offset), compression, photometric, strip offset, samples, rows, + // strip bytes, planar configuration. + let bits_at = 8 + 2 + 12 * 10 + 4; + let data_at = bits_at + 8; + let entries: [(u16, u16, u32, u32); 10] = [ + (256, 4, 1, w), + (257, 4, 1, 1), + (258, 3, 4, bits_at), + (259, 3, 1, 1), + (262, 3, 1, 5), + (273, 4, 1, data_at), + (277, 3, 1, 4), + (278, 4, 1, 1), + (279, 4, 1, data.len() as u32), + (284, 3, 1, 1), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&10u16.to_le_bytes()); + for (tag, kind, count, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..4 { + out.extend_from_slice(&16u16.to_le_bytes()); + } + out.extend_from_slice(&data); + out +} + +#[test] +fn sixteen_bit_cmyk_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let blob = ImageBlob::new("image/tiff", cmyk16_tiff(&[[65535, 0, 0, 0], [0, 0x8000, 0, 0x1234]])); + assert!(blob.is_cmyk() && blob.is_cmyk16()); + let im = image_node(&mut doc, blob, (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + assert!(program_shown(&doc).contains("/DeviceCMYK XN\n")); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 99f8cb607d..78602b9391 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -9,29 +9,32 @@ use vectorcraft_color::swatch::{REGISTRATION, Swatch}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, SubPath}; +use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath}; use vectorcraft_pathops::BoolOp; -use crate::ai_ops::{self, average, unit}; +use crate::ai_ops::{self, unit}; use crate::ps; +mod images; +mod paints; + +pub(super) use images::PAYLOAD; +#[cfg(test)] +pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +#[cfg(test)] +pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; + /// How deep symbols, live objects and pattern tiles may nest in one another (deeper art is left /// out). Groups and layers need no limit of their own: a document is never deeper than /// [`vectorcraft_doc::MAX_DEPTH`]. const MAX_NEST: u32 = 8; -/// The side of the image whose pixels are averaged (larger ones are scaled down to it first). -const AVERAGE_SIDE: u32 = 64; -/// Most pixels an image may have to be decoded and averaged (more: mid gray). -const MAX_AVERAGED_PIXELS: u64 = 1 << 24; pub(super) const TYPE: &str = "type is written as its outlines in the editing data for other apps"; -pub(super) const GRADIENTS: &str = "gradients are written as their average color in the editing data for other apps"; -const PATTERNS: &str = "pattern fills are written as their tiles cut to the shape 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 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"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps"; pub(super) const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; @@ -43,7 +46,7 @@ pub(super) const DEEP_MASKS: &str = const GROUPED_LAYER: &str = "the transparency and opacity masks of layers that an effect made into a group are left out of the editing data for other apps"; pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; -const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; +pub(super) const SWATCHES: &str = "freeform gradient swatches, gradient swatches of more than 256 stops, and pattern swatches whose patterns the data can't define, are left out of the editing data for other apps"; pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps"; const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; @@ -127,13 +130,52 @@ pub(super) struct Writer<'a> { brushes: Option>, /// The objects of the symbol art written so far, within [`vectorcraft_doc::MAX_SYMBOL_NODES`]. symbol_nodes: u64, + /// The document → the space gradients' matrices (`Xm`, `Bm`, `Bc`) and focal points are + /// written in: art space, and in a pattern's definition [`Self::tile_grad_space`]. + grad_space: Affine, + /// The pattern's space (y down) → the space a pattern's definition writes gradients' matrices + /// in: the canvas's (y down), from art space's origin there. + tile_grad_space: Affine, + /// The document → the canvas (y down), the space of a gradient's transformation in `Bg`; in a + /// pattern's definition, the pattern's space turned y up. + canvas: Affine, + /// The gradient definitions, in the order they are first used. + gradients: Vec, + /// The number the next new gradient definition's name tries first (1 is `Gradient`). + next_gradient: u64, + /// The pattern definitions written, each after those its art uses. + patterns: Vec, + /// The patterns whose definitions are being written. + defining: Vec, + /// Writing the palette: the definitions it adds are for its swatches only. + in_palette: bool, + /// Art space's origin on the canvas (y down), where a placed file's box starts. + canvas_origin: (f64, f64), + /// The binary parts of the program (images' samples, placed files' previews), each in the + /// text as a mark ([`PAYLOAD`], its index, [`PAYLOAD`]). + pub(super) payloads: Vec>, + /// How many parts of the data written on `%_` lines (opacity masks' art, patterns' tiles) the + /// art being written is in. + hidden: u32, } impl<'a> Writer<'a> { - pub(super) fn new(doc: &'a Document, to_art: Affine) -> Self { + /// A writer of `doc`'s art through `to_art`; `origin` is art space's origin on the canvas. + pub(super) fn new(doc: &'a Document, to_art: Affine, origin: (f64, f64)) -> Self { Self { doc, to_art, + grad_space: to_art, + tile_grad_space: Affine::translate((-origin.0, origin.1)), + canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, + gradients: vec![], + next_gradient: 1, + patterns: vec![], + defining: vec![], + in_palette: false, + canvas_origin: origin, + payloads: vec![], + hidden: 0, cms: vectorcraft_color::cms::active(), body: String::new(), warnings: vec![], @@ -358,12 +400,7 @@ impl<'a> Writer<'a> { } NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), NodeKind::Text(_) => self.text(n, xy), - NodeKind::Image(im) => { - let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); - let color = image_average(self.doc.image_blob(im).map(|b| b.bytes.as_slice())); - self.warn(IMAGES); - self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color)), xy); - } + NodeKind::Image(im) => self.image(im, xy), NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); self.line("u"); @@ -498,19 +535,15 @@ impl<'a> Writer<'a> { _ => std::slice::from_ref(art), }; self.nest += 1; + self.hidden += 1; for c in members { self.node(c); } + self.hidden -= 1; self.nest -= 1; let lines = std::mem::replace(&mut self.body, outer); self.body.push_str("%_/Mask :\n%_X=\n"); - for l in lines.lines() { - if !l.starts_with("%_") { - self.body.push_str("%_"); - } - self.body.push_str(l); - self.body.push('\n'); - } + hide(&lines, &mut self.body); self.body.push_str("%_X+\n%_(Art) ,\n"); for (key, on) in [("Clipping", m.clip), ("Inverted", m.invert), ("Disabled", m.disabled), ("Linked", m.linked)] { let _ = writeln!(self.body, "%_{} /Bool ({key}) ,", u8::from(on)); @@ -560,16 +593,17 @@ impl<'a> Writer<'a> { self.warn_cut(Some(first)); return self.clip_contents(children); }; - let painted = plain_paint(first); - if visible_items(first).iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + let items = self.items(first, path.to_bezpath().bounding_box()); + let painted = self.plain_paint(&items); + if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { self.warn(ITEM_TRANSPARENCY); } // Paint the clipping path can't carry: its fills under the others, its strokes over them. let (fills, strokes): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) = - if painted.is_none() { visible_items(first).into_iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; + if painted.is_none() { items.iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; if painted.is_none() { self.warn(CLIP_PAINT); - if first.extras().mask.is_some() && !visible_items(first).is_empty() { + if first.extras().mask.is_some() && !items.is_empty() { self.warn(CLIP_PAINT_MASKS); } } @@ -588,10 +622,13 @@ impl<'a> Writer<'a> { if several { self.line("*u"); } - for sp in subpaths { + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { ai_ops::subpath(&mut self.body, self.to_art, sp); - let op = if sp.closed { op } else { op.to_ascii_uppercase() }; - let _ = writeln!(self.body, "{}\nW\n{op}", if sp.closed { 'h' } else { 'H' }); + let _ = writeln!(self.body, "{}\nW", if sp.closed { 'h' } else { 'H' }); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), true, &outline); } if several { self.line("*U"); @@ -658,11 +695,11 @@ impl<'a> Writer<'a> { if path.is_empty() { return; } - let items = visible_items(n); + let items = self.items(n, path.to_bezpath().bounding_box()); if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { self.warn(ITEM_TRANSPARENCY); } - match (plain_paint(n), items.as_slice()) { + match (self.plain_paint(&items), items.as_slice()) { (Some((fill, stroke)), _) => self.path_object(path, rule, fill, stroke, xy), (None, [one]) => self.item(path, rule, one, xy), (None, items) => { @@ -679,7 +716,7 @@ impl<'a> Writer<'a> { fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem, xy: Xy) { match item { AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy), - AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), + AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), AppearanceItem::Stroke(s) => { self.warn(STROKES); if self.brush_art(path, s, xy) { @@ -716,15 +753,17 @@ impl<'a> Writer<'a> { true } - /// A fill as an object of its own, of transparency `xy`: a gradient as its average color, a - /// pattern as its tiles cut to the path. + /// A fill as an object of its own, of transparency `xy`: a color, a placed gradient or a + /// pattern the data can define as the path's fill, another pattern as its tiles cut to the path. fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, xy: Xy) { + if !matches!(f.paint, Paint::None) && self.direct(&f.paint) { + return self.path_object(path, rule, Some(f), None, xy); + } match &f.paint { - Paint::Solid { .. } => self.path_object(path, rule, Some(f), None, xy), - Paint::Gradient(g) => { - self.warn(GRADIENTS); - let flat = FillLayer { paint: Paint::solid(average(&g.gradient)), ..f.clone() }; - self.path_object(path, rule, Some(&flat), None, xy); + // A gradient not placed yet: placed on the path, or its average color. + Paint::Solid { .. } | Paint::Gradient(_) => { + let flat = self.placed(&f.paint, path.to_bezpath().bounding_box()); + self.path_object(path, rule, Some(&FillLayer { paint: flat, ..f.clone() }), None, xy); } Paint::Pattern { pattern, xf } => { self.warn(PATTERNS); @@ -826,11 +865,13 @@ impl<'a> Writer<'a> { if several { self.line("*u"); } - for sp in subpaths { + // A gradient's instance paints the last subpath; the compound path takes its paint. + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { ai_ops::subpath(&mut self.body, self.to_art, sp); - let op = if sp.closed { op } else { op.to_ascii_uppercase() }; - self.body.push(op); - self.body.push('\n'); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), false, &outline); } if several { self.line("*U"); @@ -899,11 +940,15 @@ impl<'a> Writer<'a> { // ---------- color ---------- - /// Set the fill (or with `stroke`, the stroke) color to solid paint `p`: a spot or global - /// swatch by its name, Registration, else the color itself. + /// Set the fill (or with `stroke`, the stroke) to paint `p`: a spot or global swatch by its + /// name, Registration, the color itself, or a pattern ([`Self::pattern_paint`]). A gradient sets + /// nothing: its instance paints ([`Self::painted`]). fn color(&mut self, p: &Paint, stroke: bool) { - let Paint::Solid { color, swatch, tint } = p else { - return self.plain_color(Color::gray(1.0), stroke); + let (color, swatch, tint) = match p { + Paint::Solid { color, swatch, tint } => (color, swatch, tint), + Paint::Pattern { pattern, xf } => return self.pattern_paint(pattern, *xf, stroke), + Paint::Gradient(_) => return, + Paint::None => return self.plain_color(Color::gray(1.0), stroke), }; if swatch.as_deref() == Some(REGISTRATION) { let mut s = String::from("1 1 1 1 "); @@ -989,6 +1034,7 @@ impl<'a> Writer<'a> { /// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`, /// `%AI5_EndPalette`. pub(super) fn palette(&mut self, s: &mut String) { + self.in_palette = true; s.push_str("%AI5_BeginPalette\n0 0 Pb\n"); self.registration_cell(s); let doc = self.doc; @@ -996,13 +1042,13 @@ impl<'a> Writer<'a> { self.swatch(s, sw); } for g in doc.swatch_groups.iter() { - let colors: Vec<&Swatch> = g.swatches.iter().filter(|sw| writable(sw)).collect(); - let _ = writeln!(s, "0 {} {} Pg", ps::bytes(g.name.as_bytes()), colors.len()); - for sw in &g.swatches { - self.swatch(s, sw); - } + let mut cells = String::new(); + let count = g.swatches.iter().filter(|sw| self.swatch(&mut cells, sw)).count(); + let _ = writeln!(s, "0 {} {count} Pg", ps::bytes(g.name.as_bytes())); + s.push_str(&cells); } s.push_str("PB\n%AI5_EndPalette\n"); + self.in_palette = false; } /// The Registration swatch, which every palette in the files users sent starts with: in a @@ -1021,24 +1067,31 @@ impl<'a> Writer<'a> { let _ = writeln!(s, "{name} Pc"); } - /// One swatch of the palette: a color swatch's color and `(name) Pc`; gradient and pattern - /// swatches are left out. - fn swatch(&mut self, s: &mut String, sw: &Swatch) { + /// One swatch of the palette: a color swatch's color, a gradient swatch's or pattern swatch's + /// paint ([`Self::swatch_paint`]), then `(name) Pc`. False when it isn't written: Registration + /// (written first), the None swatch, and paint the data can't hold (with a warning). + fn swatch(&mut self, s: &mut String, sw: &Swatch) -> bool { if sw.name == REGISTRATION || matches!(sw.paint, Paint::None) { - return; + return false; } - if !writable(sw) { - return self.warn(SWATCHES); - } - let Paint::Solid { color, swatch, .. } = &sw.paint else { return }; - if swatch.is_none() && (sw.global || sw.spot) { - self.named(s, &sw.name, *color, 1.0, sw.spot, false); - } else { - let body = std::mem::take(&mut self.body); - self.plain_color(*color, false); - s.push_str(&std::mem::replace(&mut self.body, body)); + match &sw.paint { + Paint::Solid { color, swatch, .. } => { + if swatch.is_none() && (sw.global || sw.spot) { + self.named(s, &sw.name, *color, 1.0, sw.spot, false); + } else { + let body = std::mem::take(&mut self.body); + self.plain_color(*color, false); + s.push_str(&std::mem::replace(&mut self.body, body)); + } + } + _ if self.swatch_paint(s, sw) => {} + _ => { + self.warn(SWATCHES); + return false; + } } let _ = writeln!(s, "{} Pc", ps::bytes(sw.name.as_bytes())); + true } /// The spot color swatches, with their full colors' CMYK equivalents, for the header. @@ -1057,14 +1110,12 @@ impl<'a> Writer<'a> { } } -/// Is `sw` a color swatch the palette writes? -fn writable(sw: &Swatch) -> bool { - matches!(sw.paint, Paint::Solid { .. }) && sw.name != REGISTRATION -} - -/// Does a plain line of one color draw `s` (the line style operators can write it)? -fn direct_stroke(s: &StrokeLayer) -> bool { - matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) +/// The gradient of paint `p`, when it has one. +fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> { + match p { + Some(Paint::Gradient(g)) => Some(g), + _ => None, + } } /// `n`'s fills and strokes that paint. @@ -1079,19 +1130,6 @@ fn visible_items(n: &Node) -> Vec<&AppearanceItem> { .collect() } -/// `n`'s paint as one path object paints: no paint, a fill of a color, a plain line of a color, -/// or both, the line over the fill; `None` when it has other paint. -fn plain_paint(n: &Node) -> Option<(Option<&FillLayer>, Option<&StrokeLayer>)> { - let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); - match visible_items(n).as_slice() { - [] => Some((None, None)), - [AppearanceItem::Fill(f)] if solid(&f.paint) => Some((Some(f), None)), - [AppearanceItem::Stroke(s)] if direct_stroke(s) => Some((None, Some(s))), - [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => Some((Some(f), Some(s))), - _ => None, - } -} - /// The painting operator of a closed subpath (§5.3.3): `b` fill and stroke, `f` fill, `s` /// stroke, `n` neither; an open one's is upper case. fn paint_op(fill: bool, stroke: bool) -> char { @@ -1124,42 +1162,43 @@ fn clip_path(n: &Node) -> Option<(PathData, FillRule)> { path.subpaths.iter().any(|sp| !sp.anchors.is_empty()).then_some((path, rule)) } -/// The image `bytes` decoded, when its header gives at most [`MAX_AVERAGED_PIXELS`] pixels; the -/// decoder may allocate at most 8 bytes a pixel. -fn decode_bounded(bytes: &[u8]) -> Option { +/// `text`'s lines on `%_` lines, as a part of the data that readers of the printed form skip (an +/// opacity mask's art, a pattern's tile) has them. An image's samples stay as they are after an +/// `XI` without `%_`, and `%_%%EndData` ends them, as in the files users sent. Samples hidden +/// already (an opacity mask's art in a pattern's tile) keep their one `%_`. +pub(super) fn hide(text: &str, out: &mut String) { + for l in text.lines() { + if l.starts_with(images::SAMPLES_LINE) { + match l.strip_suffix("%%EndData") { + Some(samples) if !samples.ends_with("%_") => { + out.push_str(samples); + out.push_str("%_%%EndData"); + } + _ => out.push_str(l), + } + } else { + if !l.starts_with("%_") { + out.push_str("%_"); + } + out.push_str(l); + } + out.push('\n'); + } +} + +/// The image `bytes` decoded, when its header gives at most `max` pixels; the decoder may allocate +/// at most 8 bytes a pixel. +fn decode_bounded(bytes: &[u8], max: u64) -> Option { let reader = || -> image::ImageResult>> { let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; let mut limits = image::Limits::default(); - limits.max_alloc = Some(MAX_AVERAGED_PIXELS * 8); + limits.max_alloc = Some(max * 8); r.limits(limits); Ok(r) }; let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?; - if u64::from(w) * u64::from(h) > MAX_AVERAGED_PIXELS { + if u64::from(w) * u64::from(h) > max { return None; } reader().and_then(|r| r.decode()).ok() } - -/// The average color of the image `bytes` (scaled down first), transparent pixels over white; -/// mid gray when it can't be decoded or has more than [`MAX_AVERAGED_PIXELS`] pixels. -fn image_average(bytes: Option<&[u8]>) -> Color { - let Some(img) = bytes.and_then(decode_bounded) else { return Color::gray(0.5) }; - let img = if img.width() > AVERAGE_SIDE || img.height() > AVERAGE_SIDE { img.thumbnail(AVERAGE_SIDE, AVERAGE_SIDE) } else { img }; - let rgba = img.to_rgba8(); - let mut sum = [0u64; 3]; - let mut n = 0u64; - for px in rgba.pixels() { - let [r, g, b, a] = px.0; - let over = |c: u8| (u64::from(c) * u64::from(a) + 255 * (255 - u64::from(a))) / 255; - sum[0] += over(r); - sum[1] += over(g); - sum[2] += over(b); - n += 1; - } - if n == 0 { - return Color::gray(0.5); - } - let c = |v: u64| (v as f32 / n as f32 / 255.0).clamp(0.0, 1.0); - Color::rgb(c(sum[0]), c(sum[1]), c(sum[2])) -} diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs new file mode 100644 index 0000000000..6ef2ccaa3a --- /dev/null +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -0,0 +1,326 @@ +//! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview +//! (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{FillLayer, ImageBlob, ImageObject, LinkInfo}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape}; + +use super::{Writer, Xy}; +use crate::ps; + +pub(in crate::ai_editing) const IMAGES: &str = "images that can't be decoded or have more than 33,554,432 pixels are written as their outlines filled mid gray in the editing data for other apps"; +pub(in crate::ai_editing) const IMAGE_DEPTH: &str = "images of 16 bits a channel are written at 8 bits a channel in the editing data for other apps"; +pub(in crate::ai_editing) const LINKS_EMBEDDED: &str = + "linked images in opacity masks and pattern tiles are written as embedded images in the editing data for other apps"; + +/// The most pixels an image is written with: as many as the reader reads. +pub(super) const MAX_PIXELS: u64 = 1 << 25; +/// The longer side of a placed file's preview at most (a smaller image's preview is its own +/// pixels): the files users sent have previews 256 pixels wide. +const PREVIEW_SIDE: u32 = 256; +/// What marks a binary payload in the program text: `\u{1}`, its index, `\u{1}` +/// ([`super::super::splice`] puts the bytes in its place). Strings never hold the byte unescaped. +pub(in crate::ai_editing) const PAYLOAD: char = '\u{1}'; +/// What starts the line of an image's samples: `XI` and its payload, then `%%EndData`. +pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; + +/// An image's pixels as the data holds them. +struct Samples { + /// `/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`. + space: &'static str, + /// The image type of `XI` (§8.1): 1 gray, 3 RGB, 4 CMYK. + kind: u8, + width: u32, + height: u32, + /// The color samples, 8 bits each, rows from the top. + color: Vec, + /// The alpha channel, a byte a pixel, when a pixel isn't opaque. + alpha: Option>, +} + +impl Samples { + /// The pixels of `blob`: a CMYK image's ink amounts, else gray samples when every pixel is gray + /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than + /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. + fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + // The header's size is checked before the inks are decoded. + if blob.is_cmyk() + && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) + && let Some(inks) = blob.cmyk() + && u64::from(inks.width) * u64::from(inks.height) <= MAX_PIXELS + { + let s = Samples { space: "/DeviceCMYK", kind: 4, width: inks.width, height: inks.height, color: inks.data, alpha: None }; + return Some((s, blob.is_cmyk16())); + } + let img = super::decode_bounded(&blob.bytes, MAX_PIXELS)?; + let deep = matches!( + img.color(), + image::ColorType::L16 + | image::ColorType::La16 + | image::ColorType::Rgb16 + | image::ColorType::Rgba16 + | image::ColorType::Rgb32F + | image::ColorType::Rgba32F + ); + let rgba = img.to_rgba8(); + // Gray when every pixel is, whatever the file's color type (an image read back from the data + // is RGBA): the same pixels are written the same way. + let gray = rgba.pixels().all(|p| p.0[0] == p.0[1] && p.0[1] == p.0[2]); + let (width, height) = rgba.dimensions(); + if width == 0 || height == 0 { + return None; + } + let opaque = rgba.pixels().all(|p| p.0[3] == 255); + let alpha = (!opaque).then(|| rgba.pixels().map(|p| p.0[3]).collect()); + let color = if gray { rgba.pixels().map(|p| p.0[0]).collect() } else { rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect() }; + let (space, kind) = if gray { ("/DeviceGray", 1) } else { ("/DeviceRGB", 3) }; + Some((Samples { space, kind, width, height, color, alpha }, deep)) + } + + /// `XI`'s fourth flag as the files users sent have it: 0 gray, 1 RGB, 2 CMYK, 16 more with an + /// alpha channel. + fn reserved(&self) -> u8 { + let space = match self.kind { + 1 => 0, + 4 => 2, + _ => 1, + }; + space + if self.alpha.is_some() { 16 } else { 0 } + } +} + +impl Writer<'_> { + /// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a + /// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on + /// `%_` lines. One whose pixels can't be read is its outline filled mid gray. Where the art is + /// cut to a clipping path, the image is in a clipping group of that path. + pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) { + let doc = self.doc; + let Some((samples, deep)) = doc.image_blob(im).and_then(Samples::of) else { + let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); + self.warn(IMAGES); + return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + }; + // A region that has nothing left hides the image. + if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) { + return; + } + if deep { + self.warn(IMAGE_DEPTH); + } + let cut = self.clip.take(); + let at_q = (self.state, self.gs); + if cut.is_some() { + self.line("q"); + } + self.set_xy(xy.object()); + // The object places the image's own pixel grid (its width × height) wherever the file's is. + let fit = + Affine::scale_non_uniform(f64::from(im.width.max(1)) / f64::from(samples.width), f64::from(im.height.max(1)) / f64::from(samples.height)); + match &im.link { + Some(link) if self.hidden == 0 => self.placed_file(link, &samples, (im.width.max(1), im.height.max(1)), im.xf), + other => { + if other.is_some() { + self.warn(LINKS_EMBEDDED); + } + self.raster(&samples, im.xf * fit); + } + } + if let Some(region) = &cut { + self.line("0 XR"); + // Several subpaths clip as one compound path (`*u` … `*U`), as a clipping group's do. + let subpaths: Vec<_> = region.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in subpaths { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + self.line("h\nW\nn"); + } + if several { + self.line("*U"); + } + (self.state, self.gs) = at_q; + self.end_group("Q", Xy::PLAIN); + } + self.clip = cut; + } + + /// An embedded image whose pixels `xf` places in the document: `%AI5_File:`, + /// `%AI5_BeginRaster`, `() 1 XG` (no file), the color space `XN`, `[matrix] w h 0 Xh`, + /// `[matrix] 0 0 w h w h 8 type alpha reserved 1 0 4 4 0 0`, `%%BeginData:` counting `XI`, its + /// line end and the color samples, `XI`, the color samples then the alpha channel in binary, + /// `%%EndData`, `XH`, `%AI5_EndRaster`, `N`. The matrix is an art-space matrix applied to the + /// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix. + fn raster(&mut self, s: &Samples, xf: Affine) { + let m = matrix(self.to_art * xf * Affine::FLIP_Y); + let (w, h) = (s.width, s.height); + let alpha = u8::from(s.alpha.is_some()); + let mut payload = Vec::with_capacity(2 + s.color.len() + s.alpha.as_ref().map_or(0, Vec::len)); + payload.extend_from_slice(b"\r\n"); + payload.extend_from_slice(&s.color); + if let Some(a) = &s.alpha { + payload.extend_from_slice(a); + } + let mark = self.payload(payload); + let _ = writeln!( + self.body, + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n{} XN\n{m} {w} {h} 0 Xh\n{m} 0 0 {w} {h} {w} {h} 8 {} {alpha} {} 1 0 4 4 0 0\n%%BeginData: {}\nXI{mark}%%EndData\nXH\n%AI5_EndRaster\nN", + s.space, + s.kind, + s.reserved(), + // `XI`, CR LF. + 4 + s.color.len(), + ); + } + + /// A linked image whose pixels `xf` places in the document: `%AI5_BeginPlace`, + /// `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and the file's path with `` ` ``, + /// `%%IncludeFile:` and the path, the folder relative to the document's between + /// `%AI28_BeginPlacedRelativePath` and its end (`()` for the document's own folder), the preview between + /// `%AI26_BeginPlacedObjectPreview` and its end (`w h rowBytes 32 17 ` and rows of + /// premultiplied ARGB, the top one first, of the pixels `s`), `~`, `%AI5_EndPlace`. The box is + /// as large as the file has pixels (`w` × `h`, the object's pixel grid, which `xf` places in the + /// document), at art space's origin on the canvas (y down); the matrix takes it from there into + /// art space. Each marked part newer releases read is in versioned content, as in the files + /// users sent. + fn placed_file(&mut self, link: &LinkInfo, s: &Samples, (w, h): (u32, u32), xf: Affine) { + let (x, y) = self.canvas_origin; + let m = matrix(self.to_art * xf * Affine::translate((-x, -y))); + let (w, h) = (f64::from(w), f64::from(h)); + let path = ps::bytes(link.path.as_bytes()); + let _ = write!(self.body, "%AI5_BeginPlace\n%%FileType: 1\n{m} "); + ps::push_nums(&mut self.body, &[x, y, x + w, y + h, 4.0, 4.0, 0.0]); + self.body.pop(); + let _ = writeln!(self.body, "\n{path}`"); + if !link.path.chars().any(char::is_control) { + let _ = writeln!(self.body, "%%IncludeFile:{}", link.path); + } + // The section holds a folder only, the file's name comes from the path: a relative path to a + // file of another name isn't written. On Windows and macOS, whose file names ignore letter + // case, names that differ only in case are the same file. + let same_name = |r: &&str| r.rsplit(['/', '\\']).next().is_some_and(|n| same_file_name(n, link.name())); + if let Some(folder) = link.relative.as_deref().filter(same_name).map(relative_folder) { + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n{}\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content", + ps::bytes(folder.as_bytes()) + ); + } + let (pw, ph, rows) = preview(s); + let mark = self.payload(rows); + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n{pw} {ph} {} 32 17 {mark}\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace", + pw * 4 + ); + } + + /// Keep `bytes` to go in the program where the mark this returns is. + fn payload(&mut self, bytes: Vec) -> String { + self.payloads.push(bytes); + format!("{PAYLOAD}{}{PAYLOAD}", self.payloads.len() - 1) + } +} + +/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four). +fn matrix(m: Affine) -> String { + let n: Vec = m.as_coeffs().iter().map(|v| precise(*v)).collect(); + format!("[{}]", n.join(" ")) +} + +/// `v` rounded to ten decimals, without trailing zeros (0 when not finite). +fn precise(v: f64) -> String { + let r = (v * 1e10).round() / 1e10; + if !r.is_finite() { + return if v.is_finite() { format!("{}", v + 0.0) } else { "0".into() }; + } + format!("{}", r + 0.0) +} + +/// The folder of a path relative to the document's (`src/checker.png` → `src/`); empty when the file +/// is in the document's own folder. `\` separators are read as `/`. +fn relative_folder(relative: &str) -> String { + match relative.replace('\\', "/").rsplit_once('/') { + Some((folder, _)) if !folder.is_empty() => format!("{folder}/"), + _ => String::new(), + } +} + +/// Do file names `a` and `b` name the same file in one folder: equal, or on Windows and macOS equal +/// but for letter case? +fn same_file_name(a: &str, b: &str) -> bool { + a == b || (cfg!(any(windows, target_os = "macos")) && a.to_lowercase() == b.to_lowercase()) +} + +/// A placed file's preview of `s`: its width, height and rows of premultiplied ARGB, the top one +/// first; the image's own pixels when neither side is longer than [`PREVIEW_SIDE`], else scaled +/// down to it, each preview pixel the average of the premultiplied pixels it covers. +fn preview(s: &Samples) -> (u32, u32, Vec) { + let (w, h) = (u64::from(s.width), u64::from(s.height)); + let longer = s.width.max(s.height); + let (pw, ph) = if longer > PREVIEW_SIDE { + let k = f64::from(PREVIEW_SIDE) / f64::from(longer); + let side = |v: u32| ((f64::from(v) * k).round() as u32).clamp(1, PREVIEW_SIDE); + (side(s.width), side(s.height)) + } else { + (s.width, s.height) + }; + let n = usize::from(channels(s.kind)); + let cmyk_memo = std::cell::RefCell::new(std::collections::HashMap::new()); + // Pixel `i` premultiplied: r, g, b, a. + let pixel = |i: usize| -> [u64; 4] { + let c = |k: usize| s.color.get(i * n + k).copied().unwrap_or(0); + let rgb = match s.kind { + 1 => [c(0); 3], + 4 => { + let mut memo = cmyk_memo.borrow_mut(); + if memo.len() > 1 << 16 { + memo.clear(); + } + *memo.entry([c(0), c(1), c(2), c(3)]).or_insert_with(|| { + let f = |v: u8| f32::from(v) / 255.0; + let [r, g, b, _] = Color::cmyk(f(c(0)), f(c(1)), f(c(2)), f(c(3))).to_rgba8(1.0); + [r, g, b] + }) + } + _ => [c(0), c(1), c(2)], + }; + let a = u64::from(s.alpha.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(255)); + let pre = |v: u8| (u64::from(v) * a + 127) / 255; + [pre(rgb[0]), pre(rgb[1]), pre(rgb[2]), a] + }; + let (pw64, ph64) = (u64::from(pw), u64::from(ph)); + let mut rows = Vec::with_capacity((pw64 * ph64 * 4) as usize); + for py in 0..ph64 { + let (y0, y1) = (py * h / ph64, ((py + 1) * h / ph64).max(py * h / ph64 + 1)); + for px in 0..pw64 { + let (x0, x1) = (px * w / pw64, ((px + 1) * w / pw64).max(px * w / pw64 + 1)); + let mut sum = [0u64; 4]; + for y in y0..y1.min(h) { + for x in x0..x1.min(w) { + let p = pixel((y * w + x) as usize); + for (t, v) in sum.iter_mut().zip(p) { + *t += v; + } + } + } + let count = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1); + let [r, g, b, a] = sum.map(|t| ((t + count / 2) / count).min(255) as u8); + rows.extend_from_slice(&[a, r, g, b]); + } + } + (pw, ph, rows) +} + +/// The samples a pixel of image type `kind` has. +fn channels(kind: u8) -> u8 { + match kind { + 1 => 1, + 4 => 4, + _ => 3, + } +} diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs new file mode 100644 index 0000000000..d805d9d0e5 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -0,0 +1,565 @@ +//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the +//! pattern operators (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::gradient::GradientGeom; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; + +use super::{MAX_NEST, Writer, Xy}; +use crate::ai_ops::{average, unit}; +use crate::ps; + +pub(in crate::ai_editing) const GRADIENTS: &str = + "freeform gradients, and gradients along or across strokes, are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str = + "the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_MIX: &str = + "gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps"; +pub(in crate::ai_editing) const STOP_LINKS: &str = + "gradient stops linked to global process colors are written as their colors in the editing data for other apps"; +/// The length of a linear gradient's caps (`Bc`): the canvas's side. +const CAP: f64 = super::super::CANVAS_SIZE as f64; + +/// A gradient definition: its name, its gradient, whether it is a gradient swatch's (named after +/// the swatch) and whether the art uses it (else only the palette does). +pub(super) struct GradientDef { + name: String, + gradient: Gradient, + swatch: bool, + used: bool, +} + +/// A pattern definition written: its name, its text (`%AI3_BeginPattern` to `%AI3_EndPattern`) +/// and whether the art uses it. +pub(super) struct PatternOut { + name: String, + text: String, + used: bool, +} + +/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai` +/// reader reads)? +fn writable_gradient(g: &Gradient) -> bool { + g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS +} + +/// The first name of `Gradient`, `Gradient 2`, `Gradient 3`, … numbered `next` or higher for +/// which `taken` returns false (`Gradient` is number 1); `next` is set past it. +pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl FnMut(&str) -> bool) -> String { + loop { + let name = if *next <= 1 { String::from("Gradient") } else { format!("Gradient {next}") }; + *next = next.saturating_add(1); + if !taken(&name) { + return name; + } + } +} + +/// The stops of `g` in order of their place on the ramp. +fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> { + let mut stops: Vec<&GradientStop> = g.stops.iter().collect(); + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + stops +} + +impl Writer<'_> { + /// Each gradient swatch's definition, named after the swatch, before the art is written. + pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) { + let doc = self.doc; + for sw in doc.swatches_iter() { + if let Paint::Gradient(g) = &sw.paint + && writable_gradient(&g.gradient) + && !self.gradients.iter().any(|d| d.name == sw.name) + { + self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false }); + } + } + } + + /// The name of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else a definition of the same gradient that no swatch names, else a + /// new one ([`free_gradient_name`]: `Gradient`, numbered when taken by another definition, a + /// swatch or a pattern). + fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { + let used = !self.in_palette; + let found = swatch + .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) + .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); + if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + d.used |= used; + return d.name.clone(); + } + let (doc, gradients) = (self.doc, &self.gradients); + let name = free_gradient_name(&mut self.next_gradient, |name| { + gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() + }); + self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); + name + } + + /// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is + /// placed there (it then no longer depends on the shape it paints, which may be cut); one the + /// data can't hold is its average color, with a warning. + pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint { + let Paint::Gradient(g) = p else { return p.clone() }; + let geom = g.resolve(bounds); + let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite()); + let radial = g.gradient.kind == GradientKind::Radial; + if g.gradient.kind == GradientKind::Freeform { + self.warn(GRADIENTS); + return Paint::solid(average(&g.gradient)); + } + if !writable_gradient(&g.gradient) || !finite || geom.length() < 1e-9 || (radial && geom.aspect <= 1e-9) { + self.warn(GRADIENT_SHAPES); + return Paint::solid(average(&g.gradient)); + } + Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })) + } + + /// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed + /// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient + /// along or across a stroke is its average color (the stroke is written as its outline). + pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec { + super::visible_items(n) + .into_iter() + .map(|i| match i { + AppearanceItem::Fill(f) => AppearanceItem::Fill(FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() }), + AppearanceItem::Stroke(s) => { + let paint = match s.path_gradient() { + Some(g) => { + self.warn(GRADIENTS); + Paint::solid(average(&g.gradient)) + } + None => self.placed(&s.paint, s.paint_bounds(bounds)), + }; + AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() }) + } + }) + .collect() + } + + /// Can paint `p` be written as the paint of a path object: a color, a placed gradient, or a + /// pattern [`Self::pattern_writable`]? + pub(super) fn direct(&self, p: &Paint) -> bool { + match p { + Paint::Solid { .. } => true, + Paint::Gradient(g) => g.geom.is_some() && writable_gradient(&g.gradient), + Paint::Pattern { pattern, .. } => self.pattern_writable(pattern), + Paint::None => false, + } + } + + /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can + /// write it)? + pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { + self.direct(&s.paint) && stroke::is_plain(s) + } + + /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the + /// line over the fill; `None` when it has other paint. + pub(super) fn plain_paint<'i>(&self, items: &'i [AppearanceItem]) -> Option<(Option<&'i FillLayer>, Option<&'i StrokeLayer>)> { + match items { + [] => Some((None, None)), + [AppearanceItem::Fill(f)] if self.direct(&f.paint) => Some((Some(f), None)), + [AppearanceItem::Stroke(s)] if self.direct_stroke(s) => Some((None, Some(s))), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if self.direct(&f.paint) && self.direct_stroke(s) => Some((Some(f), Some(s))), + _ => None, + } + } + + /// The painting operator `op` of a subpath (`closed` or open), with the gradient instances of + /// the fill (`fill`) and the stroke (`stroke`) around it when it is the last subpath of its + /// object: `Bb` … `op` `flag BB`, the stroke's `1 Bb` … after the fill's `BB`; the flag is 0, or + /// with a stroke 2 (closed) or 1 (open). `stroked`: the object has a stroke. A clipping path's + /// instances (`clip`) don't issue a clip of their own. `path`: the path the operator paints (all + /// its subpaths), in the document. + pub(super) fn painted( + &mut self, + op: char, + closed: bool, + gradients: (Option<&GradientPaint>, Option<&GradientPaint>), + stroked: bool, + clip: bool, + path: &BezPath, + ) { + let op = if closed { op } else { op.to_ascii_uppercase() }; + let flag = match (stroked, closed) { + (false, _) => "0 BB", + (true, true) => "2 BB", + (true, false) => "1 BB", + }; + let (fill, stroke) = gradients; + if let Some(f) = fill { + self.instance(f, false, clip, path); + if stroke.is_some() { + self.line(if closed { "2 BB" } else { "1 BB" }); + } + } + if let Some(s) = stroke { + self.instance(s, true, clip, path); + } + self.body.push(op); + self.body.push('\n'); + if fill.is_some() || stroke.is_some() { + self.line(flag); + } + } + + /// A gradient instance's start (placed gradient `g`, on the stroke when `stroke`, on `path` in + /// the document), before its painting operator: `Bb` (`1 Bb` on the stroke); a radial + /// gradient's focal point `x y angle fraction Bh` (its offset from the center in the space of the + /// gradient's matrices, then its angle and fraction as [`placement`] gives them; `0 0 0 0 Bh` at + /// the center); `flag (name) x y angle length a b c d tx ty 1 Bg` (flag 1, or 0 for a clipping + /// path; the rest as [`placement`] gives them); then the gradient's place: a linear one's `a b c d tx ty Xm` (the + /// unit vector onto its whole ramp), its cap before the first stop `… Bc`, a `… Bm` for each pair + /// of stops next to each other (the unit vector onto the part between them) and its cap past the + /// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse). + fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) { + let Some(geom) = g.geom else { return }; + let name = self.define_gradient(&g.gradient, g.swatch.as_deref()); + self.line(if stroke { "1 Bb" } else { "Bb" }); + let m = self.grad_space; + let u = geom.end - geom.start; + let radial = g.gradient.kind == GradientKind::Radial; + let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas); + if radial { + let c = m * geom.start; + let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c); + let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) }; + let off = if fraction > 0.0 { off } else { Vec2::ZERO }; + ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]); + self.line("Bh"); + } + let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes())); + ps::push_nums(&mut self.body, &place.bg); + ps::push_nums(&mut self.body, &place.transform.as_coeffs()); + self.line("1 Bg"); + // The unit vector along the gradient, and across it as long. + let frame = |from: f64, to: f64| { + let p = geom.start + u * from; + m * Affine::new([u.x * (to - from), u.y * (to - from), -u.y, u.x, p.x, p.y]) + }; + let mut matrix = |a: Affine, op: &str| { + ps::push_nums(&mut self.body, &a.as_coeffs()); + self.body.push_str(op); + self.body.push('\n'); + }; + if radial { + matrix(m * geom.unit_frame().unwrap_or(Affine::new([u.x, u.y, -u.y, u.x, geom.start.x, geom.start.y])), "Bm"); + return; + } + matrix(frame(0.0, 1.0), "Xm"); + let offsets: Vec = sorted_stops(&g.gradient).iter().map(|s| f64::from(s.offset)).collect(); + let len = u.hypot().max(1e-9); + let (first, last) = (offsets.first().copied().unwrap_or(0.0), offsets.last().copied().unwrap_or(1.0)); + matrix(frame(first - CAP / len, first), "Bc"); + for pair in offsets.windows(2) { + if let [a, b] = pair { + matrix(frame(*a, *b), "Bm"); + } + } + matrix(frame(last, last + CAP / len), "Bc"); + } + + /// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear, + /// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a + /// linear gradient's from the last to the first and a radial one's from the first to the last, + /// `BD`, `%AI5_EndGradient`. + fn gradient_def(&mut self, s: &mut String, d: &GradientDef) { + if d.gradient.dither || !d.gradient.method.is_classic() { + self.warn(GRADIENT_MIX); + } + let name = ps::bytes(d.name.as_bytes()); + let radial = d.gradient.kind == GradientKind::Radial; + let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len()); + let mut stops = sorted_stops(&d.gradient); + if !radial { + stops.reverse(); + } + for stop in stops { + s.push_str("%_"); + self.stop_color(s, stop); + ps::push_nums(s, &[f64::from(unit(stop.opacity)), 6.0, f64::from(stop.midpoint) * 100.0, f64::from(stop.offset) * 100.0]); + s.push_str("Bs\n"); + } + s.push_str("BD\n%AI5_EndGradient\n"); + } + + /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) + /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, + /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). + fn stop_color(&mut self, s: &mut String, stop: &GradientStop) { + let doc = self.doc; + let intent = self.cms.settings().intent; + if let Some(name) = stop.swatch.as_deref().filter(|n| *n != REGISTRATION) + && let Some(sw) = doc.swatch(name) + && let Paint::Solid { color: full, swatch: None, .. } = sw.paint + { + if sw.spot { + let cmyk = self.cms.to_cmyk(&doc.linked_color(full, true), intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let rgb = !matches!(full, Color::Cmyk { .. }); + if rgb { + ps::push_nums(s, &full.to_rgb().map(|v| f64::from(unit(v)))); + } + s.push_str(&ps::bytes(name.as_bytes())); + s.push(' '); + ps::push_num(s, f64::from(1.0 - unit(stop.tint))); + s.push_str(if rgb { " 1 4 " } else { " 3 " }); + return; + } + if sw.global { + self.warn(STOP_LINKS); + } + } + match stop.color { + Color::Gray { k } => { + ps::push_num(s, f64::from(1.0 - unit(k))); + s.push_str(" 0 "); + } + Color::Cmyk { c, m, y, k } => { + ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v)))); + s.push_str("1 "); + } + color @ (Color::Rgb { .. } | Color::Lab { .. }) => { + let cmyk = self.cms.to_cmyk(&color, intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + s.push_str("2 "); + } + } + } + + // ---------- patterns ---------- + + /// Can pattern `name` be written as a definition and painted with from here: the document has + /// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used + /// in another pattern's tile or nested more than [`MAX_NEST`] deep? + pub(super) fn pattern_writable(&self, name: &str) -> bool { + if !self.defining.is_empty() || self.nest >= MAX_NEST { + return false; + } + if self.patterns.iter().any(|p| p.name == name) { + return true; + } + self.doc.pattern(name).is_some_and(tile_holds_art) + } + + /// Write pattern `name`'s definition, once: `%AI3_BeginPattern: (name)`, `(name) llx lly urx + /// ury` (the tile, y up), the tile's box (an unpainted path whose dictionary marks it, + /// `AIPattern_Editor_Backing_Tile_Rect`) and the art on `%_` lines, `E`, `%AI3_EndPattern`. + /// False when it can't be ([`Self::pattern_writable`]). + fn define_pattern(&mut self, name: &str) -> bool { + if !self.pattern_writable(name) { + return false; + } + let used = !self.in_palette; + if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + p.used |= used; + return true; + } + let doc = self.doc; + let Some(def) = doc.pattern(name) else { return false }; + self.defining.push(name.to_string()); + // The art is written in the pattern's space, y up, from the state a definition starts in. + let saved = ( + std::mem::take(&mut self.body), + (self.to_art, self.grad_space, self.canvas), + self.state.take(), + self.gs.replace(Xy::OPAQUE), + self.clip.take(), + self.block_end, + ); + // `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its + // placement is worked out in the tile's space turned y up. + (self.to_art, self.grad_space, self.canvas, self.block_end) = (Affine::FLIP_Y, self.tile_grad_space, Affine::FLIP_Y, usize::MAX); + // The tile's box first, unpainted and marked as the box: the tile is that box. + self.state(false, false); + self.line("0 XR"); + if let Some(sp) = vectorcraft_geom::shapes::rectangle(def.tile).subpaths.first() { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + } + self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_"); + self.nest += 1; + self.hidden += 1; + for a in &def.art { + self.node(a); + } + self.hidden -= 1; + self.nest -= 1; + let art; + (art, (self.to_art, self.grad_space, self.canvas), self.state, self.gs, self.clip, self.block_end) = saved; + let art = std::mem::replace(&mut self.body, art); + self.defining.pop(); + let tile = Affine::FLIP_Y.transform_rect_bbox(def.tile); + let quoted = ps::bytes(name.as_bytes()); + let mut text = format!("%AI3_BeginPattern: {quoted}\n{quoted} "); + ps::push_nums(&mut text, &[tile.x0, tile.y0, tile.x1, tile.y1]); + text.pop(); + text.push('\n'); + super::hide(&art, &mut text); + text.push_str("E\n%AI3_EndPattern\n"); + self.patterns.push(PatternOut { name: name.to_string(), text, used }); + true + } + + /// Set the fill (or with `stroke`, the stroke) to pattern `name` placed by `xf` (the pattern's + /// space → the document): `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P` for the stroke), the + /// matrix taking the pattern's space (y up, the tile's lower left corner its origin) to the + /// art's. A pattern that can't be defined paints mid gray. + pub(super) fn pattern_paint(&mut self, name: &str, xf: Affine, stroke: bool) { + let height = self.doc.pattern(name).map(|d| d.tile.height()); + let Some(h) = height.filter(|_| self.define_pattern(name)) else { + self.warn(super::PATTERNS); + return self.plain_color(Color::gray(0.5), stroke); + }; + let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y; + let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' }); + } + + /// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then + /// each), those only the palette uses between `%AI5_Begin_NonPrinting`, `Np` and + /// `%AI5_End_NonPrinting--`, then the patterns in the same way (a pattern after those its art + /// uses). + pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { + let defs = std::mem::take(&mut self.gradients); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let _ = writeln!(s, "{} Bn", used.len()); + for d in &used { + self.gradient_def(s, d); + } + if !unused.is_empty() { + let _ = writeln!(s, "%AI5_Begin_NonPrinting\nNp\n{} Bn", unused.len()); + for d in &unused { + self.gradient_def(s, d); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + self.gradients = defs; + for p in self.patterns.iter().filter(|p| p.used) { + s.push_str(&p.text); + } + if self.patterns.iter().any(|p| !p.used) { + s.push_str("%AI5_Begin_NonPrinting\nNp\n"); + for p in self.patterns.iter().filter(|p| !p.used) { + s.push_str(&p.text); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + } + + /// A gradient swatch's or pattern swatch's paint in the palette: `Bb`, a radial gradient's + /// `0 0 0 0 Bh`, `2 (name) 0 0 0 1 1 0 0 1 0 0 1 Bg`, `0 BB`; a pattern's + /// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't + /// be written. + pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool { + match &sw.paint { + Paint::Gradient(g) if writable_gradient(&g.gradient) => { + let swatch = Some(sw.name.as_str()); + let name = self.define_gradient(&g.gradient, swatch); + s.push_str("Bb\n"); + if g.gradient.kind == GradientKind::Radial { + s.push_str("0 0 0 0 Bh\n"); + } + let _ = writeln!(s, "2 {} 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB", ps::bytes(name.as_bytes())); + true + } + Paint::Pattern { pattern, xf } if self.define_pattern(pattern) => { + if *xf != Affine::IDENTITY { + self.warn(SWATCH_PLACEMENT); + } + let _ = writeln!(s, "{} 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", ps::bytes(pattern.as_bytes())); + true + } + _ => false, + } + } +} + +/// Where `Bg` places a gradient: its `x y angle length` operands, its matrix, and a radial +/// gradient's focal point as `Bh`'s angle and fraction ([`placement`]). +struct Placement { + bg: [f64; 4], + transform: Affine, + focal: (f64, f64), +} + +impl Placement { + /// The gradient's place on the path before it is moved: `0 0 0 1`, the identity. + const UNMOVED: Placement = Placement { bg: [0.0, 0.0, 0.0, 1.0], transform: Affine::IDENTITY, focal: (0.0, 0.0) }; +} + +/// The `Bg` operands that place gradient `geom` (`radial` or linear) on `path`, both in the canvas's +/// space (y down; `canvas` takes the document there; in a pattern's tile, the tile's space turned y +/// up). `Bg` places a gradient in the space its matrix takes to the canvas's, on the path as it lies +/// there: +/// +/// - a linear one's ramp runs at `angle` degrees (counterclockwise, y up) from `x` times the path's +/// extent along that angle past where the path starts along it, `length` times that extent long +/// (`y` doesn't move it); +/// - a radial one's center lies `x` times the width and `y` times the height (y down) of the path's +/// bounds from their center, and its radius is `length` times √((dx² + dy²) / 2), `dx` and `dy` the +/// center's distances to the right side and to the bottom of the bounds, whether or not those are +/// the nearer sides; its focal point lies at `Bh`'s angle (y up), its distance from the center a +/// fraction of the radius. +/// +/// A linear gradient is written with the identity, a radial one with the matrix that takes the +/// unit circle onto its extent ellipse at the origin (so that its circle there is the unit circle). +/// [`Placement::UNMOVED`] when the path has no extent along the gradient or the gradient has none. +fn placement(geom: &GradientGeom, radial: bool, path: &BezPath, canvas: Affine) -> Placement { + let s = canvas * geom.start; + let u = canvas * geom.end - s; + if !radial { + let turn = Affine::rotate(-u.atan2()); + let along = (turn * path.clone()).bounding_box(); + let extent = along.width(); + if !(extent > 1e-9 && extent.is_finite() && u.hypot() > 1e-9) { + return Placement::UNMOVED; + } + let bg = [((turn * s).x - along.x0) / extent, 0.0, (-u.y).atan2(u.x).to_degrees(), u.hypot() / extent]; + return Placement { bg, ..Placement::UNMOVED }; + } + // The unit circle's image: `u` along the vector, `v` across it (the aspect ratio), turning the same way. + let across = geom.end - geom.start; + let mut v = canvas * (geom.start + Vec2::new(-across.y, across.x) * geom.aspect) - s; + if u.cross(v) < 0.0 { + v = -v; + } + let m = Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]); + let det = m.determinant().abs(); + if det.is_nan() || det <= 1e-12 { + return Placement::UNMOVED; + } + let back = m.inverse(); + let b = (back * path.clone()).bounding_box(); + let c = back * s; + let (dx, dy) = (b.x1 - c.x, b.y1 - c.y); + let unit = ((dx * dx + dy * dy) / 2.0).sqrt(); + if !(b.width() > 1e-9 && b.height() > 1e-9 && unit > 1e-9 && unit.is_finite()) { + return Placement::UNMOVED; + } + let off = geom.focal.map_or(Vec2::ZERO, |f| back * (canvas * f) - c); + let focal = if off.hypot() > 1e-9 { ((-off.y).atan2(off.x).to_degrees(), off.hypot()) } else { (0.0, 0.0) }; + let bg = [(c.x - b.center().x) / b.width(), (c.y - b.center().y) / b.height(), 0.0, 1.0 / unit]; + Placement { bg, transform: m, focal } +} + +/// Do `def`'s tiles make a grid, with its art (something) within the tile? Art past the tile would +/// be cut off at the tile's edge. +fn tile_holds_art(def: &PatternDef) -> bool { + let t = def.tile; + let tile_ok = [t.x0, t.y0, t.x1, t.y1].iter().all(|v| v.is_finite()) && t.width() > 0.0 && t.height() > 0.0; + tile_ok + && def.tile_type == TileType::Grid + && def.art_bounds().is_some_and(|b| { + let room = t.inflate(1e-6, 1e-6); + b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 + }) +} diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index cfa3928eca..a22c94de53 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -49,13 +49,16 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) { } } -/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`; with `closing`, a closed -/// subpath ends `(n) *` (the painting operator that closes it first). -pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, closing: bool) { +/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`. In `editing` data (see +/// [`crate::ai_editing`]) a subpath is its points and `(N) *` alone, `(n) *` when closed (the +/// painting operator that closes it first). +pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool) { for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { - s.push_str("(N) *\n"); + if !editing { + s.push_str("(N) *\n"); + } subpath(s, xf, sp); - s.push_str(if closing && sp.closed { "(n) *\n" } else { "(N) *\n" }); + s.push_str(if editing && sp.closed { "(n) *\n" } else { "(N) *\n" }); } } diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index aefb80ccb1..1b0ad86049 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,7 @@ use graphics::{GState, Out}; use interp::{Fault, Interp}; use obj::PsError; +pub(crate) use ai::MAX_GRADIENT_STOPS; pub(crate) use native::scale_document; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from}; pub use text::family_style; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index e413f6ec8e..21c6a62aa0 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -36,8 +36,10 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use frames::text_frames; +pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS; pub use read::{ - BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, palette, read, read_beside, variables, + BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, graphic_styles, palette, read, read_beside, + variables, }; pub(crate) use read::{join_and, slot_frame, slot_of}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index 3904e6aabe..4c9bda1b10 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -7,8 +7,18 @@ //! - One object, the brush manager's order, has the order of the Brushes panel: its parameters //! are the plug-in name and brush name of each brush, each one after a `/` and a space. //! - A Calligraphic brush's parameters are 11 numbers: the first is 1; the diameter, roundness and -//! angle as (low, high) pairs; how the diameter, roundness and angle vary (0 Fixed, 1 Random, 2 -//! Pressure, other codes the pen's other channels); a last number. +//! angle as (low, high) pairs; how the diameter, roundness and angle vary; a last number. The +//! codes follow the order of the Brush Options menu: 0 Fixed, 1 Random, 2 Pressure, 3 Stylus +//! Wheel, 4 Tilt, 5 Bearing, 6 Rotation. A user's 6D Art Pen brushes (#372) vary the diameter +//! with 2, the roundness with 5 and the angle with 6, the angle over a whole turn, as the barrel +//! rotation turns the nib. VectorCraft reads no stylus wheel: 3 is read as Random when the value +//! varies, as an unknown code is. +//! - A path with a Calligraphic brush is a stroke in its art style ([`super::style`]): the filter +//! `(Adobe Calligraphic Brush Tool)`, its stroke's paint and weight (the weight scales the brush: +//! 1 pt draws it at its own size), the brush by name (`/GObjRef : (name) (plug-in) +//! /PluginObject`), and the brush's settings for this path as entries: `Diameter`, `Roundness`, +//! `Angle`, their `…Variation` either side and `…DependsOn` codes, and `AngleRelativeTo` (0 the +//! page). //! - A Scatter, Art or Pattern brush's parameters are fields split by `/`: a number, the art's //! section names (one for Scatter, five for Art and Pattern, empty where there is none, each //! after a space for Art and Pattern), more fields, and last 15 numbers. @@ -168,12 +178,15 @@ fn numbers(s: &str) -> Option> { s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() } -/// How a value varies, by its code: `None` for a code that isn't Fixed, Random or Pressure. +/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. fn variation(code: f64) -> Option { match code { 0.0 => Some(Variation::Fixed), 1.0 => Some(Variation::Random), 2.0 => Some(Variation::Pressure), + 4.0 => Some(Variation::Tilt), + 5.0 => Some(Variation::Bearing), + 6.0 => Some(Variation::Rotation), _ => None, } } @@ -183,6 +196,27 @@ fn mode(code: f64, varies: bool) -> Variation { variation(code).unwrap_or(if varies { Variation::Random } else { Variation::Fixed }) } +/// A Calligraphic brush of angle, roundness and size `values`, each varying `variation` either side +/// as its code in `codes` says. +pub(super) fn calligraphic(values: [f64; 3], variation: [f64; 3], codes: [f64; 3]) -> Calligraphic { + let [angle, roundness, size] = values; + let modes = [0, 1, 2].map(|i| mode(codes[i], variation[i] != 0.0)); + Calligraphic { angle, roundness, size, variation, modes: Some(modes) } +} + +/// Does the brush `draft` draw as `c`, the settings a path's art style gives it? A path whose +/// settings differ (Options of Selected Object) keeps its drawn look: a stroke names a brush, and +/// has no settings of its own. +pub(super) fn draws_as(draft: &BrushDraft, c: &Calligraphic) -> bool { + let DraftKind::Calligraphic(d) = &draft.kind else { return false }; + let close = |a: f64, b: f64| (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0); + close(d.angle, c.angle) + && close(d.roundness, c.roundness) + && close(d.size, c.size) + && d.variation.iter().zip(&c.variation).all(|(a, b)| close(*a, *b)) + && d.modes() == c.modes() +} + /// The brush named `name` of kind `kind` from its parameters `params`. pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result { let kind = match kind { @@ -191,15 +225,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< let [_, d0, d1, r0, r1, a0, a1, dm, rm, am, ..] = n.as_slice() else { return Err(BrushError::Values) }; let mid = |a: f64, b: f64| (a + b) / 2.0; let half = |a: f64, b: f64| (b - a).abs() / 2.0; - let variation = [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)]; - let modes = [mode(*am, variation[0] != 0.0), mode(*rm, variation[1] != 0.0), mode(*dm, variation[2] != 0.0)]; - DraftKind::Calligraphic(Calligraphic { - angle: mid(*a0, *a1), - roundness: mid(*r0, *r1), - size: mid(*d0, *d1), - variation, - modes: Some(modes), - }) + DraftKind::Calligraphic(calligraphic( + [mid(*a0, *a1), mid(*r0, *r1), mid(*d0, *d1)], + [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)], + [*am, *rm, *dm], + )) } Tool::Scatter | Tool::Art | Tool::Pattern => { let fields: Vec<&str> = params.split('/').collect(); diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 17590b3203..f61fae77e7 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -1,40 +1,73 @@ //! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their -//! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the -//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's -//! letter and word spacing `TC TW`, hanging punctuation `Tq` and hyphenation `Th`), the paint style, and -//! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the +//! text paths (`a b c d tx ty startPt Tp`, an area's frame, one for each linked area, or the path +//! type runs along, `TP`), the modal character and paragraph attributes +//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging +//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`), the paint style, and the characters (`Tx`, `Tj`, +//! overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the +//! text object clips the objects of its clipping group. Final-form operators (the //! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the -//! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its -//! `%AI3_BeginEncoding` names (else `name`). +//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s +//! `useDefault` is 0, else as Windows-1252; a re-encoded font `/_name` is the font its `%AI3_BeginEncoding` or `TZ` names +//! (else `name`). use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen}; use vectorcraft_color::Paint; -use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun}; use vectorcraft_geom::AnchorKind; use super::super::obj::V; use super::art::path_data; -use super::{FLIP, GState, Reader}; +use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader}; use crate::latin; /// Most characters of type read in one file. const MAX_CHARS: usize = 1 << 22; /// Largest type size and indent read (points). const MAX_SIZE: f64 = 1e4; +/// Most re-encoded fonts read in one file, for their names and for their encodings each. +const MAX_FONTS: usize = 4096; +/// Most tab stops read in one tab definition. +const MAX_TABS: usize = 1024; +/// Largest tab stop position read (points), as `text.tabs.set` takes it. +const MAX_TAB_POSITION: f64 = 100_000.0; +/// Most values read before one operator in a re-encoding section. +const MAX_ENCODING_VALUES: usize = 1024; +/// Most text paths read in one text object (its linked areas); the frames of others are left out, +/// with a warning. +const MAX_TEXT_PATHS: usize = 4096; +/// Most frames of linked areas times characters of their story: the story is laid out again +/// through its frames when the file opens. The frames of the areas past it are left out, with a +/// warning. +const MAX_THREAD_WORK: usize = MAX_CHARS; +/// The warning when [`MAX_TEXT_PATHS`] or [`MAX_THREAD_WORK`] leaves frames of linked areas out. +const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out"; +/// The warning when type set in a mask rendering mode can't be a clipping path: type in linked +/// areas (several frames), in wraparound text or in a compound path doesn't clip. +const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; + +/// A text path (`Tp` … `TP`). +#[derive(Debug, Default)] +struct TextPath { + /// `Tp`'s matrix: text space (y up) → art space. + matrix: Option, + /// Where type on a path starts: a segment's index plus how far along it. + start: f64, + /// The frame or path, in art space, and the kind of the anchor each of its segments ends on. + path: Option<(BezPath, Vec)>, +} /// A text object being read. #[derive(Debug, Default)] pub(super) struct LegacyText { /// `To`'s type: 0 point type, 1 area type, 2 type on a path. kind: i64, - /// `Tp`'s matrix: text space (y up) → art space. - matrix: Option, - /// Where type on a path starts: a segment's index plus how far along it. - start: f64, + /// Its text paths in file order: area type has one for each linked area (§15.5.3). + paths: Vec, /// Between `Tp` and `TP`: the path read is the text path. in_path: bool, - /// The frame or path, in art space, and the kind of the anchor each of its segments ends on. - path: Option<(BezPath, Vec)>, + /// It has more than [`MAX_TEXT_PATHS`] text paths: the paths read past them are left out. + past_limit: bool, + /// The story: the characters after every text path, in file order. runs: Vec, /// Each paragraph's attributes, as they were at its first character. paras: Vec, @@ -42,6 +75,9 @@ pub(super) struct LegacyText { para_taken: bool, /// An overflow paragraph break (`(\r) TX`) not yet followed by type: the story's end. pending_break: bool, + /// Characters were set in a mask rendering mode (`Tr` 4 to 7): the text object is a clipping + /// path (§5.7). + clips: bool, /// The state when it began (lock, visibility), and whether it began on a `%_` line. gs: GState, hidden: bool, @@ -56,14 +92,31 @@ pub(super) struct TypeState { render: i64, /// The encoding strings are in, by code (`TE`); None where it says nothing. encoding: Vec>, - /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`). + /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s). fonts: Vec<(String, String)>, + /// Re-encoded fonts' own encodings (`TZ`), by the new font's name: what its encoding pairs + /// change, by code (None where they say nothing), and whether `TE`'s encoding applies to it. + font_encodings: Vec<(String, Vec>, bool)>, + /// The font `Tf` set last, as the file names it. + font: Option, + /// Between `Xb` and `XB`: the tab stops of the tab definition read so far. + tabs: Option>, chars: usize, } impl Default for TypeState { fn default() -> Self { - Self { style: CharStyle::default(), para: ParaStyle::default(), render: 0, encoding: vec![None; 256], fonts: vec![], chars: 0 } + Self { + style: CharStyle::default(), + para: ParaStyle::default(), + render: 0, + encoding: vec![None; 256], + fonts: vec![], + font_encodings: vec![], + font: None, + tabs: None, + chars: 0, + } } } @@ -72,10 +125,51 @@ impl TypeState { pub(super) fn encoding_comment(&mut self, line: &str) { let Some((_, names)) = line.split_once(':') else { return }; let mut words = names.split_whitespace(); - if let (Some(new), Some(old)) = (words.next(), words.next()) - && self.fonts.len() < 4096 - { - self.fonts.push((new.trim_start_matches('/').to_string(), old.trim_start_matches('/').to_string())); + if let (Some(new), Some(old)) = (words.next(), words.next()) { + self.font_names(new.trim_start_matches('/'), old.trim_start_matches('/')); + } + } + + /// Re-encoded font `new` is font `old`. The first statement for a name is used. + fn font_names(&mut self, new: &str, old: &str) { + if self.fonts.len() < MAX_FONTS && !self.fonts.iter().any(|(n, _)| n == new) { + self.fonts.push((new.to_string(), old.to_string())); + } + } + + /// A string's bytes, in the current font. + fn decode(&self, bytes: &[u8]) -> String { + let own = self.font.as_ref().and_then(|f| self.font_encodings.iter().find(|(n, _, _)| n == f)); + let (own, te) = own.map_or((None, true), |(_, e, te)| (Some(e.as_slice()), *te)); + bytes + .iter() + .map(|&b| { + if b == b'\r' { + return '\n'; + } + own.and_then(|e| e.get(usize::from(b)).copied().flatten()) + .or_else(|| if te { self.encoding.get(usize::from(b)).copied().flatten() } else { None }) + .unwrap_or_else(|| latin::decode(b)) + }) + .collect() + } +} + +/// Encoding pairs (§3.3.1): codes, each followed by the glyph names from it on, into `table`. +fn encoding_pairs(table: &mut [Option], vals: &[V]) { + let mut code: Option = None; + for v in vals { + match v { + V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), + V::Name(name) => { + if let Some(c) = code { + if let (Some(slot), Ok(b)) = (table.get_mut(c), u8::try_from(c)) { + *slot = latin::glyph(b, name); + } + code = Some(c + 1); + } + } + _ => {} } } } @@ -102,19 +196,86 @@ fn flag(v: f64) -> Option { impl Reader<'_> { /// `[encodingPairs TE`: codes, each followed by the glyph names from it on (§3.3.1). pub(super) fn te(&mut self, vals: &[V]) { - let mut code: Option = None; - for v in vals { - match v { - V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), - V::Name(name) => { - if let Some(c) = code { - if let (Some(slot), Ok(b)) = (self.type_state.encoding.get_mut(c), u8::try_from(c)) { - *slot = latin::glyph(b, name); - } - code = Some(c + 1); + encoding_pairs(&mut self.type_state.encoding, vals); + } + + /// `[encodingPairs newFontName oldFontName direction fontScript useDefault TZ`, with a Multiple + /// Master weight vector `[w0 … wn]` after it, and without the encoding pairs or the direction + /// in some versions (§3.3.1): the new font's own encoding pairs, which strings in it are + /// decoded by first. `useDefault` 1 (or no number after the names) decodes the codes the pairs + /// leave out by `TE`'s encoding, and 0 leaves `TE`'s encoding out for the font. The font names + /// are the last two names; only numbers and the weight vector follow them. The first `TZ` for + /// a font is used. + pub(super) fn tz(&mut self, vals: &[V]) { + let mut names = vals.iter().enumerate().filter_map(|(i, v)| if let V::Name(n) = v { Some((i, n)) } else { None }).rev(); + let (Some((old_at, old)), Some((new_at, new))) = (names.next(), names.next()) else { return }; + if new_at + 1 != old_at { + return; + } + let tail = vals.get(old_at + 1..).unwrap_or_default(); + let weights = matches!(tail.last(), Some(V::Arr(_))); + let numbers = tail.get(..tail.len() - usize::from(weights)).unwrap_or_default(); + if !numbers.iter().all(|v| matches!(v, V::Num(_))) { + return; + } + let te = !matches!(numbers.last(), Some(V::Num(n)) if *n == 0.0); + let st = &mut self.type_state; + st.font_names(new, old); + if st.font_encodings.iter().any(|(n, _, _)| n == new) || st.font_encodings.len() >= MAX_FONTS { + return; + } + // The pairs start after the `[` that opens them. + let pairs = vals.get(..new_at).unwrap_or_default(); + let pairs = pairs.iter().rposition(|v| matches!(v, V::Mark)).map_or(pairs, |m| pairs.get(m + 1..).unwrap_or_default()); + let mut table = vec![None; 256]; + encoding_pairs(&mut table, pairs); + st.font_encodings.push((new.clone(), table, te)); + } + + /// What is between `%AI3_BeginEncoding` and `%AI3_EndEncoding` (§3.3): its `TZ` is read, and + /// every other operator is skipped with its operands. + pub(super) fn encoding_section(&mut self, section: &[u8]) { + let mut lex = super::Lexer::new(section); + let mut vals: Vec = Vec::new(); + let mut marks: Vec = Vec::new(); + // `[`s past the value limit, which are not kept: as many `]`s after them are skipped. + let mut dropped: usize = 0; + while let Some(t) = lex.next_token() { + let v = match t.tok { + super::Tok::Num(n) => V::Num(n), + super::Tok::Name(n) => V::Name(super::obj::text(n)), + super::Tok::Str(s) | super::Tok::Hex(s) => V::Str(s), + super::Tok::Word(b"[") => { + // Each `[` kept is a value, so the open arrays are no more than the values. + if vals.len() >= MAX_ENCODING_VALUES { + dropped = dropped.saturating_add(1); + continue; } + marks.push(vals.len()); + V::Mark } - _ => {} + super::Tok::Word(b"]") => { + if dropped > 0 { + dropped -= 1; + continue; + } + let Some(m) = marks.pop() else { continue }; + let items: Vec = vals.split_off(m.min(vals.len())).into_iter().skip(1).collect(); + V::Arr(items) + } + super::Tok::Word(w) => { + if w == b"TZ" { + self.tz(&vals); + } + vals.clear(); + marks.clear(); + dropped = 0; + continue; + } + _ => continue, + }; + if vals.len() < MAX_ENCODING_VALUES { + vals.push(v); } } } @@ -131,6 +292,8 @@ impl Reader<'_> { self.unreadable("type in a pattern", false); } let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); + // A tab definition left open by an earlier text object (an `Xb` with no `XB`) ends here. + self.type_state.tabs = None; self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } @@ -144,27 +307,28 @@ impl Reader<'_> { 6 => (nums::<6>(vals), None), _ => (None, None), }; - if let Some(m) = m { - let m = Affine::new(m); + let matrix = m.map(Affine::new).filter(|m| { let det = m.determinant(); - if det.is_finite() && det.abs() > 1e-12 { - t.matrix = Some(m); - } + det.is_finite() && det.abs() > 1e-12 + }); + let start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + t.past_limit |= t.paths.len() >= MAX_TEXT_PATHS; + if !t.past_limit { + t.paths.push(TextPath { matrix, start, path: None }); } - t.start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); t.in_path = true; } - /// The path painted (or `TP`, ending the text path): the text object's frame or path. + /// The path painted (or `TP`, ending the text path): the text path's frame or path. pub(super) fn text_path(&mut self) { let path = std::mem::take(&mut self.path); let kinds = std::mem::take(&mut self.path_kinds); self.end_path_quietly(); - if let Some(t) = self.text.as_mut() - && t.path.is_none() + if let Some(p) = self.text.as_mut().filter(|t| !t.past_limit).and_then(|t| t.paths.last_mut()) + && p.path.is_none() && !path.elements().is_empty() { - t.path = Some((path, kinds)); + p.path = Some((path, kinds)); } } @@ -182,8 +346,9 @@ impl Reader<'_> { let st = &mut self.type_state; let n0 = nums::<1>(vals).map(|[v]| v); match w { + // `render Tr`: a mode from 0 to 9 (§15.4.5.1). "Tr" => { - if let Some(v) = n0 { + if let Some(v) = n0.filter(|v| v.fract() == 0.0 && (0.0..=9.0).contains(v)) { st.render = v as i64; } } @@ -191,6 +356,7 @@ impl Reader<'_> { // `/name size Tf`, or `/name size ascent descent Tf`. let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return }; if let Some(V::Name(name)) = vals.get(at) { + st.font = Some(name.clone()); let name = st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); let (family, style) = super::super::super::text::family_style(&name); @@ -293,6 +459,37 @@ impl Reader<'_> { h.before_last = letters(tail, 1.0, 15.0); h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 }; } + // A tab definition (§22.6): `numDots numTabs Xb` begins it, each + // `leader decimal tabType tabPosition Xe` describes one tab stop, and `XB` ends it. The + // stops it describes replace the paragraph's tab stops, sorted by position, one stop at + // each position; a definition with none (or whose descriptions were all skipped) leaves + // the default stops. The dot-leader distance, the count and the two reserved operands are + // not read. A description whose type is not 1 to 4 (left, center, right, decimal) or + // whose position is not a number from 0 to [`MAX_TAB_POSITION`] is skipped, and so is one + // outside a tab definition or past the first [`MAX_TABS`] of one. A text object's `To` + // ends a definition that an earlier object left open. + "Xb" => st.tabs = Some(vec![]), + "Xe" => { + let Some(tabs) = st.tabs.as_mut().filter(|t| t.len() < MAX_TABS) else { return }; + let Some([kind, position]) = nums::<2>(vals) else { return }; + let align = match kind { + 1.0 => TabAlign::Left, + 2.0 => TabAlign::Center, + 3.0 => TabAlign::Right, + 4.0 => TabAlign::Decimal, + _ => return, + }; + if (0.0..=MAX_TAB_POSITION).contains(&position) { + tabs.push(TabStop { position, align, leader: String::new(), align_on: '.' }); + } + } + "XB" => { + if let Some(mut tabs) = st.tabs.take() { + tabs.sort_by(|a, b| a.position.total_cmp(&b.position)); + tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); + st.para.tabs = tabs; + } + } _ => {} } } @@ -302,10 +499,7 @@ impl Reader<'_> { let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return }; let st = &mut self.type_state; let Some(t) = self.text.as_mut() else { return }; - let decoded: String = bytes - .iter() - .map(|&b| if b == b'\r' { '\n' } else { st.encoding.get(usize::from(b)).copied().flatten().unwrap_or_else(|| latin::decode(b)) }) - .collect(); + let decoded = st.decode(&bytes); if decoded.is_empty() { return; } @@ -323,6 +517,9 @@ impl Reader<'_> { st.chars += decoded.chars().count(); let gs = &self.gs; let mut style = st.style.clone(); + // Characters in modes 4 to 7 make the whole text object the mask, not each run (§5.7); 7 + // paints nothing, nor does 3 (invisible). + t.clips |= (4..=7).contains(&st.render); let (fill, stroke) = match st.render { 0 | 4 => (true, false), 1 | 5 => (false, true), @@ -358,35 +555,115 @@ impl Reader<'_> { } } - /// `TO`: the text object ends. + /// `TO`: the text object ends. Area type with several linked areas becomes one frame for each + /// area, threaded in file order: the first frame holds the story, and the flow from area to + /// area (final-form, §15.1) is laid out again. The frames are added last to first, so the + /// object's dictionary that follows names the first one ([`Reader::each_linked_frame`]). + /// Point type is read at its first text path; area type and type on a path at the first one + /// that has a frame or path (else at the first one, as point type). pub(super) fn end_text(&mut self, hidden: bool) -> Result<(), String> { let Some(t) = self.text.take() else { return Ok(()) }; if t.runs.is_empty() { return Ok(()); } - let m = t.matrix.unwrap_or(Affine::IDENTITY); let to_doc = self.space(); - // Art space → text space (y down). - let to_text = FLIP * m.inverse(); - let kind = match (t.kind, &t.path) { - (1, Some((p, kinds))) => TextKind::Area { frame: path_data(&(to_text * p.clone()), kinds) }, - (2, Some((p, kinds))) => { - TextKind::OnPath { path: path_data(&(to_text * p.clone()), kinds), start: start_fraction(p, t.start), end: None } - } - _ => TextKind::Point, + let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); + let most = (MAX_THREAD_WORK / chars.max(1)).max(1); + let all_areas = t.paths.iter().filter(|p| p.path.is_some()).count(); + // Area type with linked areas, also when the limits leave one frame of it. + let linked = t.kind == 1 && (all_areas > 1 || t.past_limit); + let areas: Vec<&TextPath> = t.paths.iter().filter(|p| p.path.is_some()).take(most).collect(); + let placed: Vec<(Affine, TextKind)> = match t.kind { + 1 if areas.len() > 1 => areas.into_iter().map(|p| placed(1, Some(p))).collect(), + 0 => vec![placed(0, t.paths.first())], + kind => vec![placed(kind, areas.first().copied().or(t.paths.first()))], }; - let mut obj = TextObject::point(kurbo::Point::ZERO, "", CharStyle::default()); - obj.kind = kind; - obj.xf = to_doc * m * FLIP; - obj.runs = t.runs; + if t.kind == 1 && (t.past_limit || all_areas > placed.len()) { + self.warn(LINKED_AREAS_LEFT_OUT); + } let mut paras = t.paras; if paras.is_empty() { paras.push(self.type_state.para.clone()); } - obj.set_paragraph_styles(paras); - let node = self.new_node(NodeKind::Text(Box::new(obj)), &t.gs); - self.add(node, t.hidden || hidden) + let last_para = paras.last().cloned().unwrap_or_default(); + let last_style = t.runs.last().map(|r| r.style.clone()).unwrap_or_default(); + let mut story = Some((t.runs, paras)); + let mut nodes = Vec::with_capacity(placed.len()); + for (m, kind) in placed { + let mut obj = TextObject::point(kurbo::Point::ZERO, "", last_style.clone()); + obj.kind = kind; + obj.xf = to_doc * m * FLIP; + match story.take() { + Some((runs, paras)) => { + obj.runs = runs; + obj.set_paragraph_styles(paras); + } + None => obj.set_paragraph_styles(vec![last_para.clone()]), + } + nodes.push(self.new_node(NodeKind::Text(Box::new(obj)), &t.gs)); + } + let frames: Vec = nodes.iter().map(|n| n.id).collect(); + // Type used as a mask clips the objects of its clipping group, as a `W` path does. A + // clipping path is one object, and wraparound text and compound paths don't clip their + // objects with type, so the frames of linked areas and type in those don't clip, with a + // warning. The frames up to the clipping group or opacity mask's art are checked, a group in + // either included. + let in_wrap_or_compound = self + .frames + .iter() + .rev() + .take_while(|f| !matches!(f.kind, Kind::Clip | Kind::Mask | Kind::Layer(_))) + .any(|f| matches!(f.kind, Kind::Wrap | Kind::Compound)); + let can_clip = !linked && nodes.len() == 1 && !in_wrap_or_compound; + if t.clips && !can_clip { + self.warn(MASK_NOT_CLIPPED); + } + for node in nodes.into_iter().rev() { + if t.clips + && can_clip + && let Some(f) = self.frames.last_mut() + { + f.clips.push(f.children.len()); + } + self.add(node, t.hidden || hidden)?; + } + if frames.len() > 1 { + self.doc.text_threads.push(frames); + } + Ok(()) } + + /// Call `f` on the other frames of the threaded text object just read, whose first frame is + /// the last object ([`Reader::end_text`]): the opacity mask and text wrap of the object's + /// dictionary apply to every frame. + pub(super) fn each_linked_frame(&mut self, mut f: impl FnMut(&mut Node)) { + if !self.after_object { + return; + } + let Some(first) = self.frames.last().and_then(|fr| fr.children.last()).map(|n| n.id) else { return }; + let Some(thread) = self.doc.text_threads.last().filter(|t| t.first() == Some(&first)) else { return }; + let rest: HashSet = thread.iter().skip(1).copied().collect(); + let Some(fr) = self.frames.last_mut() else { return }; + for n in fr.children.iter_mut().rev().skip(1).take(rest.len()).filter(|n| rest.contains(&n.id)) { + f(n); + } + } +} + +/// A text object of type `kind` on text path `p` (none: at the origin): the matrix from text space +/// (y up) to art space, and the kind of type with its frame or path in text space (y down). +fn placed(kind: i64, p: Option<&TextPath>) -> (Affine, TextKind) { + let m = p.and_then(|p| p.matrix).unwrap_or(Affine::IDENTITY); + // Art space → text space (y down). + let to_text = FLIP * m.inverse(); + let kind = match (kind, p.and_then(|p| p.path.as_ref().map(|path| (path, p.start)))) { + (1, Some(((path, kinds), _))) => TextKind::Area { frame: path_data(&(to_text * path.clone()), kinds) }, + (2, Some(((path, kinds), start))) => { + TextKind::OnPath { path: path_data(&(to_text * path.clone()), kinds), start: start_fraction(path, start), end: None } + } + _ => TextKind::Point, + }; + (m, kind) } /// Where type on `path` starts (`index.fraction`: a segment and how far along it, §15.5.2), as a diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index eb8841e0db..b96b85c068 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -55,6 +55,56 @@ const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlace /// A document included whole: (begin, end) markers. const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); +/// The line of `src` before the one that starts at `at`, without its line end, when it ends within +/// [`OPERAND_LINE`] bytes of `at` and is no longer than that. +fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> { + let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?; + let end = before.iter().rposition(|b| !is_eol(*b))? + 1; + let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1; + before.get(start..end) +} + +/// The longest line of an image's `XI` operands looked at. +const OPERAND_LINE: usize = 1024; + +/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix] +/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when +/// the alpha count isn't 0, else none (or when the operands aren't of that shape). +fn alpha_bytes(line: &[u8]) -> usize { + let line = line.strip_prefix(b"%_").unwrap_or(line); + let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 }; + let nums: Vec = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect(); + match (nums.get(4), nums.get(5), nums.get(8)) { + // At most the pixels the reader reads an image with. + (Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize, + _ => 0, + } +} + +/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose +/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line +/// end, or the end of `w`, follows. +fn end_data(w: &[u8]) -> Option { + const MARK: &[u8] = b"%%EndData"; + let mut first = None; + let mut at = 0; + while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) { + let i = at + i; + let rest = w.get(i + MARK.len()..).unwrap_or_default(); + if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) { + let next = rest.strip_prefix(b"\r").unwrap_or(rest); + let next = next.strip_prefix(b"\n").unwrap_or(next); + let next = next.strip_prefix(b"%_").unwrap_or(next); + if next.starts_with(b"XH") { + return Some(i); + } + first = first.or(Some(i)); + } + at = i + 1; + } + first +} + fn is_space(b: u8) -> bool { matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') } @@ -232,12 +282,18 @@ impl<'a> Lexer<'a> { (Some(b'\r' | b'\n'), _) => data += 1, _ => {} } - // The count leaves out an alpha channel: the data ends where `%%EndData` starts. + // The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one + // that a line end or the end of the data follows (samples can hold the marker's bytes). let declared = from.saturating_add(n).min(self.src.len()).max(data); - let window = - self.src.get(declared.saturating_sub(4).max(data)..declared.saturating_add(n.saturating_mul(2)).saturating_add(64).min(self.src.len())); - let end = match window.and_then(|w| find(w, b"%%EndData")) { - Some(i) => declared.saturating_sub(4).max(data) + i, + // The alpha channel the line before gives the image (its `XI` operands) follows the counted + // samples: the marker is looked for after it. + let line_start = self.pos.saturating_sub(line.len()); + let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start }; + let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes); + let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data); + let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len()); + let end = match self.src.get(start..stop).and_then(end_data) { + Some(i) => start + i, None => declared, }; self.pos = end; diff --git a/crates/eps/src/import/ai/paint.rs b/crates/eps/src/import/ai/paint.rs index b624a22475..178238dc15 100644 --- a/crates/eps/src/import/ai/paint.rs +++ b/crates/eps/src/import/ai/paint.rs @@ -18,19 +18,24 @@ //! `Bm` for each pair in the order of the ramp (`Bc`, around them, are the caps past the first and //! last stops). Without `Xm`, a radial gradient's one `Bm` takes the unit circle onto it. //! +//! - The name shown for a gradient's or a pattern's name in the file is the part before its first +//! newline (`\n`) ([`ShownNames`]). +//! //! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at -//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators. +//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators and §4 +//! the names of global objects. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use kurbo::{Affine, Point, Vec2}; use vectorcraft_color::gradient::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; use vectorcraft_color::{Color, Paint}; +use super::lex::{Lexer, Tok}; use super::obj::V; /// Largest number of stops read in one gradient. -const MAX_STOPS: usize = 256; +pub(crate) const MAX_STOPS: usize = 256; /// A colour read with the swatch it names (spot and global colours). #[derive(Clone, Debug, PartialEq)] @@ -172,7 +177,16 @@ impl GradientDef { } // Stops are listed along the ramp from either end: listed downwards they're reversed, so // stops sharing a ramp point keep their order (and each its midpoint, to the next stop). - if self.gradient.stops.first().zip(self.gradient.stops.last()).is_some_and(|(first, last)| first.offset > last.offset) { + // When every stop shares one ramp point, a linear gradient's are taken as listed from the + // last, as newer files list a linear gradient's stops. + let linear = self.gradient.kind == GradientKind::Linear; + if self + .gradient + .stops + .first() + .zip(self.gradient.stops.last()) + .is_some_and(|(first, last)| first.offset > last.offset || (linear && self.gradient.stops.len() > 1 && first.offset == last.offset)) + { self.gradient.stops.reverse(); } self.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); @@ -180,6 +194,157 @@ impl GradientDef { } } +/// The names of the named colors in the tokens [`Self::token`] is given: those the color operators +/// (`x`, `Xx`, `Xk` and their stroke forms) and gradient stops (`Bs` between `Bd` and `BD`) use, +/// also in the color and tile strings of patterns in the version 7 form (`(…) @`, `(…) &`). It +/// also keeps the names of the gradients `BD` finishes ([`GradientDef::finish`]). +#[derive(Default)] +pub(super) struct ColorNames { + pub names: HashSet, + pub gradients: Vec, + vals: Vec, + def: Option, + spots: Vec, +} + +impl ColorNames { + pub fn token(&mut self, tok: Tok<'_>) { + self.take(tok, true); + } + + /// [`Self::token`], with the names in the strings of a version 7 pattern's layer when `outer`. + fn take(&mut self, tok: Tok<'_>, outer: bool) { + let w = match tok { + Tok::Num(n) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Num(n)); + } + return; + } + Tok::Str(s) | Tok::Hex(s) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Str(s)); + } + return; + } + Tok::Word(w) => w, + _ => return, + }; + let vals = std::mem::take(&mut self.vals); + match w { + b"Bd" => self.def = GradientDef::begin(&vals), + b"BD" => { + if let Some((name, _)) = self.def.take().and_then(GradientDef::finish) { + self.gradients.push(name); + } + } + b"Bs" => { + if let Some(d) = self.def.as_mut() { + d.stop(&vals, &mut self.spots); + } + } + b"x" | b"X" | b"Xx" | b"XX" | b"Xk" | b"XK" => { + if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op(op, &vals)) { + self.spots.push(n); + } + } + b"@" | b"&" if outer => { + for v in &vals { + if let V::Str(s) = v { + let mut inner = ColorNames::default(); + let mut lex = Lexer::new(s); + while let Some(t) = lex.next_token() { + inner.take(t.tok, false); + } + self.names.extend(inner.names); + } + } + } + _ => {} + } + self.names.extend(self.spots.drain(..).map(|n| n.name)); + } +} + +/// A kind of global object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Global { + Gradient, + Pattern, +} + +/// The names the gradients and patterns get in the document, by their kind and names in the file. +/// The name shown for a name in the file is the part before its first newline (AI7 spec §4): +/// `(Sky\n1)` is shown as "Sky". Gradients and patterns share their swatches' names. A name with a +/// newline is shown as the part before it unless that name is reserved (a custom color's, or a +/// gradient's or pattern's name without a newline) or an object defined earlier (of either kind) +/// got it; then it is the first free "Sky 2", "Sky 3"… A name shown as nothing (`(\n3)`) is shown +/// as "Gradient" or "Pattern", numbered the same way. A name without a newline is kept. An object +/// defined again under the same name in the file keeps the name it got. +#[derive(Debug, Default)] +pub(super) struct ShownNames { + gradients: HashMap, + patterns: HashMap, + taken: HashSet, + /// The number to try first for each shown name already taken. + next: HashMap, +} + +impl ShownNames { + fn by_file(&self, kind: Global) -> &HashMap { + match kind { + Global::Gradient => &self.gradients, + Global::Pattern => &self.patterns, + } + } + + /// The name the object of `kind` defined as `name` in the file got ([`Self::define`]), or + /// `name` for one not defined. + pub fn get<'n>(&'n self, kind: Global, name: &'n str) -> &'n str { + self.by_file(kind).get(name).map_or(name, String::as_str) + } + + /// Keep `name` from the objects defined after. + pub fn reserve(&mut self, name: &str) { + self.taken.insert(name.to_string()); + } + + /// The name the object of `kind` defined as `name` in the file gets. + pub fn define(&mut self, kind: Global, name: &str) -> String { + if let Some(shown) = self.by_file(kind).get(name) { + return shown.clone(); + } + let shown = match name.split_once('\n') { + None => name.to_string(), + Some((base, _)) => { + let base = match (base.is_empty(), kind) { + (false, _) => base, + (true, Global::Gradient) => "Gradient", + (true, Global::Pattern) => "Pattern", + }; + if self.taken.contains(base) { + // The first free number from the one after the last number this base got. Of + // the numbers `from..=tries`, at least one is free. + let from = self.next.get(base).copied().unwrap_or(2); + let tries = from.saturating_add(self.taken.len()); + let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries); + self.next.insert(base.to_string(), i.saturating_add(1)); + format!("{base} {i}") + } else { + base.to_string() + } + } + }; + self.taken.insert(shown.clone()); + let by_file = match kind { + Global::Gradient => &mut self.gradients, + Global::Pattern => &mut self.patterns, + }; + by_file.insert(name.to_string(), shown.clone()); + shown + } +} + /// A gradient instance on an object, between `Bb` and `BB`. #[derive(Clone, Debug, Default)] pub(super) struct Instance { @@ -258,8 +423,9 @@ impl Instance { self.xm.is_some() || self.bm.is_some() } - /// The paint, through `to_doc` (art space → the document), when the gradient is defined. - pub fn paint(&self, defs: &HashMap, to_doc: Affine) -> Option { + /// The paint, through `to_doc` (art space → the document), when the gradient is defined, linked + /// to the gradient's swatch by the name `shown` gave it. + pub fn paint(&self, defs: &HashMap, shown: &ShownNames, to_doc: Affine) -> Option { let name = self.name.as_ref()?; let gradient = defs.get(name)?.clone(); let radial = gradient.kind == GradientKind::Radial; @@ -310,7 +476,8 @@ impl Instance { let focal = (self.hilight.hypot() > 1e-9).then_some(focal).filter(|p| p.is_finite()); let geom = GradientGeom { start, end, aspect, focal: if radial { focal } else { None } }; let angle = -(end - start).atan2().to_degrees(); - Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch: Some(name.clone()), ..GradientPaint::new(gradient) }))) + let swatch = Some(shown.get(Global::Gradient, name).to_string()); + Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch, ..GradientPaint::new(gradient) }))) } } @@ -406,22 +573,59 @@ mod tests { bg.extend(nums(&[100.0, 100.0, 0.0, 50.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); i.bg(&bg); i.bm(&nums(&[50.0, 0.0, 0.0, -50.0, 100.0, 100.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let shown = ShownNames::default(); + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; + assert_eq!(gp.swatch.as_deref(), Some("G")); let geom = gp.geom.unwrap(); assert_eq!(geom.start, Point::new(100.0, 100.0)); assert_eq!(geom.end, Point::new(150.0, 100.0)); assert!((geom.aspect - 1.0).abs() < 1e-9); - assert!(i.paint(&HashMap::new(), Affine::IDENTITY).is_none()); + assert!(i.paint(&HashMap::new(), &shown, Affine::IDENTITY).is_none()); // Newer files give the matrix with `Xm`; the `Bm`s after it are bands of a cached ramp. let mut i = Instance::begin(&[]); i.bg(&bg); i.xm(&nums(&[40.0, 0.0, 0.0, -40.0, 10.0, 10.0])); i.bm(&nums(&[5.0, 0.0, 0.0, -40.0, 30.0, 10.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; let geom = gp.geom.unwrap(); assert_eq!((geom.start, geom.end), (Point::new(10.0, 10.0), Point::new(50.0, 10.0))); } + /// A name is shown up to its first newline, numbered when a reserved name or an earlier object + /// of either kind has it; a name defined again keeps the name it got, and a blank one gets its + /// kind's stand-in. A name without a newline is kept. + #[test] + fn global_names_are_shown_up_to_their_newline() { + let mut shown = ShownNames::default(); + // A color's name, and the names without a newline the file defines. + for name in ["Ink", "Sky", "Sky 2", "Sea"] { + shown.reserve(name); + } + let got: Vec = [ + (Global::Gradient, "Sky\n1"), + (Global::Gradient, "Sky\n2"), + (Global::Gradient, "Sky"), + (Global::Gradient, "Sky\n1"), + (Global::Pattern, "Sky\n1"), + (Global::Gradient, "Sea\nA\nB"), + (Global::Gradient, "\n3"), + (Global::Pattern, "\n4"), + (Global::Gradient, "Sky 2"), + (Global::Pattern, "Ink\n1"), + (Global::Gradient, "Ink"), + (Global::Pattern, "Sea"), + (Global::Pattern, "Tide\n1"), + (Global::Pattern, ""), + ] + .iter() + .map(|(kind, n)| shown.define(*kind, n)) + .collect(); + assert_eq!(got, ["Sky 3", "Sky 4", "Sky", "Sky 3", "Sky 5", "Sea 2", "Gradient", "Pattern", "Sky 2", "Ink 2", "Ink", "Sea", "Tide", ""]); + assert_eq!(shown.get(Global::Gradient, "Sky\n2"), "Sky 4"); + assert_eq!(shown.get(Global::Pattern, "Sky\n1"), "Sky 5"); + assert_eq!(shown.get(Global::Pattern, "Sky\n2"), "Sky\n2", "not a pattern's name"); + } + #[test] fn gradient_stops_beyond_the_cap_are_ignored() { let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap(); @@ -434,6 +638,24 @@ mod tests { assert_eq!(g.stops.len(), MAX_STOPS); } + /// A hard edge: every stop at one ramp point. A linear gradient's are listed from the last, a + /// radial one's from the first. + #[test] + fn stops_at_one_ramp_point_keep_their_sides() { + for (kind, listed) in [(0.0, [0.75, 0.25]), (1.0, [0.25, 0.75])] { + let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)]).unwrap(); + for (gray, mid) in listed.into_iter().zip([40.0, 70.0]) { + d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![]); + } + let (_, g) = d.finish().unwrap(); + let lightness: Vec = g.stops.iter().map(|s| (s.color.to_rgb()[0] * 100.0).round() / 100.0).collect(); + let first_mid = if kind == 0.0 { 0.7 } else { 0.4 }; + assert_eq!(lightness, vec![0.25, 0.75], "kind {kind}"); + assert!((g.stops[0].midpoint - first_mid).abs() < 1e-6, "kind {kind}: {:?}", g.stops); + assert!(g.stops.iter().all(|s| (s.offset - 0.3).abs() < 1e-6)); + } + } + /// A linear gradient of three stops as newer files place it: `Bg` with numbers that aren't in /// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops. #[test] @@ -454,7 +676,7 @@ mod tests { // From the stop at 20 to the one at 60, then on to the one at 100. i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 260.0])); i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 180.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &ShownNames::default(), Affine::IDENTITY) else { panic!() }; gp.geom.unwrap() }; for xm in [true, false] { diff --git a/crates/eps/src/import/ai/palette.rs b/crates/eps/src/import/ai/palette.rs index 9a4ba72ebc..e816c5d6c0 100644 --- a/crates/eps/src/import/ai/palette.rs +++ b/crates/eps/src/import/ai/palette.rs @@ -63,6 +63,14 @@ impl Palette { pub fn is_empty(&self) -> bool { self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty()) } + + /// The names the palette gives its color groups and swatches, except the name a swatch takes + /// from its gradient or pattern. + pub fn own_names(&self) -> impl Iterator { + let named = |e: &Entry| !matches!(&e.cell, Cell::Gradient(n) | Cell::Pattern(n) if *n == e.name); + let swatches = self.swatches.iter().chain(self.groups.iter().flat_map(|(_, s)| s)).filter(move |e| named(e)); + self.groups.iter().map(|(name, _)| name.as_str()).chain(swatches.map(|e| e.name.as_str())) + } } /// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end. diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index a3eda140e5..2cf9dc736e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -35,6 +35,11 @@ //! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and //! an alpha channel that hides part of such an image becomes its opacity mask; other samples //! become an RGBA PNG. +//! - Linked images in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF` with the +//! operands `XI` takes and no samples. Each is a linked image of that file showing a placeholder +//! over the image's place until its file is found. An `XF` without a file name before it, or +//! with operands `XI` couldn't read, is left out with a warning. An `XI` after `XG` (newer files +//! write `() 1 XG` before their embedded images) stays an embedded image. //! - Placed (linked) files, as written in files users sent: `%AI5_BeginPlace`, `[matrix] llx lly urx //! ury … (path)` and the operator `` ` ``, the file's preview between `%AI26_BeginPlacedObjectPreview` //! and its end (`w h rowBytes 32 n `, then rows of premultiplied ARGB, the top one first), `~`. The @@ -52,7 +57,9 @@ //! lines and `1 (style) XW`: the drawn look is kept, named after the object. //! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's //! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is -//! read by a reader of its own and becomes a pattern swatch. In the version 7 form (§3.4) a list +//! read by a reader of its own and becomes a pattern swatch. An unpainted path whose dictionary +//! marks it as the tile's box (`AIPattern_Editor_Backing_Tile_Rect`) is left out of the art. In +//! the version 7 form (§3.4) a list //! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its //! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one: //! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix @@ -80,8 +87,18 @@ //! style's appearance and transparency is linked to it. A `1` naming a style the list doesn't //! have is the object's own appearance, not a link. //! -//! Sections the reader doesn't need (symbols, styles, filters) are skipped; -//! type, symbols, fills with a pattern it can't read, placed files without a preview and operators +//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the +//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration +//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of +//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names +//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx +//! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art, +//! it takes it to art space about the canvas point of art space's origin, as a pattern's +//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after +//! it. +//! +//! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it +//! can't read, fills with a pattern it can't read, placed files without a preview and operators //! it doesn't know are errors. So is data that ends inside a layer, a group or a compound path. use std::collections::{BTreeSet, HashMap, HashSet}; @@ -103,7 +120,7 @@ use super::super::ate::CANVAS_CENTRE; use super::super::graphics::HAIRLINE; use super::lex::{Lexer, Tok}; use super::obj::{self, Obj, V}; -use super::paint::{self, GradientDef, Instance, Named}; +use super::paint::{self, Global, GradientDef, Instance, Named, ShownNames}; use crate::ps; mod art; @@ -117,12 +134,12 @@ mod types; pub(crate) use art::join_and; use art::preview_png; -pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, palette, variables}; +pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, graphic_styles, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; pub use types::IMAGE_TOO_LARGE; -use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster}; +use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster, SymbolHead}; #[cfg(test)] -pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; +pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] @@ -153,6 +170,10 @@ pub struct Structure { /// Where the drawn looks lay that objects read with their art style took the place of (the /// document's coordinates): the page draws Illustrator's rendering of those styles there. pub restyled: Vec, + /// Where linked images whose pixels the data doesn't keep (`XF`) show a placeholder (the + /// document's coordinates). A PostScript page doesn't draw them there; a PDF part draws the + /// image's pixels. + pub placeholders: Vec, /// Placed files whose pixels the file puts at another point too: their image's id and the /// move, in its pixels, that places them there (the corner of the box they are written with, /// in place of the canvas point of art space's origin). @@ -199,7 +220,7 @@ pub(super) fn remember_xml_id(xml_ids: &mut HashMap>, byt /// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may /// keep the reduced one, which the PDF import reads as it is (#2031). pub fn read(data: &[u8], large_canvas: bool) -> Result { - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); r.large_canvas = large_canvas.then_some(1.0); r.run()?; r.finish() @@ -209,13 +230,129 @@ pub fn read(data: &[u8], large_canvas: bool) -> Result { /// data): the program's header gives the author and the custom colors the editing data's header /// doesn't. pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8]) -> Result { - let mut r = Reader::new(data); + let header = Reader::header_of(ps); + let mut r = Reader::with_names(data); r.large_canvas = large_canvas.then_some(1.0); + // The program's custom colors have swatches of their names, which no gradient or pattern takes. + for n in &header.custom_colors { + r.global_names.reserve(&n.name); + } r.run()?; - r.program_header(ps); + r.program_header(header); r.finish() } +/// The names the gradients and patterns of the editing data `data` get in the document +/// ([`ShownNames`]), with the names its other swatches can have reserved first: Registration, the +/// default swatches of both color modes when the palette the reader keeps is missing or empty, the +/// names that palette gives, the named colors, and the names without a newline of the gradients +/// and patterns. Names come only from what the reader reads: not from the alternates of versioned +/// content, the prolog, resources, sections it skips (such as symbols and the text document) or +/// what follows the trailer. The palette the reader keeps is the last one outside those and the +/// sections it reads on their own. +fn swatch_names(data: &[u8]) -> ShownNames { + /// The sections the reader reads on their own whose definitions and colors it keeps. + const READ_APART: &[&str] = &["BeginPattern", "BeginBrushPattern", "BeginPluginObject", "BeginArtStyles", "BeginArtStyleList"]; + /// Whether the marker `m` ends what began with `begin` and ends with `end`, `depth` of its kind + /// open inside it. + fn closes(begin: &str, end: &str, depth: &mut usize, m: &str) -> bool { + if !begin.is_empty() && m == begin { + *depth += 1; + } else if m == end { + match depth.checked_sub(1) { + Some(d) => *depth = d, + None => return true, + } + } + false + } + let mut names = ShownNames::default(); + names.reserve(vectorcraft_color::swatch::REGISTRATION); + let mut colors = paint::ColorNames::default(); + let mut lex = Lexer::new(data); + // What the reader skips wherever it is (the marker of one of its kind nested in it, its end + // marker, how many are open inside it, and where reading goes on when it doesn't end), the + // top-level section being passed over (the first three, and whether the reader reads it on its + // own), and where the palette being found starts. + let mut skip: Option<(&str, &str, usize, Option)> = None; + let mut section: Option<(&str, &str, usize, bool)> = None; + let (mut palette_at, mut palette) = (None, None); + // A pattern's name is the first string of its definition. + let mut head = false; + loop { + let before = lex.offset(); + let Some(t) = lex.next_token() else { + // Versioned content that doesn't end is read whole, as the reader reads it. + match skip.take() { + Some((.., Some(at))) => { + lex.seek(at); + continue; + } + _ => break, + } + }; + match &t.tok { + Tok::Comment(c) => { + let line = String::from_utf8_lossy(c); + let m = marker(&line); + if let Some((begin, end, depth, _)) = skip.as_mut() { + if closes(begin, end, depth, m) { + skip = None; + } + } else if let Some(at) = palette_at { + if m == "EndPalette" { + palette = Some(lex.slice(at, before)); + palette_at = None; + } + } else if m.starts_with("Alternate_Content") && section.is_none_or(|s| s.3) { + skip = Some(("Begin_Content_if_version_gt", "End_Versioned_Content", 0, Some(lex.offset()))); + } else if m == "%BeginProlog" { + skip = Some(("", "%EndProlog", 0, None)); + } else if m == "%BeginResource" { + skip = Some(("", "%EndResource", 0, None)); + } else if let Some((begin, end, depth, _)) = section.as_mut() { + if closes(begin, end, depth, m) { + section = None; + } + } else if m == "BeginPalette" { + palette_at = Some(lex.offset()); + } else if let Some((begin, end)) = types::SKIPPED.iter().find(|(b, _)| *b == m) { + section = Some((begin, end, 0, READ_APART.contains(begin))); + head = m == "BeginPattern"; + } else if matches!(m, "%PageTrailer" | "%Trailer") { + break; + } + continue; + } + // A palette's names are those of the palette kept, as the palette reads them. + _ if skip.is_some() || palette_at.is_some() || section.is_some_and(|s| !s.3) => continue, + Tok::Str(s) | Tok::Hex(s) if std::mem::take(&mut head) => { + let text = obj::text(s); + if !text.contains('\n') { + names.reserve(&text); + } + } + _ => {} + } + colors.token(t.tok); + } + colors.gradients.iter().filter(|n| !n.contains('\n')).for_each(|n| names.reserve(n)); + let palette = palette.map(super::palette::palette).unwrap_or_default(); + if palette.is_empty() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk] { + let (swatches, groups) = vectorcraft_color::default_swatches(mode.model()); + for g in &groups { + names.reserve(&g.name); + g.swatches.iter().for_each(|s| names.reserve(&s.name)); + } + swatches.iter().for_each(|s| names.reserve(&s.name)); + } + } + palette.own_names().for_each(|n| names.reserve(n)); + colors.names.iter().for_each(|n| names.reserve(n)); + names +} + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -234,6 +371,8 @@ struct Reader<'a> { to_doc: Option, cropmarks: Option, artboards: Vec, + /// The index in `artboards` of the active artboard (`CropAreaActive`). + active_board: Option, /// The user the header's `%%For` names. author: Option, /// The custom colors the header's `%%CMYKCustomColor` and `%%RGBCustomColor` define. @@ -247,6 +386,8 @@ struct Reader<'a> { /// The Objects on Path records of the `/Document` dictionary and the ids of the objects. on_path: on_path::OnPath, gradients: HashMap, + /// The names the gradients and patterns get in the document, by their names in the file. + global_names: ShownNames, gradient_def: Option, instance: Option, pending_fill: Option, @@ -257,10 +398,15 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The file `XG` names for the image after it (`XF`), until an image is read. + image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). place: Option, /// The last object read is the last child of the innermost frame, and nothing started since. after_object: bool, + /// The last object read is an image, and only the operators that end its raster (`XH`, `Xr`, + /// `N`) came since: its name and opacity mask still follow. + image_tail: bool, nodes: usize, /// What layers that show have that this reader doesn't read (errors). unsupported: BTreeSet, @@ -269,7 +415,24 @@ struct Reader<'a> { /// What layers that don't show have that this reader doesn't read. hidden_unread: BTreeSet, unread: Vec<(NodeId, Vec)>, + /// The art boxes (symbol space) of symbols whose definition can be measured but not read + /// whole, by their name in the file: their instances come in as the page draws them. symbol_bounds: HashMap, + /// The symbols read, by their name in the file → their name in the document. + symbol_names: HashMap, + /// The names the symbols read have in the document, and for each name read more than once, + /// the number its next copy is tried with. + symbol_taken: HashSet, + symbol_suffix: HashMap, + /// The art boxes (symbol space) of symbols read, by their name in the file, once measured for + /// an instance that comes in as the page draws it. + symbol_art_bounds: HashMap>, + /// The symbol list's names, in the Symbols panel's order (`%AI24_BeginSymbolList`). + symbol_list: Option>, + /// The symbols read were checked for instances of symbols the file doesn't have. + symbols_checked: bool, + /// This reader reads a symbol's definition (see [`Reader::define_symbol`]). + symbol: Option, /// Depth shared by pattern and symbol readers. subreader_depth: usize, pending_unread_fill: bool, @@ -341,6 +504,8 @@ struct Reader<'a> { palette: super::palette::Palette, /// See [`Structure::restyled`]. restyled: Vec, + /// See [`Structure::placeholders`]. + placeholders: Vec, /// See [`Structure::placed_elsewhere`]. placed_elsewhere: Vec<(NodeId, Affine)>, unread_elsewhere: Vec<(NodeId, Rect)>, @@ -410,6 +575,14 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool { } impl<'a> Reader<'a> { + /// A reader of the editing data `data` as a whole, with the names its gradients and patterns + /// get in the document found first ([`swatch_names`]). + fn with_names(data: &'a [u8]) -> Self { + let mut r = Self::new(data); + r.global_names = swatch_names(data); + r + } + fn new(data: &'a [u8]) -> Self { let mut doc = Document::new(1.0, 1.0); doc.layers.clear(); @@ -427,6 +600,7 @@ impl<'a> Reader<'a> { to_doc: None, cropmarks: None, artboards: Vec::new(), + active_board: None, author: None, custom_colors: Vec::new(), custom_more: None, @@ -434,6 +608,7 @@ impl<'a> Reader<'a> { variables: VariableRead::default(), on_path: on_path::OnPath::default(), gradients: HashMap::new(), + global_names: ShownNames::default(), gradient_def: None, instance: None, pending_fill: None, @@ -441,15 +616,24 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_link: None, place: None, foreign_data: None, after_object: false, + image_tail: false, nodes: 0, unsupported: BTreeSet::new(), unknown: BTreeSet::new(), hidden_unread: BTreeSet::new(), unread: Vec::new(), symbol_bounds: HashMap::new(), + symbol_names: HashMap::new(), + symbol_taken: HashSet::new(), + symbol_suffix: HashMap::new(), + symbol_art_bounds: HashMap::new(), + symbol_list: None, + symbols_checked: false, + symbol: None, subreader_depth: 0, pending_unread_fill: false, pending_unread_stroke: false, @@ -485,6 +669,7 @@ impl<'a> Reader<'a> { style_links: vec![], palette: super::palette::Palette::default(), restyled: vec![], + placeholders: vec![], placed_elsewhere: vec![], unread_elsewhere: vec![], mesh: None, diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 1df1b2d9c1..7eb55ad114 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -1,13 +1,14 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::types::{ - FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, + FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, Place, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; +use vectorcraft_doc::links::missing_placeholder; impl<'a> Reader<'a> { /// A text object (`/AI11Text`): an empty group standing for it, named after its story. @@ -15,6 +16,7 @@ impl<'a> Reader<'a> { if self.pattern.is_some() { self.unreadable("type in a pattern", false); } + self.left_out_of_symbol(); // `1 /FreeUndo`: type in a drawn look. Its story is one of another text document // (`/AI11UndoFreeTextDocument`), which counts its stories on its own, so its slot has none. // In the look of a text object that has an appearance, the object itself follows the look, @@ -45,6 +47,11 @@ impl<'a> Reader<'a> { /// group. Without data, or with a PDF that can't be read, nothing is drawn. pub(super) fn foreign_art(&mut self, o: &Obj) -> Result<(), String> { let Some(text) = self.foreign_data.take() else { return Ok(()) }; + // Where a symbol's art puts it isn't known. + if self.symbol.is_some() { + self.left_out_of_symbol(); + return Ok(()); + } // One `%` starts each line; the rest, `_` included, is data. let mut encoded = String::with_capacity(text.len()); for line in text.split(|b| matches!(b, b'\r' | b'\n')) { @@ -164,6 +171,9 @@ impl<'a> Reader<'a> { self.path_kinds.clear(); self.points = 0; self.clip_next = false; + if let Some(head) = self.symbol.as_mut() { + (head.missing_fill, head.missing_stroke) = (false, false); + } } /// Paint the current path (`op`), as a guide when `guide`. @@ -176,6 +186,7 @@ impl<'a> Reader<'a> { self.set_instance(&i); } let (fill_paint, stroke_paint) = (self.pending_fill.take(), self.pending_stroke.take()); + let missing = self.symbol.as_mut().map_or((false, false), |h| (std::mem::take(&mut h.missing_fill), std::mem::take(&mut h.missing_stroke))); if bp.elements().is_empty() { return Ok(()); } @@ -195,6 +206,10 @@ impl<'a> Reader<'a> { "b" => (true, true), _ => (false, false), }; + // A symbol's art painted with a gradient the file doesn't define is left out. + if (missing.0 && fill) || (missing.1 && stroke) { + self.left_out_of_symbol(); + } // A gradient instance's paint replaces the missing pattern. let unread = (fill && self.pending_unread_fill && fill_paint.is_none()) || (stroke && self.pending_unread_stroke && stroke_paint.is_none()); let mut items = Vec::new(); @@ -352,15 +367,20 @@ impl<'a> Reader<'a> { 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 - // origin, as the file's PDF part draws them. - if self.pattern.is_some() + // origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are. + if (self.pattern.is_some() || self.symbol.is_some()) && i.has_matrix() && let Some(t) = self.template { let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]); } - match i.paint(&self.gradients, to_doc) { + let paint = i.paint(&self.gradients, &self.global_names, to_doc); + if let Some(head) = self.symbol.as_mut() { + let missing = if i.stroke { &mut head.missing_stroke } else { &mut head.missing_fill }; + *missing = paint.is_none(); + } + match paint { Some(p) if i.stroke => self.pending_stroke = Some(p), Some(p) => self.pending_fill = Some(p), None => { @@ -383,25 +403,59 @@ impl<'a> Reader<'a> { self.image_from(vals, data) } + /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits + /// ImageType AlphaChannelCount reserved bin-ascii ImageMask`, as `XI` and `XF` take them); `None` + /// without a matrix or with fewer numbers than up to the encoding (bin-ascii). + fn image_operands(vals: &[V]) -> Option<(Vec, Vec)> { + let m = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None })?; + let n = Self::nums(vals); + (n.len() >= 11).then_some((m, n)) + } + + /// `XG` (`w`, which names the file of the image after it) or `XF` (that image), with their + /// operands `vals`. Before the art, the setup's procedures run: there they do nothing. + pub(super) fn image_link_op(&mut self, w: &str, vals: Vec, hidden: bool) -> Result<(), String> { + if self.frames.is_empty() { + return Ok(()); + } + if w == "XG" { + self.image_link = Self::image_link(&vals); + return Ok(()); + } + self.linked_image(vals, hidden) + } + + /// The file `XG`'s operands (`(path) modified`) name; `None` for operands of another shape or + /// an empty path. + fn image_link(vals: &[V]) -> Option { + match vals { + [.., V::Str(path), V::Num(_)] if !path.is_empty() => Some(super::obj::text(path)), + _ => None, + } + } + /// An image of operands `vals` and samples `data`. pub(super) fn image_from(&mut self, vals: Vec, data: &[u8]) -> Result<(), String> { + // A file `XG` named before this image isn't the file of a later `XF`. + self.image_link = None; let space = self.raster.as_ref().and_then(|r| r.space.clone()).unwrap_or_default(); - let Some(m) = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None }) else { - self.warn("an image VectorCraft can't read was left out"); + let Some((m, n)) = Self::image_operands(&vals) else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let n = Self::nums(&vals); - let [_, _, _, _, w, h, bits, kind, alpha, _, binary, ..] = n.as_slice() else { - self.warn("an image VectorCraft can't read was left out"); + let [_, _, _, _, w, h, bits, kind, alpha, _, binary, rest @ ..] = n.as_slice() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; + // ImageMask 1: the image is transparent and takes a color (version 7 specification §8.1). + let image_mask = rest.first() == Some(&1.0); let (w, h) = (*w as u64, *h as u64); if w.saturating_mul(h) > MAX_PIXELS { - self.warn(IMAGE_TOO_LARGE); + self.image_left_out(IMAGE_TOO_LARGE); return Ok(()); } if w == 0 || h == 0 || ![1.0, 8.0].contains(bits) { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } let channels: usize = match space.as_str() { @@ -427,7 +481,7 @@ impl<'a> Reader<'a> { // An alpha channel follows the colour samples, one byte a pixel. let alpha_len = if *alpha > 0.0 { (w * h) as usize } else { 0 }; let (Some(samples), opacity) = (data.get(..need), data.get(need..need.saturating_add(alpha_len))) else { - self.warn("an image whose data is cut short was left out"); + self.image_left_out("an image whose data is cut short was left out"); return Ok(()); }; let opacity = opacity.filter(|_| alpha_len > 0); @@ -437,7 +491,10 @@ impl<'a> Reader<'a> { && *bits == 8.0 && let Some(blob) = Inks::new(w as u32, h as u32, samples.to_vec()).and_then(|i| ImageBlob::cmyk_tiff(&i)) { - return self.add_raster(blob, opacity, &m, (w as u32, h as u32)); + return self.add_raster(blob, opacity, &m, (w as u32, h as u32), None); + } + if image_mask && channels == 1 && *bits == 1.0 { + return self.colorized_raster(samples, row, opacity, &m, (w as u32, h as u32)); } let mut rgba = Vec::with_capacity((w * h * 4) as usize); for y in 0..h as usize { @@ -465,38 +522,145 @@ impl<'a> Reader<'a> { } } let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; let mut png = vec![]; if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } - self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32)) + self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) + } + + /// A 1-bit gray image whose ImageMask is 1 (`samples`, `row` bytes a row): a grayscale image + /// colorized with the fill color. Its 0 bits, which open black with ImageMask 0, take that color, + /// and its 1 bits are transparent. A fill that isn't a solid color colorizes it black. + fn colorized_raster(&mut self, samples: &[u8], row: usize, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + let mut gray = Vec::with_capacity(w as usize * h as usize); + for y in 0..h as usize { + let line = samples.get(y * row..(y + 1) * row).unwrap_or_default(); + for x in 0..w as usize { + let v = line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255); + gray.push(v); + } + } + let mut png = vec![]; + let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)); + if !matches!(written, Some(Ok(()))) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let paint = self.mask_paint(); + self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) + } + + /// The color that colorizes an image mask: the fill color, or black when the fill isn't a + /// solid color. + fn mask_paint(&self) -> Paint { + match &self.gs.fill { + p @ Paint::Solid { .. } => p.clone(), + _ => Paint::solid(vectorcraft_color::Color::BLACK), + } + } + + /// `XF` (§8.2): an image whose pixels are in the file the `XG` before it names becomes a linked + /// image of that file, of its `w` × `h` pixels placed as the matrix maps them, as `XI` places an + /// image. The data keeps no pixels or preview of it, so a placeholder is spread over those pixels + /// until its file is found. A 1-bit image mask is colorized as `XI` colorizes one. One without + /// that file name, or whose operands `XI` couldn't read (no + /// matrix, too few numbers, no pixels, or samples of other than 1 or 8 bits), is left out with a + /// warning. No pixels are read, so its size isn't held to the limit on `XI`'s samples. + fn linked_image(&mut self, vals: Vec, hidden: bool) -> Result<(), String> { + let path = self.image_link.take(); + let operands = Self::image_operands(&vals); + let (Some(path), Some((m, n))) = (path, operands) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let (&[a, b, c, d, tx, ty], &[_, _, _, _, w, h, bits, ..]) = (m.as_slice(), n.as_slice()) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + if !(1.0..=MAX_SIDE).contains(&w) || !(1.0..=MAX_SIDE).contains(&h) || ![1.0, 8.0].contains(&bits) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let (w, h) = (w as u32, h as u32); + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let xf = to_doc * Affine::new([a, b, c, d, tx, ty]) * FLIP; + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let Some(png) = missing_placeholder() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + // The placeholder is all the document has of the file: what a missing link shows. + let bytes = Arc::new(png); + let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; + let key = linked_key(&blob, &path); + self.doc.images.entry(key.clone()).or_insert(blob); + self.warn(LINKED_PLACEHOLDERS); + // A PostScript page doesn't draw the placeholder: there its pixels are left out of the + // comparisons with the page. + if !hidden && !self.gs.hidden && self.shown() { + self.placeholders.push(xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))); + } + let im = ImageObject { key, width: w, height: h, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }; + // A 1-bit image mask (ImageMask 1) keeps the color that colorizes it once its file is relinked. + let image_mask = bits == 1.0 && n.get(7) == Some(&1.0) && n.get(11) == Some(&1.0); + let colorize = image_mask.then(|| self.mask_paint()); + self.add_image_colorized(im, None, colorize, hidden) } /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image. - fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + /// image, and `colorize` as the color that colorizes it. + fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead // gives the same place only when the image isn't rotated (b = c = 0). let [a, b, c, d, tx, ty] = m else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let to_doc = self.space(); let xf = to_doc * Affine::new([*a, *b, *c, *d, *tx, *ty]) * FLIP; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } let mask = alpha.and_then(|a| self.alpha_mask(a, w, h, xf)); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); - self.add_image_masked(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }, mask, false) + let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; + self.add_image_colorized(im, mask, colorize, false) + } + + /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't + /// read whole, so its instances come in as the page draws them. + fn image_left_out(&mut self, warning: &str) { + if self.symbol.is_some() { + self.left_out_of_symbol(); + } else { + self.warn(warning); + } + } + + /// Note art of a symbol's definition that is left out: the symbol isn't kept, and its + /// instances come in as the page draws them, within the box of the art that is read. + pub(super) fn left_out_of_symbol(&mut self) { + if let Some(head) = self.symbol.as_mut() { + head.left_out = true; + } } /// An image's alpha channel (`w` × `h` bytes) as a grayscale image over the image (`xf`): its @@ -524,18 +688,33 @@ impl<'a> Reader<'a> { /// Add an image object with the state's transparency and `mask` as its opacity mask. fn add_image_masked(&mut self, im: ImageObject, mask: Option, hidden: bool) -> Result<(), String> { + self.add_image_colorized(im, mask, None, hidden) + } + + /// Add an image object with the state's transparency, `mask` as its opacity mask and + /// `colorize` as the color that colorizes it. + fn add_image_colorized(&mut self, im: ImageObject, mask: Option, colorize: Option, hidden: bool) -> Result<(), String> { let gs = self.gs.clone(); let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs); node.opacity = gs.opacity; node.blend = gs.blend; node.extras_mut().mask = mask.map(Box::new); - self.add(node, hidden) + node.extras_mut().colorize = colorize.map(Box::new); + self.add(node, hidden)?; + self.image_tail = self.after_object; + Ok(()) } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that /// shows the preview the data keeps of it, as a linked image whose file is missing does. One /// without a preview, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { + // Where a symbol's art puts a placed file's pixels isn't known. + if self.symbol.is_some() { + self.place = None; + self.left_out_of_symbol(); + return Ok(()); + } let (m, b, path, png, w, h, folder) = match self.place.take() { Some(Place { broken: true, .. }) => { self.unreadable("placed files", hidden); @@ -597,7 +776,7 @@ impl<'a> Reader<'a> { // The preview is all the document has of the file: what a missing link shows. let bytes = Arc::new(png); let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; - let key = blob.content_key(); + let key = linked_key(&blob, &path); self.doc.images.entry(key.clone()).or_insert(blob); self.warn(LINKED_PREVIEWS); if let Some(shift) = elsewhere @@ -712,17 +891,28 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } /// A placed file's path relative to the document's folder (`/` separators): its relative `folder` -/// (`src/`, `..\art`) followed by its file `name`. `None` when the folder is empty, absolute, or -/// holds control characters, or when there is no name. +/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the +/// document's own folder). `None` when the folder is absolute or holds control characters, or +/// when there is no name. pub(super) fn relative_path(folder: &str, name: &str) -> Option { let folder = folder.replace('\\', "/"); let absolute = folder.starts_with('/') || folder.as_bytes().get(1) == Some(&b':') || folder.contains("://"); - if folder.is_empty() || absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) { + if absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) { return None; } + if folder.is_empty() { + return Some(name.to_string()); + } Some(format!("{}/{name}", folder.trim_end_matches('/'))) } +/// The image key of a linked image of the file at `path` that shows `blob` (its preview or a +/// placeholder): the blob's own key and the path's. Images of other files that show the same pixels +/// have keys of their own, and reading one file's pixels in changes that file's images only. +fn linked_key(blob: &ImageBlob, path: &str) -> String { + format!("{}-{}", blob.content_key(), vectorcraft_doc::links::hash_bytes(path.as_bytes())) +} + pub(super) fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_SIDE) } diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 2273f087ba..f6ac4a00ae 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -1,7 +1,9 @@ use super::document::slot_of; use super::ops::{paints_apart, path_rule}; use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope}; -use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj}; +use super::{ + AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashMap, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj, +}; use vectorcraft_doc::TextWrap; impl<'a> Reader<'a> { @@ -13,6 +15,7 @@ impl<'a> Reader<'a> { } if matches!(kind, Kind::Layer(_)) { self.ensure_space(); + self.check_symbols(); } let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) }; self.frames.push(Frame { @@ -133,7 +136,7 @@ impl<'a> Reader<'a> { // Some files mark every group so, the plain one holding the subpaths too (#980): one // paint for all its paths keeps it one compound path, its holes cut. Kind::Compound if kids.iter().any(|k| self.looks.contains(&k.id) && paints_apart(k)) => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, true, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } Kind::Compound => { @@ -153,7 +156,7 @@ impl<'a> Reader<'a> { } // A group with a clipping path (`q` … `Q`, or a `W` path in a group) is a clipping group. _ => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, false, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } }; @@ -200,9 +203,76 @@ impl<'a> Reader<'a> { Some(n) } + /// How deep in the document the objects the open frames hold are, less one: a dictionary adds no level, and an + /// opacity mask's art is two under the frames around the object it masks. + fn nesting(&self) -> usize { + self.frames + .iter() + .map(|f| match f.kind { + Kind::Obj(_) => 0, + Kind::Mask => 2, + _ => 1, + }) + .sum() + } + + /// `kids` with the clipping paths among them (indexes `clips`) first → the children and whether they clip. + /// + /// Several clipping paths in a clipping group or a layer clip to their intersection, as each `W` reduces the clip + /// set by the ones before it: each clipping path after the first clips a clipping group nested in the one before + /// it, and the innermost one holds the art. As with one clipping path, every object in the group is clipped by all + /// of them, wherever it is written. A clipping path's painted fill stays at its path's level. In a compound path + /// (`union`), several clipping paths are one compound path. `at`: how deep the group or layer made of them is in the + /// document. + fn clip_first(&mut self, kids: Vec, clips: &[usize], union: bool, at: usize) -> Result<(Vec>, bool), String> { + if union || clips.len() < 2 { + return Ok(self.clip_union(kids, clips)); + } + let clips: std::collections::HashSet = clips.iter().copied().collect(); + let (clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); + let innermost = clip.len() - 1; + // A painted fill follows its clipping path; the art goes in the innermost level. + let level = |i: usize, n: &Node| { + if self.clip_fills.contains(&n.id) { clip.iter().rposition(|(c, _)| *c < i).unwrap_or(0) } else { innermost } + }; + // Each nested clipping group adds a level over the nodes placed in it, the clipping paths included. Past the + // reader's limit, or past the document's when the nodes fit in it without those levels (the document would merge + // the deepest groups and drop their clipping paths), the editing data isn't read. + let deepest = + rest.iter().map(|(i, n)| level(*i, n) + depth(n)).chain(clip.iter().enumerate().map(|(k, (_, n))| k + depth(n))).max().unwrap_or(0); + let flat = rest.iter().map(|(_, n)| depth(n)).chain(clip.iter().map(|(_, n)| depth(n))).max().unwrap_or(0); + if at + deepest > MAX_DEPTH || (at + deepest > vectorcraft_doc::MAX_DEPTH && at + flat <= vectorcraft_doc::MAX_DEPTH) { + return Err("its clipping masks are nested too deeply".into()); + } + // Each level: its clipping path, the clipping paths' own fills, which paint under the art they clip, then the + // art. + let mut fills_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + let mut art_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + for (i, n) in rest { + let k = level(i, &n); + let at = if self.clip_fills.contains(&n.id) { &mut fills_at } else { &mut art_at }; + if let Some(v) = at.get_mut(k) { + v.push(n); + } + } + let mut children: Vec> = Vec::new(); + let mut levels = clip.into_iter().map(|(_, n)| n).zip(fills_at.into_iter().zip(art_at)).rev().peekable(); + while let Some((path, (fills, art))) = levels.next() { + let mut inner: Vec> = Vec::with_capacity(fills.len() + art.len() + children.len() + 1); + inner.push(Arc::new(path)); + inner.extend(fills.into_iter().chain(art).map(Arc::new)); + inner.append(&mut children); + if levels.peek().is_none() { + return Ok((inner, true)); + } + children = vec![Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children: inner, clip: true }))]; + } + Ok((children, false)) + } + /// `kids` with the clipping paths among them (indexes `clips`) first, several as one compound /// path → the children and whether they clip. - fn clip_first(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { + fn clip_union(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { let clips: std::collections::HashSet = clips.iter().copied().collect(); let (mut clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); let clip_node = match clip.len() { @@ -245,7 +315,7 @@ impl<'a> Reader<'a> { (mesh.opacity, mesh.blend, mesh.isolate, mesh.knockout) = before; } let Kind::Layer(a) = f.kind else { return Ok(()) }; - let (children, clip) = self.clip_first(f.children, &f.clips); + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 1)?; let color = a.color.unwrap_or(LayerColor::Preset(0)); let mut layer = Node::new( self.doc.alloc_id(), @@ -307,7 +377,8 @@ impl<'a> Reader<'a> { pub(super) fn end_mask(&mut self) -> Result<(), String> { self.end_path_quietly(); let f = self.close("X+", |k| matches!(k, Kind::Mask))?; - let (children, clip) = self.clip_first(f.children, &f.clips); + // The mask's art is one level under the object it masks. + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 2)?; let art = self.new_node(NodeKind::Group { children, clip }, &f.gs); self.gs = f.gs; self.pending_unread_fill = f.pending_unread_fill; @@ -480,24 +551,141 @@ impl<'a> Reader<'a> { Ok(Some(id)) } + /// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its + /// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is + /// written about the canvas point of art space's origin, and the name is the file's until the + /// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one + /// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`, + /// comes in as the page draws it, within the symbol's box placed by the matrix when the box is + /// known. fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> { - let bounds = o.get("SymbolRef").and_then(|v| v.iter().find_map(V::text)).and_then(|name| self.symbol_bounds.get(&name).copied()); - let matrix = o - .get("Matrix") - .or_else(|| o.get("Transform")) - .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))); - let box_at_canvas = match (bounds, matrix.as_deref()) { - (Some(b), Some([a, c, d, e, x, y])) if [*a, *c, *d, *e, *x, *y].iter().all(|n| n.is_finite()) => { - Some(self.space().transform_rect_bbox(super::Affine::new([*a, *c, *d, *e, *x, *y]).transform_rect_bbox(b))) - } + let name = o.text("SymbolRef"); + let affine = |n: &[f64]| match n { + [a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])), _ => None, }; - match box_at_canvas { - Some(b) => self.unread_box("symbols", b, self.obj_hidden).map(|_| ()), - None => { - self.unreadable("symbols", self.obj_hidden); - Ok(()) + let live = affine(&o.nums("RTransformMatrix")); + let boxed_only = live.is_none(); + let matrix = live.or_else(|| { + o.get("Matrix") + .or_else(|| o.get("Transform")) + .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))) + .and_then(|n| affine(&n)) + }); + let hidden = self.obj_hidden; + let place = if self.symbol.is_some() { + self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])) + } else { + Some(self.space()) + }; + let (Some(name), Some(m), Some(place)) = (name, matrix, place) else { + self.unreadable("symbols", hidden); + return Ok(()); + }; + let xf = place * m; + let usable = xf.determinant().abs() >= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite()); + let symbol = if self.symbol.is_some() { Some(name.clone()) } else { self.symbol_names.get(&name).cloned() }; + match symbol.filter(|_| usable && !boxed_only && !overrides(o)) { + Some(symbol) => { + // Its transparency is the `Xy` after it, as a group's is. + let gs = self.gs.clone(); + let node = self.new_node(NodeKind::SymbolInstance { symbol, xf }, &gs); + self.add(node, hidden) } + None => { + let bounds = self.symbol_art_bounds(&name).or_else(|| self.symbol_bounds.get(&name).copied()); + match bounds.map(|b| xf.transform_rect_bbox(b)).filter(|_| usable && self.symbol.is_none()) { + Some(b) => self.unread_box("symbols", b, hidden).map(|_| ()), + None => { + self.unreadable("symbols", hidden); + Ok(()) + } + } + } + } + } + + /// The art box (symbol space) of the symbol read under `name` (its name in the file), measured + /// once. + fn symbol_art_bounds(&mut self, name: &str) -> Option { + if let Some(b) = self.symbol_art_bounds.get(name) { + return *b; + } + let named = self.symbol_names.get(name)?; + let boxes = self.doc.symbol_boxes(); + let b = self.doc.symbols.iter().find(|s| &s.name == named).and_then(|s| s.art.visual_bounds_with(&boxes)); + drop(boxes); + self.symbol_art_bounds.insert(name.to_string(), b); + b + } + + /// Check the symbols read for instances in their art of symbols the file doesn't have, before + /// the first layer: a symbol with one isn't kept, and so on for the symbols holding its + /// instances. The instances in the art kept then name the symbols as the document does. + pub(super) fn check_symbols(&mut self) { + if std::mem::replace(&mut self.symbols_checked, true) { + return; + } + // Each symbol's name in the file (none for one named as an earlier one), and the names its + // instances use. + let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect(); + let defs: Vec<(Option, Vec)> = self + .doc + .symbols + .iter() + .map(|s| { + let mut uses = vec![]; + symbol_uses(&s.art, &mut uses, 0); + (files.get(s.name.as_str()).map(|f| f.to_string()), uses.into_iter().map(str::to_string).collect()) + }) + .collect(); + // A symbol goes when one of its instances names a symbol that isn't kept: first those + // naming one the file doesn't have, then, one at a time, those using a symbol that went. + let mut kept: Vec = vec![true; defs.len()]; + let mut users: HashMap<&str, Vec> = HashMap::new(); + let mut going: Vec = vec![]; + for (i, (_, uses)) in defs.iter().enumerate() { + for u in uses { + users.entry(u.as_str()).or_default().push(i); + } + if uses.iter().any(|u| !self.symbol_names.contains_key(u)) { + going.push(i); + } + } + while let Some(i) = going.pop() { + match kept.get_mut(i) { + Some(k) if *k => *k = false, + _ => continue, + } + if let Some(file) = defs.get(i).and_then(|(file, _)| file.as_deref()) { + going.extend(users.get(file).into_iter().flatten().copied().filter(|j| kept.get(*j).copied().unwrap_or(false))); + } + } + drop(users); + if kept.iter().any(|k| !k) { + let left: Vec<(Option, String)> = defs + .iter() + .zip(&self.doc.symbols) + .zip(&kept) + .filter(|(_, k)| !**k) + .map(|(((file, _), s), _)| (file.clone(), s.name.clone())) + .collect(); + let mut i = 0; + self.doc.symbols.retain(|_| { + i += 1; + kept.get(i - 1).copied().unwrap_or(false) + }); + // Their art's box isn't known (the instances that made them go have none), so their + // instances have no box either. + for (file, named) in left { + self.doc.set_symbol_registration(&named, vectorcraft_doc::SymbolRegistration::CENTER); + let Some(file) = file else { continue }; + self.symbol_names.remove(&file); + } + } + let names = self.symbol_names.clone(); + for s in &mut self.doc.symbols { + rename_uses(Arc::make_mut(&mut s.art), &names, 0); } } @@ -573,6 +761,8 @@ impl<'a> Reader<'a> { let mut blend = Node::new(self.doc.alloc_id(), kind); (blend.name, blend.visible, blend.locked) = (steps.name.take(), steps.visible, steps.locked); (blend.opacity, blend.blend, blend.isolate, blend.knockout) = (steps.opacity, steps.blend, steps.isolate, steps.knockout); + // Its note, URL and data (object tags) too. + blend.extras_mut().attrs = steps.extras_mut().attrs.take(); f.children.push(blend); } None => { @@ -723,6 +913,68 @@ pub(super) fn drop_commented_copies(layers: &mut [Arc], hidden: &HashSet(node: &'n Node, out: &mut Vec<&'n str>, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + out.push(symbol); + } + if let Some(m) = &node.extras().mask { + symbol_uses(&m.art, out, depth + 1); + } + for c in node.children().into_iter().flatten() { + symbol_uses(c, out, depth + 1); + } +} + +/// The instances in `node`, and in the art of its opacity masks, named by `names` (a name in the +/// file → the symbol's in the document). +fn rename_uses(node: &mut Node, names: &HashMap, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &mut node.kind + && let Some(named) = names.get(symbol.as_str()) + { + symbol.clone_from(named); + } + if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) { + rename_uses(Arc::make_mut(&mut m.art), names, depth + 1); + } + for c in node.children_mut().into_iter().flatten() { + rename_uses(Arc::make_mut(c), names, depth + 1); + } +} + +/// Whether a symbol instance's dictionary carries appearance of its own (a dynamic symbol's +/// edits), which isn't read. +fn overrides(o: &Obj) -> bool { + const KEYS: [&str; 5] = [ + "AI19SymbolAppearanceMap", + "AI19SymbolOverriddenSymbolMap", + "AI Local Art of Symbol Instance", + "AI15 Layer In Symbol", + "AI15 Color Of Layer In Symbol", + ]; + // In a dictionary or array nested in it, as a keyed entry's value, in an array or among the + // values closed without a key. + fn has(o: &Obj, depth: usize) -> bool { + depth <= 8 + && (o.entries.iter().any(|(k, v)| k.as_deref().is_some_and(|k| KEYS.contains(&k)) || v.iter().any(|v| in_value(v, depth + 1))) + || o.content.iter().any(|v| in_value(v, depth + 1))) + } + fn in_value(v: &V, depth: usize) -> bool { + match v { + V::Obj(c) => has(c, depth), + V::Arr(items) => depth <= 8 && items.iter().any(|v| in_value(v, depth + 1)), + _ => false, + } + } + has(o, 0) +} + /// Close the subpath `bp` ends with, if it has one open. pub(super) fn close(bp: &mut BezPath) { if bp.elements().last().is_some_and(|e| !matches!(e, PathEl::ClosePath)) { @@ -730,6 +982,20 @@ pub(super) fn close(bp: &mut BezPath) { } } +/// How many levels of nodes `n` holds, itself included, its opacity masks' art included. +fn depth(n: &Node) -> usize { + let mut deepest = 0; + let mut todo = vec![(n, 1)]; + while let Some((n, d)) = todo.pop() { + deepest = deepest.max(d); + todo.extend(n.children().into_iter().flatten().map(|c| (c.as_ref(), d + 1))); + if let Some(m) = n.extras().mask.as_ref() { + todo.push((m.art.as_ref(), d + 1)); + } + } + deepest +} + /// The fill rule of a path or compound node. /// `kids` with the members of each plain group among them in the group's place, at any depth. fn ungrouped(kids: Vec) -> Vec { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index b1c9db39d3..c5f64079cb 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,10 +1,13 @@ +use std::collections::HashMap; + use super::super::brush; use super::art::{four, sane, two}; use super::types::{ - FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, - VERSIONED_UNENDED, + FLIP, GState, Kind, MAX_DEPTH, MAX_HEX, MAX_LISTED, MAX_NODES, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, MAX_SYMBOLS, + PatternHead, Place, Raster, SKIPPED, SymbolHead, VERSIONED_UNENDED, }; -use super::{Arc, Lexer, Node, PatternDef, Reader, Rect, Tok, V, marker, obj}; +use super::{Arc, Global, Lexer, Node, NodeKind, PatternDef, Reader, Rect, Tok, V, marker, obj}; +use vectorcraft_doc::{NodeId, Symbol, SymbolRegistration}; impl<'a> Reader<'a> { pub(super) fn push(&mut self, v: V) -> Result<(), String> { @@ -85,7 +88,7 @@ impl<'a> Reader<'a> { } let m = marker(line); // A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete. - if m == "BeginPattern" { + if m == "BeginPattern" && self.symbol.is_none() { let section = self.section("EndPattern")?; if self.pattern.is_some() { self.unsupported.insert("patterns inside patterns".into()); @@ -96,7 +99,12 @@ impl<'a> Reader<'a> { } if m == "BeginSymbol" { let section = self.section("EndSymbol")?; - self.symbol_bounds(section); + self.define_symbol(section); + return Ok(()); + } + if m == "BeginSymbolList" { + let section = self.section("EndSymbolList")?; + self.symbol_list(section); return Ok(()); } // Brushes and their art (those in a pattern's or a brush's art aren't read). @@ -127,6 +135,9 @@ impl<'a> Reader<'a> { } if m == "BeginEncoding" { self.type_state.encoding_comment(line); + let section = self.section("EndEncoding")?; + self.encoding_section(section); + return Ok(()); } // Versioned content holds alternatives of the same art, the newest first: the first is // read, and the next one (`%AI17_Alternate_Content`, or `…_if_version_gt:` for a version @@ -160,8 +171,12 @@ impl<'a> Reader<'a> { return Ok(()); } if line.starts_with("AI5_BeginRaster") { + // An `XG` outside a raster object names no image in it. + self.image_link = None; self.raster = Some(Raster::default()); } else if line.starts_with("AI5_EndRaster") { + // A file `XG` named in this raster object is no later one's. + self.image_link = None; if let Some(Raster { operands: Some(vals), hex, .. }) = self.raster.take() { return self.image_from(vals, &hex); } @@ -303,6 +318,8 @@ impl<'a> Reader<'a> { _ => return, }; if !name.trim().is_empty() && !self.custom_colors.iter().any(|n| n.name == name) { + // A gradient or pattern defined after it does not take its swatch's name. + self.global_names.reserve(&name); self.custom_colors.push(super::Named { name, color, tint: 1.0, spot: true }); } } @@ -355,13 +372,15 @@ impl<'a> Reader<'a> { let mut sub = Reader::new(section); sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead::default()); - // The gradients defined so far, lent (and those it defines kept). + // The gradients defined so far and the names given, lent (and those it defines kept). sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); sub.nodes = self.nodes; sub.template = self.template; let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); // Unread art in the definition, hidden or not, leaves the tile incomplete. let whole = read.is_ok() && sub.unsupported.is_empty() @@ -380,6 +399,7 @@ impl<'a> Reader<'a> { sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) }); sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); sub.nodes = self.nodes; sub.template = self.template; let mut read = sub.open(Kind::Group, false); @@ -391,6 +411,7 @@ impl<'a> Reader<'a> { } self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); let whole = read.is_ok() && sub.unsupported.is_empty() && sub.unknown.is_empty() @@ -466,15 +487,17 @@ impl<'a> Reader<'a> { return; }; let art: Vec> = frame.children.iter().map(|n| Arc::new(self.doc.reid(n))).collect(); - let mut def = PatternDef::new(&head.name, art); + // Fills and the tables look the pattern up by its name in the file; the document has it by + // the name it shows. + let mut def = PatternDef::new(&self.global_names.define(Global::Pattern, &head.name), art); def.tile = FLIP.transform_rect_bbox(tile); - if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() { + if self.pattern_tiles.insert(head.name.clone(), def.tile).is_some() { self.doc.patterns.retain(|p| p.name != def.name); } if v7 { - self.v7_patterns.insert(def.name.clone()); + self.v7_patterns.insert(head.name); } else { - self.v7_patterns.remove(&def.name); + self.v7_patterns.remove(&head.name); } self.doc.patterns.push(def); for (key, blob) in sub.doc.images { @@ -489,32 +512,165 @@ impl<'a> Reader<'a> { } } - /// Read a definition's box for an instance whose art must come from the page. - fn symbol_bounds(&mut self, section: &[u8]) { - if self.symbol_bounds.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { + /// A symbol's definition (`section`: what follows `%AI14_BeginSymbol`), read by a reader of its + /// own into a symbol of the document, its art in the symbol's space (y down), named as the file + /// names it unless another symbol has that name. A definition inside another one or inside a + /// pattern's isn't read, nor is one after the first layer (the symbols were checked there, see + /// [`Reader::check_symbols`]). One it can't read whole (an operator it doesn't know, type, unbalanced + /// groups, art it leaves out) isn't kept: its instances come in as the page draws them, within + /// its art's box when that can be measured. + fn define_symbol(&mut self, section: &[u8]) { + if self.symbol.is_some() + || self.pattern.is_some() + || self.symbols_checked + || self.subreader_depth >= MAX_SUBREADERS + || self.doc.symbols.len() + self.symbol_bounds.len() >= MAX_SYMBOLS + { return; } - let mut lex = super::Lexer::new(section); - let name = match lex.next_token().map(|t| t.tok) { - Some(Tok::Str(bytes)) => super::obj::text(&bytes), + let name = match Lexer::new(section).next_token().map(|t| t.tok) { + Some(Tok::Str(bytes)) => obj::text(&bytes), _ => return, }; let mut sub = Reader::new(section); sub.subreader_depth = self.subreader_depth + 1; - sub.cropmarks = self.cropmarks; + sub.symbol = Some(SymbolHead::default()); sub.template = self.template; + // The gradients, art styles and patterns defined so far and the names given, lent. + sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); + sub.styles = std::mem::take(&mut self.styles); + sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.v7_patterns.clone_from(&self.v7_patterns); sub.nodes = self.nodes; let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); self.nodes = sub.nodes; - if read.is_err() || !sub.unsupported.is_empty() || !sub.unknown.is_empty() || sub.frames.len() != 1 { + self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); + self.styles = std::mem::take(&mut sub.styles); + self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + // Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or + // gradient still open at the end (as [`Reader::run_string`] checks), isn't whole. + let open = sub.done + || sub.stack.iter().any(|v| matches!(v, V::Mark)) + || !sub.marks.is_empty() + || sub.text.is_some() + || sub.raster.is_some() + || sub.place.is_some() + || sub.mesh.is_some() + || sub.gradient_def.is_some(); + let head = sub.symbol.take().unwrap_or_default(); + let registration = head.registration; + let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; + let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; + let mut kids = frame.children; + // Where a symbol's art puts a pattern's tiles isn't known. + let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0)); + if !whole { + let boxes = self.doc.symbol_boxes(); + let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes))); + drop(boxes); + if let Some(b) = bounds.filter(|b| sane(*b) && b.area() > 0.0) { + self.symbol_bounds.insert(name, b); + } return; } - let Some(frame) = sub.frames.pop() else { return }; - let bounds = frame.children.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds())); - let Some(bounds) = bounds.map(|b| sub.space().inverse().transform_rect_bbox(b)) else { return }; - if sane(bounds) && bounds.area() > 0.0 { - self.symbol_bounds.insert(name, bounds); + let art = match (kids.len(), kids.pop()) { + (1, Some(one)) => one, + (_, last) => Node::group(self.doc.alloc_id(), kids.into_iter().chain(last).map(Arc::new).collect()), + }; + // The group a definition holds its art in, when it holds one object and isn't linked to a + // graphic style. + let linked = sub.style_links.iter().any(|(id, _)| *id == art.id); + let art = match symbol_art_member(&art).filter(|_| !linked).cloned() { + Some(m) => Arc::unwrap_or_clone(m), + None => art, + }; + let read_art = art; + let mut art = self.doc.reid(&read_art); + self.reid_masks(&mut art, 0); + // The objects of the art linked to graphic styles, by their ids in the document. + if !sub.style_links.is_empty() { + let mut ids = HashMap::new(); + pair_ids(&read_art, &art, &mut ids, 0); + for (id, style) in &sub.style_links { + if let Some(new) = ids.get(id) + && self.style_links.len() < MAX_NODES + { + self.style_links.push((*new, style.clone())); + } + } } + let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + if let Some(reg) = registration.and_then(symbol_registration) { + self.doc.set_symbol_registration(&named, reg); + } + self.symbol_names.entry(name).or_insert(named); + for (key, blob) in sub.doc.images { + self.doc.images.entry(key).or_insert(blob); + } + self.spots.extend(sub.spots); + self.stop_spots.extend(sub.stop_spots); + self.cmyk_colors += sub.cmyk_colors; + self.rgb_colors += sub.rgb_colors; + self.drawn_looks += sub.drawn_looks; + for w in &sub.warnings { + self.warn(w); + } + } + + /// `base`, or the first free "`base` N" (N from 2) when a symbol read has that name, as + /// [`vectorcraft_doc::Document::unique_symbol_name`] names it, without looking at every symbol + /// for each N. + fn unique_symbol_name(&mut self, base: &str) -> String { + let mut named = base.to_string(); + if self.symbol_taken.contains(&named) { + let next = self.symbol_suffix.entry(named.clone()).or_insert(2); + while self.symbol_taken.contains(&format!("{base} {next}")) { + *next += 1; + } + named = format!("{base} {next}"); + *next += 1; + } + self.symbol_taken.insert(named.clone()); + named + } + + /// Give the art of the opacity masks in `n` (a copy of a symbol's art with ids of this + /// document, [`vectorcraft_doc::Document::reid`], which leaves masks as they are) ids of this + /// document too. + fn reid_masks(&mut self, n: &mut Node, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + let mut art = self.doc.reid(&m.art); + self.reid_masks(&mut art, depth + 1); + m.art = Arc::new(art); + } + for c in n.children_mut().into_iter().flatten() { + self.reid_masks(Arc::make_mut(c), depth + 1); + } + } + + /// The symbol list (`section`: what follows `%AI24_BeginSymbolList`): the symbols' names in the + /// Symbols panel's order. The first list is kept. + fn symbol_list(&mut self, section: &[u8]) { + if self.symbol.is_some() || self.pattern.is_some() || self.symbol_list.is_some() { + return; + } + let mut lex = Lexer::new(section); + let mut names = vec![]; + while let Some(t) = lex.next_token() { + if let Tok::Str(bytes) = t.tok { + if names.len() >= MAX_LISTED { + break; + } + names.push(obj::text(&bytes)); + } + } + self.symbol_list = Some(names); } /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's @@ -560,15 +716,19 @@ impl<'a> Reader<'a> { // In a space of its own (y down), with no head to take. sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() }); sub.subreader_depth = self.subreader_depth + 1; - // The gradients and patterns defined so far, lent. + // The gradients and patterns defined so far, and which patterns are in the version 7 form, lent. sub.gradients = std::mem::take(&mut self.gradients); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.v7_patterns = std::mem::take(&mut self.v7_patterns); + sub.global_names = std::mem::take(&mut self.global_names); sub.nodes = self.nodes; sub.template = self.template; let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + self.v7_patterns = std::mem::take(&mut sub.v7_patterns); + self.global_names = std::mem::take(&mut sub.global_names); // Images aren't kept: the document's images don't count a brush's art among their users. Art // read with a note (something left out of it) isn't kept either. let whole = read.is_ok() @@ -769,6 +929,64 @@ fn ps_string(v: &[u8]) -> Option { None } +/// The one member of `n` when `n` is a plain group holding only it (not clipping, unnamed, shown, +/// unlocked, opaque, Normal, not isolated, knockout neutral, no knockout shape, appearance, opacity +/// mask or other extras such as object attributes): a symbol's art written as such a group +/// (definitions hold a group) is that member. +pub(crate) fn symbol_art_member(n: &Node) -> Option<&Arc> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let [one] = children.as_slice() else { return None }; + let plain = n.name.as_deref().is_none_or(str::is_empty) + && n.visible + && !n.locked + && n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::Neutral + && !n.knockout_shape + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && *n.extras() == vectorcraft_doc::NodeExtras::default(); + plain.then_some(one) +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is filled or stroked with a +/// pattern. +fn paints_pattern(n: &Node, depth: usize) -> bool { + if depth > MAX_DEPTH { + return true; + } + let pattern = |p: &super::Paint| matches!(p, super::Paint::Pattern { .. }); + n.appearance.items.iter().any(|item| match item { + super::AppearanceItem::Fill(f) => pattern(&f.paint), + super::AppearanceItem::Stroke(s) => pattern(&s.paint), + }) || n.extras().mask.as_ref().is_some_and(|m| paints_pattern(&m.art, depth + 1)) + || n.children().into_iter().flatten().any(|c| paints_pattern(c, depth + 1)) +} + +/// Each id of `old` and its descendants → the id of the object in its place in `new`, a copy of +/// `old` with new ids ([`vectorcraft_doc::Document::reid`]). +fn pair_ids(old: &Node, new: &Node, ids: &mut HashMap, depth: usize) { + ids.insert(old.id, new.id); + if depth > MAX_DEPTH { + return; + } + if let (Some(a), Some(b)) = (old.extras().mask.as_ref(), new.extras().mask.as_ref()) { + pair_ids(&a.art, &b.art, ids, depth + 1); + } + if let (Some(a), Some(b)) = (old.children(), new.children()) { + for (a, b) in a.iter().zip(b) { + pair_ids(a, b, ids, depth + 1); + } + } +} + +/// The registration point `AI13PatternRegistrationType` `v` gives a symbol: 1 to 9 from the top +/// left, row by row (5 the center); `None` for other numbers. +pub(super) fn symbol_registration(v: f64) -> Option { + (v.fract() == 0.0 && (1.0..=9.0).contains(&v)).then(|| SymbolRegistration(v as u8 - 1)) +} + #[cfg(test)] mod tests { use super::*; @@ -786,9 +1004,11 @@ mod tests { assert_eq!(ps_string(longest.as_bytes()).map(|s| s.len()), Some(MAX_STRING)); } + /// Definitions nested in a definition aren't read, however deep, and none is read past the + /// limit of nested readers. #[test] fn deeply_nested_symbol_definitions_stop_at_subreader_limit() { - let mut definition = String::from("(Outer) 0 Ae\n"); + let mut definition = String::from("(Outer) 0 A 0 Xw 0 Ae\n"); for i in 0..300 { definition.push_str(&format!("%AI14_BeginSymbol\n(S{i}) 0 Ae\n")); } @@ -798,8 +1018,34 @@ mod tests { } let mut reader = Reader::new(b""); reader.subreader_depth = MAX_SUBREADERS; - reader.symbol_bounds(definition.as_bytes()); - assert!(reader.symbol_bounds.is_empty()); + reader.define_symbol(definition.as_bytes()); + assert!(reader.doc.symbols.is_empty()); + reader.subreader_depth = 0; + reader.define_symbol(definition.as_bytes()); + let names: Vec<&str> = reader.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Outer"]); + } + + /// Definitions past the limit aren't read, however they are named. + #[test] + fn symbol_definitions_stop_at_the_limit_even_with_one_name() { + let mut reader = Reader::new(b""); + for _ in 0..MAX_SYMBOLS + 10 { + reader.define_symbol(b"(Same) 0 A 0 Xw 0 Ae\nu\nU\n"); + } + assert_eq!(reader.doc.symbols.len(), MAX_SYMBOLS); + assert_eq!(reader.doc.symbols.last().map(|s| s.name.as_str()), Some(format!("Same {MAX_SYMBOLS}").as_str())); + } + + /// The registration points 1 to 9 run from the top left, row by row; other numbers give none. + #[test] + fn symbol_registration_numbers_run_row_by_row() { + assert_eq!(symbol_registration(1.0), Some(SymbolRegistration(0))); + assert_eq!(symbol_registration(5.0), Some(SymbolRegistration::CENTER)); + assert_eq!(symbol_registration(9.0), Some(SymbolRegistration(8))); + for v in [0.0, 10.0, 2.5, -1.0, f64::NAN] { + assert_eq!(symbol_registration(v), None); + } } #[test] diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 5aebb94dda..2408b11cc4 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -4,10 +4,10 @@ use super::containers::drop_commented_copies; use super::ops::appearance_from_art_style; use super::types::{FLIP, Kind, MAX_DEPTH}; use super::{ - Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, + Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Global, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, Swatch, Unit, V, obj, }; -use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, TextWrap, Variable, VariableKind, Variables}; +use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, Symbol, TextWrap, Variable, VariableKind, Variables}; /// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files). fn ruler_unit(v: u8) -> Option { @@ -128,27 +128,41 @@ pub(crate) const LOOK_SLOT: &str = "\u{0}text:look"; /// The artboards (names, and rects in art space) of the editing data `data` that [`read`] can't /// read as a whole, as far as it gets: where to put the pages of its PDF part instead, and what to -/// call them (#1068). -pub fn artboards(data: &[u8]) -> Vec<(String, Rect)> { +/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`). +pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let found = artboards_read(data); - if !found.is_empty() { + if !found.0.is_empty() && found.1.is_some() { return found; } - // Reading can stop before the artboards (art kept in the document's data comes first): read - // their array on its own. - artboard_array(data).map_or(found, |array| { - let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); - alone.extend_from_slice(array); - alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); - artboards_read(&alone) - }) + // Reading can stop before the artboards (art kept in the document's data comes first), or + // between them and the active artboard's entry: read their array on its own. + let Some((array, active)) = artboard_array(data) else { return found }; + let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); + alone.extend_from_slice(array); + if let Some(active) = active { + alone.push(b'\n'); + alone.extend_from_slice(active); + } + alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); + let (boards, active) = artboards_read(&alone); + if found.0.is_empty() { + (boards, active) + } else if boards == found.0 { + // The same array: its names and rects read alike. + (found.0, active) + } else { + found + } } +/// The key that ends the `ArtboardArray` entry of the editing data. +const ARTBOARD_ARRAY: &[u8] = b"%_; (ArtboardArray) ,"; + /// The `ArtboardArray` entry of the editing data `data`, from its `/Array :` to its key: found -/// from the key back, counting the dictionaries its artboards open and close. -fn artboard_array(data: &[u8]) -> Option<&[u8]> { - const KEY: &[u8] = b"%_; (ArtboardArray) ,"; - let end = data.windows(KEY.len()).rposition(|w| w == KEY)? + KEY.len(); +/// from the key back, counting the dictionaries its artboards open and close; and the +/// `CropAreaActive` entry of the dictionary that holds it ([`crop_area_active`]). +fn artboard_array(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> { + let end = data.windows(ARTBOARD_ARRAY.len()).rposition(|w| w == ARTBOARD_ARRAY)? + ARTBOARD_ARRAY.len(); let head = data.get(..end)?; let mut depth = 0usize; let mut line_end = head.len(); @@ -160,7 +174,10 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } else if text.starts_with(b"/") && text.windows(2).any(|w| w == b" :") { depth = depth.checked_sub(1)?; if depth == 0 { - return head.get(line_start..); + let breaks = |b: &u8| *b == b'\n' || *b == b'\r'; + let after = data.get(end..).and_then(|rest| crop_area_active(rest.split(breaks), true)); + let active = after.or_else(|| data.get(..line_start).and_then(|before| crop_area_active(before.rsplit(breaks), false))); + return Some((head.get(line_start..)?, active)); } } } @@ -168,6 +185,33 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } } +/// The `CropAreaActive` entry (`%_ /Int (CropAreaActive) ,`) among the entries of the dictionary +/// that holds the `ArtboardArray` entry, skipping the dictionaries and arrays inside it: `lines` are +/// the lines after that entry, in order (`forward`), or those before it, last first. +fn crop_area_active<'a>(lines: impl Iterator, forward: bool) -> Option<&'a [u8]> { + const KEY: &[u8] = b" /Int (CropAreaActive) ,"; + let mut depth = 0usize; + for line in lines { + let Some(text) = line.strip_prefix(b"%_") else { continue }; + let closes = text.starts_with(b";") || text.starts_with(b"/Def ;"); + let opens = !closes && text.starts_with(b"/") && text.windows(2).any(|w| w == b" :"); + let (enters, leaves) = if forward { (opens, closes) } else { (closes, opens) }; + if enters { + // Into a dictionary or array inside the holder. + depth += 1; + } else if leaves { + // Out of one, or out of the holder itself. + depth = depth.checked_sub(1)?; + } else if depth == 0 { + let digits = text.iter().take_while(|b| b.is_ascii_digit()).count(); + if digits > 0 && text.get(digits..) == Some(KEY) { + return Some(line); + } + } + } + None +} + /// The palette of a `.ai` file's editing data, as [`palette`] reads it. pub struct PaletteSwatches { pub swatches: Vec, @@ -231,7 +275,7 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { /// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the /// palette is empty or reading stops before it. pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option { - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); @@ -281,7 +325,7 @@ pub struct Brushes { pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { // Brush objects are plug-in objects: data without one isn't read again. memchr::memmem::find(data, b"BeginPluginObject")?; - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); // The brushes come before the art, so an error in the art leaves them read. let _ = r.run(); let (mut lib, unread) = r.brush_library()?; @@ -317,9 +361,25 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) }) } +/// The graphic styles of the editing data `data`, for a file whose layers aren't read (a graphic +/// style library has none), as [`read`] makes them, with ids from 1, and the data's declared large +/// canvas scale (1 when it declares none). `large_canvas`: as [`read`] takes it. The styles are +/// those the list names before reading stops, and none when the data has no style list or lists no +/// style this reads. +pub fn graphic_styles(data: &[u8], large_canvas: bool) -> (Vec, f64) { + if crate::import::ai::find(data, b"BeginArtStyleList").is_none() { + return (vec![], 1.0); + } + let mut r = Reader::with_names(data); + r.large_canvas = large_canvas.then_some(1.0); + // The styles come before the art, so an error in the art leaves them read. + let _ = r.run(); + (r.graphic_styles().0, r.canvas_scale) +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). -fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { +fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let mut r = Reader::new(data); let _ = r.run(); let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); @@ -328,7 +388,8 @@ fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { r.document(o); } } - r.artboards.into_iter().map(|b| (b.name, b.rect)).collect() + let active = r.active_board.filter(|i| *i < r.artboards.len()); + (r.artboards.into_iter().map(|b| (b.name, b.rect)).collect(), active) } /// An object bound to a variable of the library: the variable's name, and the XML id of the object @@ -406,10 +467,23 @@ pub fn variables(data: &[u8]) -> VariableRead { } impl<'a> Reader<'a> { - /// Take the author and custom colors that the header of the program `ps` gives (its comment - /// lines up to `%%EndComments`), where the editing data's own header gives none: the program of - /// an EPS whose editing data is kept apart from it. - pub(super) fn program_header(&mut self, ps: &[u8]) { + /// Take the author and custom colors that the header of a program gives (`outer`, from + /// [`Self::header_of`]), where the editing data's own header gives none: the program of an EPS + /// whose editing data is kept apart from it. + pub(super) fn program_header(&mut self, outer: Reader<'_>) { + if self.author.is_none() { + self.author = outer.author; + } + for n in outer.custom_colors { + if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { + self.custom_colors.push(n); + } + } + } + + /// A reader that has read the header of the program `ps` (its comment lines up to + /// `%%EndComments`). + pub(super) fn header_of(ps: &[u8]) -> Reader<'_> { let mut end = 0; for line in ps.split_inclusive(|&b| b == b'\n' || b == b'\r') { if !line.starts_with(b"%") && !line.trim_ascii().is_empty() { @@ -422,14 +496,7 @@ impl<'a> Reader<'a> { } let mut outer = Reader::new(ps.get(..end).unwrap_or_default()); let _ = outer.run(); - if self.author.is_none() { - self.author = outer.author; - } - for n in outer.custom_colors { - if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { - self.custom_colors.push(n); - } - } + outer } } @@ -495,9 +562,27 @@ fn text_wrap(o: &Obj, scale: f64) -> Option { } impl<'a> Reader<'a> { - /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the - /// opacity mask it may carry. + /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), the opacity + /// mask it may carry, and in a pattern's definition the mark of the tile's box + /// (`AIPattern_Editor_Backing_Tile_Rect`), which leaves that box out of the art. pub(super) fn art_dictionary(&mut self, o: &Obj) { + // The unpainted box that a pattern's definition marks as its tile's box isn't art. + if self.pattern.is_some() + && o.nums("AIPattern_Editor_Backing_Tile_Rect").first().copied() == Some(1.0) + && self.after_object + && let Some(f) = self.frames.last_mut() + && f.children.last().is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }) && n.appearance.items.iter().all(|i| i.paint().is_none())) + { + f.children.pop(); + return; + } + // The dictionary after a symbol's art: its registration point. + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && let Some(r) = o.nums("AI13PatternRegistrationType").first() + { + head.registration = Some(*r); + } self.constraint_art(o); // A blend's key object or spine. if let Some(kind) = o.text("ShapeBlendPathType") @@ -519,7 +604,8 @@ impl<'a> Reader<'a> { let value = OpacityMask { art: art.clone(), clip: on("Clipping"), invert: on("Inverted"), disabled: on("Disabled"), linked: on("Linked") }; if let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { - n.extras_mut().mask = Some(Box::new(value)); + n.extras_mut().mask = Some(Box::new(value.clone())); + self.each_linked_frame(|n| n.extras_mut().mask = Some(Box::new(value.clone()))); } else if !on("Disabled") { self.unreadable("opacity masks without an owning object", false); } @@ -542,6 +628,7 @@ impl<'a> Reader<'a> { && let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { n.extras_mut().wrap = Some(wrap); + self.each_linked_frame(|n| n.extras_mut().wrap = Some(wrap)); } // The object's XML id, which the variable library's bindings name it by. if let Some(uid) = o.obj("AI10_ArtUID").and_then(Obj::content_text).filter(|u| !u.is_empty()) @@ -565,8 +652,9 @@ impl<'a> Reader<'a> { } } - /// The `/Document` dictionary: the artboards and their display options, Document Raster Effects - /// Settings, its variable library (the first one read), and its Objects on Path records. + /// The `/Document` dictionary: the artboards and their display options, the active artboard + /// (`CropAreaActive`, `/Int`: its index in the `ArtboardArray`, next to it), Document Raster + /// Effects Settings, its variable library (the first one read), and its Objects on Path records. pub(super) fn document(&mut self, o: &Obj) { if !self.variables.present { self.variables = variable_library(o); @@ -575,7 +663,9 @@ impl<'a> Reader<'a> { if let Some(r) = find_entry(o, "AI Auto Rasterize", 0) { raster_settings(r, &mut self.doc); } - let Some(list) = find_entry(o, "ArtboardArray", 0) else { return }; + let Some(holder) = find_holder(o, "ArtboardArray", 0) else { return }; + let Some(list) = holder.obj("ArtboardArray") else { return }; + let active = typed(holder, "CropAreaActive", "Int"); for (i, ab) in list.items().enumerate().take(1000) { let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2")); let ([x0, y0, ..], [x1, y1, ..]) = (p1.as_slice(), p2.as_slice()) else { continue }; @@ -586,6 +676,9 @@ impl<'a> Reader<'a> { let name = ab.text("Name").unwrap_or_else(|| format!("Artboard {}", i + 1)); let mut board = AiArtboard::new(name, r); display_options(ab, &mut board); + if active == Some(i as f64) { + self.active_board = Some(self.artboards.len()); + } self.artboards.push(board); } } @@ -639,9 +732,50 @@ impl<'a> Reader<'a> { } /// Art space → where the art being read goes: the document, or while a pattern's definition is - /// read, the pattern's space (y down). + /// read, the pattern's space (y down). A symbol's definition is written in the symbol's space. pub(crate) fn space(&mut self) -> Affine { - if self.pattern.is_some() { FLIP } else { self.ensure_space() } + if self.pattern.is_some() { + FLIP + } else if self.symbol.is_some() { + Affine::IDENTITY + } else { + self.ensure_space() + } + } + + /// 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. + pub(super) fn image_space(&mut self) -> Option { + if self.pattern.is_none() && self.symbol.is_some() { + return self.canvas_origin().map(|o| Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])); + } + Some(self.space()) + } + + /// The canvas point of art space's origin, from the template box's center (the canvas's): what + /// a pattern's gradients and the instances in a symbol's art are written about. + pub(super) fn canvas_origin(&self) -> Option { + let t = self.template?; + let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); + let origin = Point::new(CANVAS_CENTRE - cx, CANVAS_CENTRE + cy); + (origin.x.is_finite() && origin.y.is_finite()).then_some(origin) + } + + /// The symbols in the symbol list's order, those it doesn't name after them as they were + /// defined; names it has twice or that no symbol has don't count. + fn order_symbols(&mut self) { + let Some(list) = self.symbol_list.take() else { return }; + let mut slots: Vec> = std::mem::take(&mut self.doc.symbols).into_iter().map(Some).collect(); + let at: HashMap = slots.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (s.name.clone(), i))).collect(); + let mut ordered = Vec::with_capacity(slots.len()); + for name in &list { + if let Some(s) = self.symbol_names.get(name).and_then(|named| at.get(named)).and_then(|i| slots.get_mut(*i)).and_then(Option::take) { + ordered.push(s); + } + } + ordered.extend(slots.into_iter().flatten()); + self.doc.symbols = ordered; } /// The swatches of the palette, `[None]` first, in its order, and its color groups; a gradient @@ -652,18 +786,26 @@ impl<'a> Reader<'a> { return None; } let palette = std::mem::take(&mut self.palette); - let swatch = |e: crate::import::ai::palette::Entry| -> Option { + let swatch = |mut e: crate::import::ai::palette::Entry| -> Option { use crate::import::ai::palette::Cell; let (paint, global, spot) = match e.cell { Cell::Color { color, global, spot } => (Paint::solid(color), global, spot), + // A swatch named by its gradient or pattern takes the name that got in the document. Cell::Gradient(g) => { let mut gp = vectorcraft_color::gradient::GradientPaint::new(self.gradients.get(&g)?.clone()); + if e.name == g { + e.name = self.global_names.get(Global::Gradient, &g).to_string(); + } gp.swatch = Some(e.name.clone()); (Paint::Gradient(Box::new(gp)), false, false) } Cell::Pattern(p) => { - patterns.iter().find(|d| d.name == p)?; - (Paint::Pattern { pattern: p, xf: Affine::IDENTITY }, false, false) + let pattern = self.global_names.get(Global::Pattern, &p).to_string(); + patterns.iter().find(|d| d.name == pattern)?; + if e.name == p { + e.name.clone_from(&pattern); + } + (Paint::Pattern { pattern, xf: Affine::IDENTITY }, false, false) } }; Some(Swatch { name: e.name, paint, global, spot }) @@ -740,9 +882,13 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); + self.check_symbols(); + self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); super::on_path::apply(&mut self.doc, &self.on_path); let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); + // The active artboard, when it is not the first (the default). + let active = self.active_board.filter(|i| *i > 0 && *i < self.artboards.len()); let boards: Vec = if self.artboards.is_empty() { artboard.or_else(|| self.bbox_board()).map(|r| vec![AiArtboard::new("Artboard 1".to_string(), r)]).unwrap_or_default() } else { @@ -778,6 +924,7 @@ impl<'a> Reader<'a> { color: None, }]; } + doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); if !self.ruler_guides.is_empty() { let ids: Vec = doc.artboards.iter().map(|a| a.id).collect(); let (candidates, centre) = (std::mem::take(&mut self.ruler_guides), self.template_center); @@ -850,6 +997,9 @@ impl<'a> Reader<'a> { let links: HashMap = self.style_links.iter().filter_map(|(node, name)| Some((*node, *ids.get(name)?))).collect(); if !links.is_empty() { link_styles(&mut doc.layers, &links, &styles, 0); + for symbol in &mut doc.symbols { + link_styles(std::slice::from_mut(&mut symbol.art), &links, &styles, 0); + } } doc.graphic_styles = styles.into(); } @@ -872,6 +1022,11 @@ impl<'a> Reader<'a> { doc.variables = variables.variables.into(); } let (bindings, bindings_skipped) = (variables.bindings, variables.bindings_skipped); + // Symbols that hold instances of themselves can't be drawn: those instances go before the + // layers are compared with the page. + if !doc.symbols.is_empty() { + doc.limit_depth_noting(&mut warnings); + } Ok(Structure { doc, to_doc, @@ -883,6 +1038,7 @@ impl<'a> Reader<'a> { unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, restyled: self.restyled, + placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, envelopes_drawn: self.envelopes_drawn, styles_read, @@ -981,10 +1137,18 @@ fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { + find_holder(o, key, depth).and_then(|h| h.obj(key)) +} + +/// The dictionary that [`find_entry`] finds the entry `key` in: `o` or one it holds. +fn find_holder<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { if depth > 8 { return None; } - o.obj(key).or_else(|| o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_entry(c, key, depth + 1))) + if o.obj(key).is_some() { + return Some(o); + } + o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_holder(c, key, depth + 1)) } // ---- the variable library ----------------------------------------------------------------- diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 5d47ce16fa..dc30890247 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1,9 +1,12 @@ use super::containers::close; use super::document::slot_of; -use super::types::{BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, Place, line_width}; +use super::types::{ + BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, + line_width, +}; use super::{ - Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Gradient, GradientDef, Graph, HashMap, HashSet, Instance, - Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, StrokeLayer, V, obj, paint, + Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, Graph, HashMap, HashSet, Instance, + Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint, }; impl<'a> Reader<'a> { @@ -73,6 +76,36 @@ impl<'a> Reader<'a> { } } + /// `/identifier (string) XT` (version 7 specification §7): a tag on the object before it. The + /// `AdobeURL` tag sets the object's URL, and every other tag is added to the object's data in + /// order, up to [`MAX_TAGS`]. A tag with no object before it, with an empty identifier, or with + /// an identifier or string longer than [`MAX_TAG_TEXT`] bytes is ignored, and so are tags in a + /// pattern's or brush's art, which is not an object of the document. A clipping path's tags are + /// its own, not those of the copy that paints its fill. + fn object_tag(&mut self, vals: &[V], hidden: bool) { + let [.., V::Name(id), V::Str(value)] = vals else { + self.note_unknown("XT", hidden); + return; + }; + if id.is_empty() || id.len() > MAX_TAG_TEXT || value.len() > MAX_TAG_TEXT || !self.after_object || self.pattern.is_some() { + return; + } + let (id, value) = (id.clone(), obj::text(value)); + let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return }; + let Some(mut at) = kids.len().checked_sub(1) else { return }; + if at > 0 && kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) { + at -= 1; + } + let Some(n) = kids.get_mut(at) else { return }; + n.edit_attrs(|a| { + if id == URL_TAG { + a.url = value; + } else if a.data.len() < MAX_TAGS { + a.data.push((id, value)); + } + }); + } + pub(super) fn op(&mut self, w: &str, hidden: bool) -> Result<(), String> { if self.blend_record.is_some() { self.end_blend(); @@ -124,6 +157,7 @@ impl<'a> Reader<'a> { "Bs" => d.stop(&vals, &mut self.stop_spots), "BD" => { if let Some((name, g)) = self.gradient_def.take().and_then(GradientDef::finish) { + self.global_names.define(Global::Gradient, &name); self.gradients.insert(name, g); } } @@ -211,6 +245,12 @@ impl<'a> Reader<'a> { Some(0.0) => self.gs.show_center = None, _ => {} }, + // Object tags (§7): `/identifier (string) XT` after the object it tags. The state written + // after a group or a mesh is still theirs after its tags. + "XT" => { + self.object_tag(&vals, hidden); + (self.group_ended, self.mesh_ended) = (group_ended, mesh_ended); + } "w" => { if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) { self.gs.width = *v; @@ -317,21 +357,28 @@ impl<'a> Reader<'a> { "Tp" => self.begin_text_path(&vals), "TP" => self.end_text_path(), "TO" => self.end_text(hidden)?, - "Tx" | "Tj" | "TX" => self.text_body(w, &vals), - "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" => self.text_attr(w, &vals), + // `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`. + "Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals), + "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "Xb" | "Xe" | "XB" => self.text_attr(w, &vals), // Attributes the reader doesn't keep (kerning pairs, Far-Eastern type) and final-form // positions (§15.3). "Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {} - // The hyphenation language and tab rulers, which the reader doesn't keep either (§22): `XL`, - // `Xb`/`XB` a tab definition (and the `Xe` tab descriptions between them). - "XL" | "Xb" | "XB" | "Xe" => {} + // `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the + // reader takes `Te` with any number of operands. + "TM" | "Te" => {} + // The hyphenation language (`XL`), which the reader doesn't keep either (§22). + "XL" => {} "TE" => self.te(&vals), + "TZ" => self.tz(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { if let Some(r) = self.raster.as_mut() { r.operands = Some(vals); } } + // A linked image (§8.2, §8.3): `(path) modified XG` names the file of the `XF` image after + // it, which has `XI`'s operands and no samples. + "XG" | "XF" => self.image_link_op(w, vals, hidden)?, // A plugin group ends; a blend's record follows on `%` lines. "XP" => { let name = vals.iter().find_map(V::text).unwrap_or_default(); @@ -431,7 +478,7 @@ impl<'a> Reader<'a> { self.unread_pattern(w); return; }; - let p = Paint::Pattern { pattern: name.unwrap_or_default(), xf }; + let p = Paint::Pattern { pattern: name.as_deref().map(|n| self.global_names.get(Global::Pattern, n).to_string()).unwrap_or_default(), xf }; if w == "p" { self.pending_unread_fill = false; self.gs.fill = p; @@ -473,10 +520,16 @@ impl<'a> Reader<'a> { self.gs.fill = p; self.pending_fill = None; self.pending_unread_fill = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_fill = false; + } } else { self.gs.stroke = p; self.pending_stroke = None; self.pending_unread_stroke = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_stroke = false; + } } } @@ -496,8 +549,16 @@ impl<'a> Reader<'a> { /// The state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the /// `LB`, and can have the stroke style between its `Xy` and `Xd`: that keeps the layer's state, /// and what a mesh or blend before it had (`mesh_undo`). + /// After an image, the operators that end its raster (`XH`, `Xr` and the `N` after + /// `%AI5_EndRaster`) keep it the object its name and opacity mask go to. fn state_block_continues(&mut self, w: &str) { - if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") { + if self.image_tail && matches!(w, "XH" | "XT" | "Xr" | "N") { + return; + } + self.image_tail = false; + // An object's tags (`XT`) follow it one after another, and an image's follow the `XH` that + // ends its data. + if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH") { return; } self.after_object = false; @@ -530,14 +591,18 @@ impl<'a> Reader<'a> { let gs = &self.gs; let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); let Some(Frame { kind: Kind::Layer(_), children, .. }) = self.frames.last_mut() else { return }; - let Some(n) = children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) else { return }; + let Some(n) = + children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. })) + else { + return; + }; (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = before; self.layer_state = Some(state); } - /// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too, and right - /// after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and `6 () XW`), - /// theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). + /// `mode opacity isolate knockout shape Xy`; after a group's end or a symbol instance, theirs + /// too, and right after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and + /// `6 () XW`), theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). fn transparency(&mut self, vals: &[V], mesh_ended: bool) { let n = Self::nums(vals); let [mode, opacity, rest @ ..] = n.as_slice() else { return }; @@ -567,6 +632,12 @@ impl<'a> Reader<'a> { // The layer's instead when the layer's `7 () XW` follows (`layer_state_block`). self.container_undo = in_layer.then_some(before); self.layer_state = None; + } else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) { + // A symbol instance's, as a group's. + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + self.container_undo = in_layer.then_some(before); + self.layer_state = None; } else { // After a layer's art and before its `LB`: the layer's own state (#2003). Kept until // an operator that isn't part of the state block (or the `LB` that takes it) says the @@ -652,7 +723,14 @@ impl<'a> Reader<'a> { object, look, st, - &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space }, + &StylePaints { + gradients: &self.gradients, + patterns: &self.pattern_tiles, + names: &self.global_names, + v7_patterns: &self.v7_patterns, + brushes: &self.brush_drafts, + space, + }, ) }) { // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). @@ -714,6 +792,23 @@ impl<'a> Reader<'a> { look.name = object.name.clone().or(look.name.take()); look.visible = object.visible; look.locked = object.locked; + // The object's note, Show Center, URL and data (object tags) stay with the look that stands + // for it, in place of the look's own where the object has them. + if let Some(a) = object.extras().attrs.as_deref().cloned() { + look.edit_attrs(|l| { + if a.show_center.is_some() { + l.show_center = a.show_center; + } + if !a.url.is_empty() { + l.url = a.url; + } + if !a.note.is_empty() { + l.note = a.note; + } + let room = MAX_TAGS.saturating_sub(l.data.len()); + l.data.extend(a.data.into_iter().take(room)); + }); + } if !hidden { self.drawn_looks += 1; } @@ -769,12 +864,15 @@ fn pattern_controls(n: &[f64]) -> Option { xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) } -/// What a style's fills paint with: the file's gradients and pattern tiles, the patterns defined in -/// the version 7 form, and art space → the document. +/// What a style's fills paint with: the file's gradients and pattern tiles with the names they get +/// in the document, the patterns defined in the version 7 form, and art space → the document. struct StylePaints<'a> { gradients: &'a HashMap, patterns: &'a HashMap, + names: &'a ShownNames, v7_patterns: &'a HashSet, + /// The brushes the file defines, which a brushed stroke names. + brushes: &'a [super::super::brush::BrushDraft], space: Affine, } @@ -813,21 +911,88 @@ fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { } } +/// Is `n` a path, a compound path or a group without a clip, with no opacity mask, the objects +/// whose outline the effects that move it (Transform, Twist, Free Distort) are read on? Images, +/// type (and a text object's slot, filled with type placed where the page has it) and live objects +/// draw more than their outline, and a mask stays where it is. +fn outlines_only(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { clip: false, .. }) + && n.extras().mask.is_none() + && slot_of(n.name.as_deref()).is_none() +} + +/// Does `n`, inside an object whose outline an effect moves, move with it: is it and everything in +/// it [`outlines_only`], painting with no gradient or pattern (which stay where they are placed) +/// and with no effects of its own (drawn after the outer effect, not before)? Deeper than +/// [`MAX_DEPTH`] counts as no. +fn moves_alike(n: &Node, depth: usize) -> bool { + depth <= MAX_DEPTH + && outlines_only(n) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty() && !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && n.children().into_iter().flatten().all(|c| moves_alike(c, depth + 1)) +} + +/// Does `n` or anything in it (to [`MAX_DEPTH`]) have a stroke that paints? +fn strokes(n: &Node, depth: usize) -> bool { + depth > MAX_DEPTH + || n.appearance.items.iter().any(|i| !i.is_fill() && !i.paint().is_none()) + || n.children().into_iter().flatten().any(|c| strokes(c, depth + 1)) +} + +/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? +fn straight(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p), + NodeKind::Compound { children, .. } => children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. }) && straight(c)), + _ => false, + } +} + +/// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything +/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path +/// or compound path with straight segments, and Transform that scales, turns or reflects only when +/// nothing is stroked (its reference point lies on the bounds without strokes). +fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + use crate::import::ai::style::StyleItem; + let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) + || object.children().into_iter().flatten().any(|c| strokes(c, 1)); + !st.items.iter().any(|i| matches!(i, StyleItem::Gradient { .. })) + && outlines_only(object) + && object.children().into_iter().flatten().all(|c| moves_alike(c, 1)) + && st.effects.iter().all(|e| match e.id.as_str() { + "distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object), + "distort.transform" => { + let p = &e.params; + !stroked + || (p["scaleH"].as_f64() == Some(100.0) + && p["scaleV"].as_f64() == Some(100.0) + && p["rotate"].as_f64() == Some(0.0) + && p["reflectX"].as_bool() == Some(false) + && p["reflectY"].as_bool() == Some(false)) + } + _ => true, + }) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; /// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one -/// this reads, asks a group for fills or strokes, or has Pathfinder effects on anything but a group -/// with no fills or strokes. +/// this reads, asks a group for fills or strokes, has Pathfinder effects on anything but a group +/// with no fills or strokes, or moves the outline of an object it isn't read on ([`moves_with`]). fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option { use crate::import::ai::style::StyleItem; // A text object's slot (an empty group standing for it) takes the style as the type will. let slot = slot_of(object.name.as_deref()).is_some(); + // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain + || matches!(object.kind, NodeKind::SymbolInstance { .. }) || (!slot && !st.simple) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) || (st.pathfinder && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) + || (!slot && st.moves_outline() && !moves_with(object, st)) { return None; } @@ -843,7 +1008,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), StyleItem::Gradient { name, angle } => { - let paint = match (name.as_ref().and_then(|n| placed.get(n)), gradients, own_gradient) { + // The drawn look's gradients are keyed by the names they got in the document. + let paint = match (name.as_ref().and_then(|n| placed.get(paints.names.get(Global::Gradient, n))), gradients, own_gradient) { // Other objects than type: the object's own, as they always were. (_, 1, Some(own)) if !slot => own.paint.clone(), (Some(p), ..) => p.clone(), @@ -858,7 +1024,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p }; AppearanceItem::Fill(FillLayer::new(paint)) } - StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) { + StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name))) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), None => { let tile = paints.patterns.get(name).copied()?; @@ -867,10 +1033,20 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); } let xf = pattern_xf(paints.space, matrix, tile)?; - AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf })) + AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: paints.names.get(Global::Pattern, name).to_string(), xf })) } }, - StyleItem::Stroke { .. } => stroke_layer(item)?, + StyleItem::Stroke { brush, .. } => { + // A brushed stroke draws as its look only with the brush the file defines (the + // first of its name, as the Brushes panel keeps it) at the object's settings. + if let Some((name, settings)) = brush { + let draft = paints.brushes.iter().find(|d| &d.name == name)?; + if !super::super::brush::draws_as(draft, settings) { + return None; + } + } + stroke_layer(item)? + } }; if let Some(look) = st.looks.get(n) { with_look(&mut layer, look); @@ -896,6 +1072,8 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) for (n, item) in st.items.iter().enumerate() { let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), + // A graphic style's brush isn't checked against the file's brushes: it is left out. + StyleItem::Stroke { brush: Some(_), .. } => return None, StyleItem::Stroke { .. } => stroke_layer(item)?, StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None, }; @@ -909,9 +1087,10 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) /// A style's stroke as an appearance item (`None` for a fill). fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option { - let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile } = item else { return None }; + let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, brush } = item else { return None }; let mut layer = StrokeLayer::new(paint.clone(), line_width(*width)); (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile) = (*cap, *join, *miter, dash.clone(), profile.clone()); + layer.brush = brush.as_ref().map(|(name, _)| name.clone()); Some(AppearanceItem::Stroke(layer)) } @@ -942,3 +1121,71 @@ fn strip(n: &mut Node, hidden: &HashSet) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::ImageObject; + use vectorcraft_geom::shapes; + + fn square(id: u64, fill: Paint) -> Arc { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) + } + + #[test] + fn only_outlines_without_gradients_move_alike() { + // GUARDS: an image's pixels and a placed gradient stay behind when an effect moves the outline. + let solid = || square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_alike(&Node::group(NodeId(1), vec![solid(), solid()]), 1)); + let gradient = square(3, Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint::new(Gradient::default())))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), gradient]), 1)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image)))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(5), vec![image.clone()]))]), 1)); + assert!(!outlines_only(&image)); + // A text object's slot, and a member with an opacity mask. + let mut slot = Node::group(NodeId(6), vec![]); + slot.name = Some(format!("{}0", super::super::document::TEXT_SLOT)); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(slot)]), 1)); + let mut masked = Node::clone(&solid()); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(masked)]), 1)); + // A member with an effect of its own. + let mut turned = Node::clone(&solid()); + turned.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.twist".into(), + params: serde_json::json!({"angle": 30.0}), + visible: true, + }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(turned)]), 1)); + // A member painting a pattern, whose tiles stay where they are, and a clipping group. + let tiled = square(8, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), tiled]), 1)); + let mut clipped = Node::group(NodeId(9), vec![solid(), solid()]); + if let NodeKind::Group { clip, .. } = &mut clipped.kind { + *clip = true; + } + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(clipped)]), 1)); + } + + #[test] + fn an_outline_moves_with_its_effect_only_on_outlines() { + // GUARDS: a top-level image or masked path took an effect that moves the outline. + use crate::import::ai::style::ArtStyle; + let effect = |id: &str, params| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let style = |e| ArtStyle { effects: vec![e], ..ArtStyle::default() }; + let twist = style(effect("distort.twist", serde_json::json!({"angle": 30.0}))); + let path = square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_with(&path, &twist)); + let mut masked = Node::clone(&path); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_with(&masked, &twist)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let distort = style(effect("distort.freeDistort", serde_json::json!({"corners": [[0.1, 0.0], [1.1, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(!moves_with(&image, &distort)); + assert!(moves_with(&path, &distort)); + } +} diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 39b77cf749..09f752db5d 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -40,9 +40,26 @@ pub(crate) const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). pub(super) const MAX_PATTERNS: usize = 4096; +/// Most symbol definitions read (instances of others come in as the page draws them). +pub(super) const MAX_SYMBOLS: usize = 4096; + +/// Most names a symbol list orders. +pub(super) const MAX_LISTED: usize = 4 * MAX_SYMBOLS; + /// Most characters of a path's note read (the version 7 specification allows 254, §5.3.1). pub(super) const MAX_NOTE: usize = 1024; +/// Most object tags (`XT`) kept in one object's data. SVG import keeps the same number of `data-*` +/// attributes per element. +pub(super) const MAX_TAGS: usize = 64; + +/// The longest identifier or string an object tag (`XT`) may have, in bytes: SVG import keeps +/// another application's attribute values up to the same length. +pub(super) const MAX_TAG_TEXT: usize = 64 * 1024; + +/// The object tag that holds the object's URL (version 7 specification §7). +pub(super) const URL_TAG: &str = "AdobeURL"; + #[derive(Clone, Debug)] pub(crate) struct GState { pub(crate) fill: Paint, @@ -216,6 +233,22 @@ pub(super) struct PatternHead { pub(super) tile: Option, } +/// What a reader of a symbol's definition has read of the symbol besides its art. +#[derive(Debug, Default)] +pub(super) struct SymbolHead { + /// `AI13PatternRegistrationType` in the dictionary after the art. + pub(super) registration: Option, + /// Art the reader left out (type, a placed file, non-native art, an image it can't read or + /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the + /// page draws them, within the box of the rest. + pub(super) left_out: bool, + /// A gradient instance the reader can't make a paint of (a gradient the file doesn't define, + /// or one it can't place) is the next path's fill or stroke: the art is left out when that + /// path paints it. + pub(super) missing_fill: bool, + pub(super) missing_stroke: bool, +} + /// An image's operands, from `XN` and before `XI`. #[derive(Debug, Default)] pub(super) struct Raster { @@ -258,6 +291,11 @@ pub(super) const MAX_PLACED_FOLDER: usize = 4096; pub(super) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; +/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a +/// placeholder. +pub const LINKED_PLACEHOLDERS: &str = + "linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel"; + /// Operators that change nothing the reader keeps. pub(super) const IGNORED: &[&str] = &[ "Ae", @@ -265,12 +303,10 @@ pub(super) const IGNORED: &[&str] = &[ "As", "Xd", "Xr", - "XG", // `/DeviceGray XC` after a linked image's file name (`XG`): its colour space. "XC", "Xh", "XH", - "XF", "Bc", "XP", "Np", @@ -278,7 +314,6 @@ pub(super) const IGNORED: &[&str] = &[ "i", // Path resolution (`Ar`, §12): how finely curves print. "Ar", - "TZ", "Xs", "Xt", // A brushed path's width at each anchor (`(…) Xt n XD`), on its hidden source path. @@ -301,6 +336,8 @@ pub(super) const IGNORED: &[&str] = &[ ]; /// Sections skipped whole, by their markers without the `AI_` prefix: begin → end. +/// Patterns, symbols and the symbol list are read before this list is looked at; their markers +/// stay here for sections of the same kind nested in them to be skipped. pub(super) const SKIPPED: &[(&str, &str)] = &[ ("BeginPattern", "EndPattern"), ("BeginBrushPattern", "EndBrushPattern"), diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e1947bfdaf..0e1a52a6f2 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -32,8 +32,13 @@ //! gradient (`Bb` … `flag (name) x y angle length … Bg` … `BB`); `stroke fill Xd` says whether it //! paints at all. A blend filter's `mode opacity isolate knockout shape Xy` is its transparency. //! +//! A stroke with a Calligraphic brush is its own basic filter, `(Adobe Calligraphic Brush Tool)`, with +//! its stroke's style and the brush's settings for the object as entries (see +//! [`super::brush`]). +//! //! A style is *plain* when every filter in it is one read here: fills and strokes (in a colour; fills -//! with a pattern or gradient too), each with its own transparency and effects, and the effects of +//! with a pattern or gradient too; strokes with a Calligraphic brush too), each with its own +//! transparency and effects, and the effects of //! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and //! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the //! object's chain) are read on a group with no fills or strokes of its own, which keeps its members. @@ -72,6 +77,8 @@ const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files const PATHFINDER: &str = "Adobe Pathfinder"; // brand-ok: the filter's name in the files +const CALLIGRAPHIC: &str = "Adobe Calligraphic Brush Tool"; // brand-ok: the filter's and plug-in's name in the files + const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; const FILL: &str = "Fill Style Filter"; @@ -131,7 +138,8 @@ pub(super) struct ArtStyle { pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, - /// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object + /// Feather, Round Corners, Scribble, Convert to Shape, the Path effects (Offset Path, Outline Object, Outline Stroke) + /// and some Distort & Transform effects ([`any_object_takes`]) on the object /// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, @@ -150,6 +158,13 @@ pub(super) struct ArtStyle { pub pathfinder: bool, } +impl ArtStyle { + /// Do its effects move the object's outline (Transform, Twist, Free Distort)? + pub fn moves_outline(&self) -> bool { + self.effects.iter().any(|e| matches!(e.id.as_str(), "distort.transform" | "distort.twist" | "distort.freeDistort")) + } +} + #[derive(Clone, Debug, PartialEq)] pub(super) enum StyleItem { Fill(Paint), @@ -174,6 +189,8 @@ pub(super) enum StyleItem { miter: f64, dash: Option, profile: Option, + /// A Calligraphic brush: its name, and its settings for this object. + brush: Option<(String, vectorcraft_brush::Calligraphic)>, }, } @@ -231,6 +248,9 @@ struct Filter { gradient_of: Option<(Option, f64)>, /// `(name) … [matrix] p`, and the numbers between the name and the matrix. pattern: Option<(String, Option<[f64; 6]>, Vec)>, + /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and + /// plug-in name. + plugin_object: Option<(String, String)>, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, /// `… isolate knockout … Xy`. @@ -259,6 +279,7 @@ impl Default for Filter { gradient: false, gradient_of: None, pattern: None, + plugin_object: None, xy: None, xy_group: None, } @@ -388,6 +409,13 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } } b"Array" => dict_array = Some(vec![]), + b"PluginObject" if in_basic => { + let mut texts = operands.iter().rev().filter_map(V::text); + if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) { + f.plugin_object = Some((name, plugin)); + } + other_entry = Some(None); + } b"Int" | b"Real" | b"Bool" => { // The number right before the type: an earlier one isn't this value. let value = operands.last().and_then(V::num); @@ -1066,13 +1094,46 @@ fn paint_item(f: &Filter) -> Result, ()> { miter: f.miter, dash: f.dash.clone(), profile: width_profile(&f.arrays), + brush: None, })), _ => Err(()), }, + CALLIGRAPHIC => calligraphic_stroke(f).map(Some).ok_or(()), _ => Err(()), } } +/// A Calligraphic brush's filter `f` as the stroke it paints: `None` when it isn't a stroke in a +/// colour, names no Calligraphic brush, or its settings aren't all there as numbers. An angle +/// relative to the path isn't read. +fn calligraphic_stroke(f: &Filter) -> Option { + let real = |key: &str| entry(f, key, Kind::Real).ok().flatten(); + let code = |key: &str| entry(f, key, Kind::Int).ok().flatten(); + if !f.paints.0 || f.gradient || f.pattern.is_some() || f.repeated { + return None; + } + if entry(f, "AngleRelativeTo", Kind::Int).ok()?.unwrap_or(0.0) != 0.0 { + return None; + } + let (name, plugin) = f.plugin_object.as_ref()?; + if plugin != CALLIGRAPHIC { + return None; + } + let values = [real("Angle")?, real("Roundness")?, real("Diameter")?]; + let variation = [real("AngleVariation")?, real("RoundnessVariation")?, real("DiameterVariation")?].map(f64::abs); + let codes = [code("AngleDependsOn")?, code("RoundnessDependsOn")?, code("DiameterDependsOn")?]; + Some(StyleItem::Stroke { + paint: f.stroke.clone()?, + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: None, + profile: None, + brush: Some((name.clone(), super::brush::calligraphic(values, variation, codes))), + }) +} + /// Builds an [`ArtStyle`] from a style's filter tree. struct Builder<'a> { filters: &'a [Filter], @@ -1113,7 +1174,7 @@ impl Builder<'_> { let c = &filters[k]; match c.name.as_str() { _ if c.compound => {} - FILL | STROKE => match paint_item(c) { + FILL | STROKE | CALLIGRAPHIC => match paint_item(c) { Ok(Some(StyleItem::Stroke { .. })) => under.strokes = true, Ok(Some(StyleItem::Pattern { .. })) => under.patterns = true, _ => {} @@ -1127,7 +1188,7 @@ impl Builder<'_> { let c = &filters[k]; match c.name.as_str() { _ if c.compound => self.plain = false, - FILL | STROKE => { + FILL | STROKE | CALLIGRAPHIC => { paints += 1; look.visible &= c.visible; match paint_item(c) { @@ -1177,6 +1238,52 @@ impl Builder<'_> { } } +/// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform +/// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing, +/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map). +/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is +/// `read::ops`' `moves_with`. +fn any_object_takes(e: &Effect) -> bool { + match e.id.as_str() { + "stylize.dropShadow" + | "stylize.innerGlow" + | "stylize.outerGlow" + | "stylize.feather" + | "stylize.roundCorners" + | "stylize.scribble" + | "convertToShape.rectangle" + | "convertToShape.roundedRectangle" + | "convertToShape.ellipse" + | "path.offsetPath" + | "path.outlineObject" + | "path.outlineStroke" + | "distort.twist" + | "distort.tweak" => true, + // Copies are drawn as one path, its fills under all its strokes, where the file paints each + // copy's fill and stroke in turn. + "distort.transform" => e.params["copies"].as_i64() == Some(0), + "distort.puckerBloat" => e.params["amount"].as_f64() == Some(0.0), + "distort.freeDistort" => affine(&e.params), + id => is_pathfinder(id), + } +} + +/// Do Free Distort params `p`'s corners (top left, top right, bottom right, bottom left) make a +/// parallelogram, so that the bilinear map is affine? +fn affine(p: &serde_json::Value) -> bool { + let Some(c) = p["corners"].as_array() else { return false }; + let at = |i: usize, axis: usize| c.get(i).and_then(|c| c.get(axis)).and_then(serde_json::Value::as_f64); + (0..2).all(|axis| match (at(0, axis), at(1, axis), at(2, axis), at(3, axis)) { + (Some(tl), Some(tr), Some(br), Some(bl)) => { + // The corners are fractions of the object's box, divided out of the file's rounded + // decimals; the tolerance is relative to how far apart they lie, not where. + let (lo, hi) = [tl, tr, br, bl].iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + ((tl + br) - (tr + bl)).abs() <= 1e-5 * (hi - lo).max(1.0) + } + _ => false, + }) +} + fn style(filters: &[Filter]) -> ArtStyle { let mut st = ArtStyle { plain: true, ..ArtStyle::default() }; let Some(root) = filters.iter().position(|f| f.parent.is_none()) else { return st }; @@ -1187,7 +1294,7 @@ fn style(filters: &[Filter]) -> ArtStyle { let f = &filters[id]; match f.name.as_str() { STACK if f.compound => b.stack(id, &mut st), - FILL | STROKE | CHAIN => { + FILL | STROKE | CALLIGRAPHIC | CHAIN => { if let Some((item, look)) = b.item(id) { st.items.push(item); st.looks.push(look); @@ -1221,23 +1328,10 @@ fn style(filters: &[Filter]) -> ArtStyle { && count(false) <= 1 && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. })) && st.looks.iter().all(|l| l.visible && l.opacity >= 1.0 && l.blend == BlendMode::Normal && l.effects.is_empty()) - && st.effects.iter().all(|e| { - matches!( - e.id.as_str(), - "stylize.dropShadow" - | "stylize.innerGlow" - | "stylize.outerGlow" - | "stylize.feather" - | "stylize.roundCorners" - | "stylize.scribble" - | "convertToShape.rectangle" - | "convertToShape.roundedRectangle" - | "convertToShape.ellipse" - | "path.offsetPath" - | "path.outlineObject" - | "path.outlineStroke" - ) || is_pathfinder(&e.id) - }) + && st.effects.iter().all(any_object_takes) + // An effect that moves the outline is drawn on its own: with others, their order and what + // scales with it aren't kept. + && (!st.moves_outline() || st.effects.len() == 1) // Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group). && (!st.pathfinder || st.items.is_empty()); st diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 2815f589c5..4b6cc1502a 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -891,6 +891,48 @@ fn pucker_and_twist_keep_their_sense() { assert_eq!(read_effect("Adobe Twirl", "4000 /Real (angle) ,\n"), None); } +#[test] +fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() { + // GUARDS: `simple` left out every Distort & Transform effect, so only type took them. + let simple = |name: &str, keys: &str| { + let st = distort_effect_style(name, keys); + assert!(st.plain, "{name}: {st:?}"); + st.simple + }; + assert!(simple("Adobe Twirl", "45 /Real (angle) ,\n")); + assert!(simple("Adobe Transform", &format!("0.5 /Real (scaleH_Factor) ,\n{SWITCHES}"))); + assert!(simple("Adobe Scribble and Tweak", "")); + assert!(simple("Adobe Punk and Bloat", "")); + assert!(simple("Adobe Free Distort", "")); + // A slant: the bottom edge moved as far as the top one. + let src = [[0.0, 0.0], [1.0, 0.0], [0.0, -1.0], [1.0, -1.0]]; + assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n")); + assert!(!simple("Adobe Zigzag", "")); + assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}"))); + // With another effect, only type takes it. + let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")]; + let data = format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &chain)); + let st = art_styles(data.as_bytes()).remove("Fx").unwrap_or_default(); + assert!(st.plain && !st.simple, "{st:?}"); +} + +#[test] +fn affine_corners_are_a_parallelogram_however_far_they_reach() { + assert!(affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.0], [190.0, -260.0]]}))); + assert!(!affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.01], [190.0, -260.0]]}))); + // Far from the box, a small shape is held to its own size. + assert!(!affine(&json!({"corners": [[9999.0, 0.0], [10000.0, 0.0], [10000.05, 1.0], [9999.0, 1.0]]}))); + // GUARDS: a slant written in rounded decimals, in a frame of 33.333 pt, missed by a hair. + let src = [[0.0, 0.0], [33.333, 0.0], [0.0, -33.333], [33.333, -33.333]]; + let slant = distort_effect_style("Adobe Free Distort", &corners(src, [[6.6667, 0.0], [40.0, 0.0], [0.0, -33.333], [33.333, -33.333]])); + assert!(slant.plain && slant.simple, "{slant:?}"); + assert!(!affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]}))); + assert!(!affine(&json!({}))); +} + #[test] fn roughen_keeps_the_drawn_look() { // Its outline is random and the file holds no seed; at a size of 0 the effect still redraws the diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index fabf97a5db..0a1938dff9 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -229,6 +229,163 @@ fn a_note_or_ap_in_a_skipped_section_does_not_reach_the_art_after_it() { assert!(!n.shows_center()); } +/// A node's URL and data (object tags), empty when it has no attributes. +fn tags(n: &Node) -> (String, Vec<(String, String)>) { + n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone())).unwrap_or_default() +} + +fn tag(id: &str, value: &str) -> (String, String) { + (id.to_string(), value.to_string()) +} + +/// `/identifier (string) XT` tags the object before it (version 7 specification §7): `AdobeURL` +/// is its URL, and other tags go to its data in order, an empty string included. Paths, groups, +/// compound paths, text objects and images take tags. +#[test] +fn object_tags_are_kept_on_the_object_before_them() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Hi) Tx\nTO\n"; + let body = format!( + "{a}N\n/part_no (A-12) XT\n/AdobeURL (https://example.com/a) XT\n/part_no (A-13) XT\n\ + u\n{b}f\nU\n/hand () XT\n*u\n{c}f\n{d}f\n*U\n/shape (two \\(parts\\)) XT\n{text}/AdobeURL (https://example.com/t) XT\n{a}f\n" + ); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let got: Vec<_> = art(&r.doc).iter().map(|n| tags(n)).collect(); + assert_eq!( + got, + [ + ("https://example.com/a".to_string(), vec![tag("part_no", "A-12"), tag("part_no", "A-13")]), + (String::new(), vec![tag("hand", "")]), + (String::new(), vec![tag("shape", "two (parts)")]), + ("https://example.com/t".to_string(), vec![]), + (String::new(), vec![]), + ] + ); + assert!(r.warnings.is_empty() && r.unread.is_empty(), "{:?} {:?}", r.warnings, r.unread); + // The group's and the compound path's paths keep no tags of their own. + for n in &art(&r.doc)[1..3] { + assert!(n.children().unwrap().iter().all(|k| k.extras().attrs.is_none())); + } + // A later `AdobeURL` replaces an earlier one. + let body = format!("{a}f\n/AdobeURL (https://example.com/1) XT\n/AdobeURL (https://example.com/2) XT\n"); + assert_eq!(tags(&art(&read7(&layer7("L", &body)).doc)[0]).0, "https://example.com/2"); +} + +/// A tag with no object right before it (at a layer's start, after a state change, after a group +/// opens) and a tag with an empty identifier tag nothing; one with operands of another kind is an +/// operator the reader doesn't know. +#[test] +fn object_tags_without_an_object_before_them_tag_nothing() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + for body in + [format!("/first (x) XT\n{a}f\n"), format!("{a}f\n1 w\n/late (x) XT\n"), format!("u\n/inside (x) XT\n{a}f\nU\n"), format!("{a}f\n/ (x) XT\n")] + { + let doc = read7(&layer7("L", &body)).doc; + let mut all = art(&doc); + all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::>()); + assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); + } + for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { + let err = read(stream7(&layer7("L", &format!("{a}f\n{bad}"))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{bad}: {err}"); + } + // Outside any layer too. + let err = read(stream7(&format!("(x) (y) XT\n{}", layer7("L", &format!("{a}f\n")))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{err}"); +} + +/// A clipping path's tags are its own, not those of the copy that paints its fill, and a clip +/// group's tags after `Q` are the group's. One object keeps at most 64 tags in its data. +#[test] +fn object_tags_on_clipping_paths_and_the_tag_limit() { + let body = format!( + "0 Ae\nq\n{RED}{}W\nf\n/edge (clip) XT\n{}f\nQ\n/group (clipped) XT\n", + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(0.0, 0.0, 30.0, 30.0) + ); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc); + assert_eq!(top.len(), 1); + assert_eq!(tags(&top[0]).1, [tag("group", "clipped")]); + let tagged: Vec<_> = top[0].children().unwrap().iter().filter(|k| !tags(k).1.is_empty()).map(|k| k.kind.clone()).collect(); + assert_eq!(tagged.len(), 1, "{tagged:?}"); + assert!(matches!(tagged[0], NodeKind::Path { clipping: true, .. }), "{tagged:?}"); + let many: String = (0..70).map(|i| format!("/t{i} ({i}) XT\n")).collect(); + let body = format!("{}f\n{many}/AdobeURL (https://example.com) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let (url, data) = tags(&art(&read_ok(&layer(&body)).doc)[0]); + assert_eq!(data.len(), 64); + assert_eq!(data.last(), Some(&tag("t63", "63"))); + assert_eq!(url, "https://example.com", "the URL is kept past the limit"); + // A tag whose identifier or string is longer than 64 KiB is ignored. + let long = "x".repeat(64 * 1024 + 1); + let body = format!("{}f\n/{long} (a) XT\n/b ({long}) XT\n/c (ok) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + assert_eq!(tags(&art(&read_ok(&layer(&body)).doc)[0]).1, [tag("c", "ok")]); +} + +/// An image takes the tags after it, as any other object does. +#[test] +fn object_tags_after_an_image_are_its_own() { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 3); + let at = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap(); + data.splice(at..at, b"/AdobeURL (https://example.com/i) XT\r\n/sku (I-1) XT\r\n".iter().copied()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/i".to_string(), vec![tag("sku", "I-1")])); +} + +/// The state written after a group's end or a gradient mesh's `/End X!` is still theirs when the +/// object's tags come first. +#[test] +fn object_tags_before_a_group_or_mesh_state_leave_it_theirs() { + let body = format!("{RED}0 Ae\nu\n0 0.5 0 0 0 Xy\n{}f\nU\n/hand (x) XT\n0 0 Xd\n6 () XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&layer(&body)).doc; + assert_eq!((art(&doc)[0].opacity, tags(&art(&doc)[0]).1), (0.5, vec![tag("hand", "x")])); + let corner = + |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1); + let mesh = format!( + "/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + let doc = read_ok(&layer(&format!("{mesh}/hand (y) XT\n1 0.35 0 0 0 Xy\n0 0 Xd\n6 () XW\n"))).doc; + let (m, l) = (&art(&doc)[0], &doc.layers[0]); + assert!(matches!(m.kind, NodeKind::Mesh(_)), "{m:#?}"); + assert_eq!((m.opacity, m.blend, tags(m).1), (0.35, BlendMode::Multiply, vec![tag("hand", "y")])); + assert_eq!((l.opacity, l.blend), (1.0, BlendMode::Normal), "not the layer's"); +} + +/// The tags of an object whose drawn look stands for it (its style not found) stay with the look. +#[test] +fn a_drawn_look_keeps_its_objects_tags() { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let body = format!( + "0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{hidden_rect}n\n%_/AdobeURL (https://example.com/n) XT\n%_/sku (N-1) XT\n1 (Gone style) XW\n", + rect_path(0.0, 0.0, 10.0, 10.0), + ); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("sku", "N-1")])); + // A look with tags of its own keeps them, and takes the object's after them. + let a = art(&read_ok(&layer(&body.replace("U\n0 0 Xd", "U\n/own (L) XT\n0 0 Xd"))).doc); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("own", "L"), tag("sku", "N-1")])); +} + +/// Tags in a brush's art don't keep it from being read, and stay out of the art: it isn't an object +/// of the document. +#[test] +fn a_brushs_art_with_tags_is_read_without_them() { + let art_ = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0 g\n{}f\n/sku (D-1) XT\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + let r = read_ok(&format!("{art_}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter: {:?}", r.warnings) }; + assert_eq!(s.art.geometric_bounds().map(|b| (b.width(), b.height())), Some((4.0, 4.0))); + assert!(s.art.extras().attrs.is_none(), "{:?}", s.art.extras().attrs); +} + #[test] fn paths_colours_and_strokes() { let art_ = format!( @@ -448,12 +605,82 @@ fn a_gradient_stop_naming_a_process_colour_leaves_its_swatch_process() { assert!(near(sw.paint.color()), "{sw:?}"); } +/// A gradient whose name in the file is shown as the name of a color a later gradient's stop names +/// is numbered: the color keeps its swatch. +#[test] +fn a_gradient_shown_as_a_stops_color_name_is_numbered() { + let first = "%AI5_BeginGradient: (Test Cyan\\n1)\n(Test Cyan\\n1) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let brand = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\ + %_0.93 0.1 0 0 (Test Cyan) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let art_ = format!("Bb\n1 (Test Cyan\\n1) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{first}{brand}{}", layer(&art_))).doc; + let Paint::Gradient(g) = fill(&art(&doc)[0]) else { panic!("{:?}", fill(&art(&doc)[0])) }; + assert_eq!(g.swatch.as_deref(), Some("Test Cyan 2")); + let sw = doc.swatch("Test Cyan").unwrap(); + assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global, "{sw:?}"); +} + +/// A gradient whose name has no newline keeps it when a gradient shown as that name is defined +/// first: the one shown up to its newline is numbered. +#[test] +fn a_gradient_name_without_a_newline_is_kept_whichever_comes_first() { + let gradient = |name: &str| format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"); + let filled = |name: &str| format!("Bb\n1 ({name}) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{}{}{}", gradient("Sky\\n1"), gradient("Sky"), layer(&format!("{}{}", filled("Sky\\n1"), filled("Sky"))))).doc; + let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Gradient(g) = fill(n) { g.swatch.clone() } else { None }).collect(); + assert_eq!(links, [Some("Sky 2".to_string()), Some("Sky".to_string())]); + // A gradient without stops isn't kept, and its name stays free. + let empty = "%AI5_BeginGradient: (Sky)\n(Sky) 0 0 Bd\n[\nBD\n%AI5_EndGradient\n"; + let doc = read_ok(&format!("{empty}{}{}", gradient("Sky\\n1"), layer(&filled("Sky\\n1")))).doc; + assert!(matches!(fill(&art(&doc)[0]), Paint::Gradient(g) if g.swatch.as_deref() == Some("Sky"))); +} + /// A pattern's definition (`%AI3_BeginPattern`): its name and tile (8 points square here, y up), /// then its art on `%_` lines (a group of the tile's unpainted box and a dot, a round-capped /// stroke of no length), `E`. const DOTS: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 8 8\n%_0 A\n%_0 Xw\n%_0 Ae\n%_u\n%_0 O\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n\ %_0 R\n%_0 0 0 1 K\n%_1 J 0 j 2 w 4 M []0 d\n%_4 4 m\n%_4 4 L\n%_S\n%_U\n%_/ArtDictionary :\n%_;\n%_\n%_9 () XW\nE\n%AI3_EndPattern\n"; +/// An unpainted box that a pattern's definition marks as its tile's box isn't art; a painted one +/// with the mark stays. +#[test] +fn a_patterns_marked_tile_box_is_not_art() { + let mark = "%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"; + let def = |paint: &str, op: &str| { + format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{paint}0 XR\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_{op}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ) + }; + let layer = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n(Box) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0) + ); + let s = read_ok(&format!("{}{layer}", def("", "n"))); + let art = &s.doc.pattern("Box").unwrap().art; + assert_eq!(art.len(), 1, "the square only"); + assert_eq!(art[0].geometric_bounds(), Some(Rect::new(2.0, -6.0, 6.0, -2.0))); + let s = read_ok(&format!("{}{layer}", def("1 0 0 0 k\n%_", "f"))); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "a painted box is art"); + // The mark after a group or a compound path of an unpainted box leaves it in the art. + for (open, close, kind) in [("u", "U", "group"), ("*u", "*U", "compound path")] { + let def = format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{open}\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n%_{close}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ); + let s = read_ok(&format!("{def}{layer}")); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "after a {kind}"); + } + // Outside a pattern's definition the mark leaves the box in the art. + let marked = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 XR\n{}n\n{mark}0 0 0 1 k\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0), + rect_path(20.0, 30.0, 40.0, 50.0) + ); + let s = read_ok(&marked); + assert_eq!(s.doc.layers[0].children().unwrap().len(), 2, "outside a pattern"); +} + /// Patterns are read into pattern swatches, and `p` fills with one (#1025): the art keeps its /// layers, the fill places the tiles by its matrix. #[test] @@ -491,6 +718,116 @@ fn patterns_are_pattern_swatches_and_fill_with_them() { assert!(s.warnings.is_empty(), "{:?}", s.warnings); } +/// A pattern's name in the file is shown up to its newline (AI7 spec §4): two patterns named +/// `Dots` apart from what follows the newline are "Dots" and "Dots 2", each fill paints with its +/// own, and one defined again under its name in the file replaces the first. +#[test] +fn pattern_names_are_shown_up_to_their_newline() { + let def = |name: &str, tile: u32| DOTS.replace("(Dots)", &format!("({name})")).replace("0 0 8 8\n", &format!("0 0 {tile} {tile}\n")); + let filled = |name: &str| format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0)); + let body = format!( + "{}{}{}{}", + def("Dots\\n1", 8), + def("Dots\\n2", 8), + def("Dots\\n2", 9), + layer(&format!("{}{}", filled("Dots\\n2"), filled("Dots\\n1"))) + ); + let s = read_ok(&body); + let doc = &s.doc; + let tiles: Vec<_> = doc.patterns.iter().map(|p| (p.name.as_str(), p.tile.width())).collect(); + assert_eq!(tiles, [("Dots", 8.0), ("Dots 2", 9.0)]); + for name in ["Dots", "Dots 2"] { + assert!(matches!(&doc.swatch(name).unwrap().paint, Paint::Pattern { pattern, .. } if pattern == name), "{name}"); + } + let fills: Vec<_> = art(doc).iter().map(|n| if let Paint::Pattern { pattern, .. } = fill(n) { pattern } else { String::new() }).collect(); + assert_eq!(fills, ["Dots 2", "Dots"]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // Without a palette (or with an empty one) the document keeps its default swatches, and a named + // color the art uses has its swatch: a pattern takes none of their names. + let empty = "%AI5_BeginPalette\n0 0 Pb\nPB\n%AI5_EndPalette\n"; + let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + for palette in ["", empty] { + let body = + format!("{}{}{palette}{}", def("Black\\n1", 8), def("Ink\\n1", 8), layer(&format!("{}{}{ink}", filled("Black\\n1"), filled("Ink\\n1")))); + let doc = read_ok(&body).doc; + for (solid, pattern) in [("Black", "Black 2"), ("Ink", "Ink 2")] { + assert!(matches!(&doc.swatch(pattern).unwrap().paint, Paint::Pattern { pattern: p, .. } if p == pattern), "{palette:?}"); + assert!(matches!(doc.swatch(solid).unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + } + let fills: Vec<_> = art(&doc).iter().map(|n| fill(n)).collect(); + assert!(matches!(&fills[..2], [Paint::Pattern { pattern: a, .. }, Paint::Pattern { pattern: b, .. }] if a == "Black 2" && b == "Ink 2")); + } + // Nor the name of a custom color the program of an EPS gives, or None's. + let ps = b"%!PS-Adobe-3.0\n%%CMYKCustomColor: 0 0 1 0 (Outer Ink)\n%%EndComments\n"; + let data = stream(&format!("{}{}{}", def("Outer Ink\\n1", 8), def("[None]\\n1", 8), layer(&filled("Outer Ink\\n1")))); + let doc = super::read_beside(data.as_bytes(), true, ps).unwrap().doc; + assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Outer Ink 2", "[None] 2"]); + assert!(matches!(doc.swatch("Outer Ink").unwrap().paint, Paint::Solid { .. })); + assert!(matches!(fill(&art(&doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Outer Ink 2")); +} + +/// A pattern shown as the name of one of the document's other swatches is numbered: a swatch or a +/// color group of the palette the reader keeps (under any version's prefix, a swatch it names by +/// its values too), Registration, and a custom color of the editing data's own header. A pattern +/// whose name has no newline keeps it, whichever is defined first. The default swatches go when a +/// palette replaces them, and their names are free then; a palette only in versioned content that +/// isn't read replaces nothing. +#[test] +fn pattern_names_are_numbered_around_the_documents_swatches() { + let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})")); + let palette = "%AI12_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n1 (Greys) 1 Pg\n0 0 0 0.2 k\nPc\nPB\n%AI12_EndPalette\n"; + let header = "%%CMYKCustomColor: 0 0 1 0 (Head Ink)\n"; + let doc = |defs: &[&str], palette: &str| { + let body = format!("{}{palette}{}", defs.iter().map(|n| def(n)).collect::(), layer("")); + read(stream_with_header(header, &body).as_bytes()).unwrap().doc + }; + let names = |d: &Document| d.patterns.iter().map(|p| p.name.clone()).collect::>(); + let d = doc(&["Mist\\n1", "Greys\\n1", "[Registration]\\n1", "Head Ink\\n1", "Red\\n1", "Sky\\n1", "Sky"], palette); + let generated = d.swatch_groups[0].swatches[0].name.clone(); + let all: Vec<&str> = d.swatches_iter().map(|s| s.name.as_str()).collect(); + assert!(d.swatch("Mist").is_some() && d.swatch("Head Ink").is_some(), "{all:?}"); + assert!(matches!(&d.swatch("Red").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Red"), "{all:?}"); + assert_eq!(names(&d), ["Mist 2", "Greys 2", "[Registration] 2", "Head Ink 2", "Red", "Sky 2", "Sky"]); + let d = doc(&[&format!("{generated}\\n1")], palette); + assert_eq!(names(&d), [format!("{generated} 2")]); + // Without a palette the default swatches stay, and so they do when the only palette is in + // versioned content that isn't read. + let versioned = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{palette}%AI17_End_Versioned_Content\n"); + for palette in ["", &versioned] { + let d = doc(&["Red\\n1"], palette); + assert!(matches!(d.swatch("Red").unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + assert_eq!(names(&d), ["Red 2"], "{palette:?}"); + } + // A pattern and a color in versioned content that isn't read take no name. + let unread = format!( + "%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}{}%AI17_End_Versioned_Content\n", + def("Sky"), + layer("0 1 1 0 (Sea) 0 x\n") + ); + let d = doc(&["Sky\\n1", "Sea\\n1"], &unread); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Nor does a color of a palette that a later one replaces, or of a palette's alternate. + let replaced = "%AI5_BeginPalette\n0 0 Pb\n0 1 1 0 (Sky) 0 x\n(Sky)\nPc\nPB\n%AI5_EndPalette\n\ + %AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:17 1\n0 0 0 1 k\n(Ink)\nPc\n\ + %AI17_Alternate_Content\n0 1 0 0 (Sea) 0 x\n(Sea)\nPc\n%AI17_End_Versioned_Content\nPB\n%AI5_EndPalette\n"; + let d = doc(&["Sky\\n1", "Sea\\n1"], replaced); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Versioned content that doesn't end is read whole, its colors too. + let unended = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}", layer("0 1 1 0 (Sea) 0 x\n")); + let d = doc(&["Sea\\n1"], &unended); + assert_eq!(names(&d), ["Sea 2"]); +} + +/// A palette's pattern swatch named by its pattern takes the name the pattern is shown with. +#[test] +fn a_palette_pattern_swatch_takes_its_patterns_shown_name() { + let palette = "%AI5_BeginPalette\n0 0 Pb\n(Dots\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPB\n%AI5_EndPalette\n"; + let doc = read_ok(&format!("{}{palette}{}", DOTS.replace("(Dots)", "(Dots\\n1)"), layer(""))).doc; + let names: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["[None]", "Dots"]); + assert!(matches!(&doc.swatch("Dots").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Dots")); +} + /// Where a definition draws its tile doesn't move the fill: the tile's lower left is the pattern's /// origin, so the same dots drawn at 30..38 × 40..48 tile as they do at 0..8 × 0..8. #[test] @@ -658,6 +995,17 @@ fn a_version_7_patterns_underbar_fills_the_tile_box() { assert!(def.art[1].appearance.stroke().is_some()); } +/// A version 7 pattern shown as the name of a custom color its own layer strings use is numbered: +/// the color keeps its swatch. +#[test] +fn a_version_7_pattern_shown_as_its_colors_name_is_numbered() { + let layers = "(0 O 0 R 0 0 0 1 \\(Ink\\) 0 x) @ (2 2 m 9 2 L 9 9 L f) &\n"; + let s = pattern_read7(&pattern7("Ink\\n1", layers), &pattern_layer7("Art", "")); + assert_eq!(s.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Ink 2"]); + assert!(matches!(&s.doc.swatch("Ink 2").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Ink 2")); + assert!(matches!(s.doc.swatch("Ink").unwrap().paint, Paint::Solid { .. })); +} + /// A layer's strings are read with their escapes undone: `\r`, `\n`, an octal tab, a backslash at /// a line's end, and escaped parentheses around a custom color's name. #[test] @@ -798,6 +1146,20 @@ fn a_style_pattern_fill_is_placed_as_a_direct_one() { } } +/// An art style's pattern fill paints with the pattern under the name it is shown with. +#[test] +fn a_style_pattern_fill_paints_with_the_shown_name() { + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let defs = format!("{}{}", pattern7("Grid", "(0 g) @ _ &\n"), pattern7("Grid\\n1", "(0 g) @ _ &\n")); + let s = read_ok(&format!("{}{defs}{}", tiled_style("Grid\\n1", "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let pattern = |n: &Node| match fill(n) { + Paint::Pattern { pattern, .. } => pattern, + p => panic!("{p:?} {:?} {:?}", s.unread, s.warnings), + }; + assert_eq!(pattern(&art(&s.doc)[0]), "Grid 2"); +} + #[test] fn compound_paths_and_clipping() { let art_ = format!( @@ -863,18 +1225,132 @@ fn a_clipping_paths_stroke_stays_on_the_clipping_path() { children(&read_ok(&format!("{defs}{}", layer(&gradient))).doc), [(true, None, false, Some((blue, 3.0))), (false, None, true, None), (false, red, false, None)] ); - // Several clipping paths clip as one compound path, which keeps their stroke when they all have the same one. + // Several clipping paths each keep their own stroke, opacity and blend mode: the second one clips a clipping group + // inside the first one's. let inner = rect_path(10.0, 10.0, 20.0, 20.0); - let compound_stroke = |first: &str, second: &str| { + let strokes = |first: &str, second: &str| { let body = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{first}{clip}W\nS\n{second}{inner}W\nS\nQ\n"); let doc = read_ok(&layer(&body)).doc; let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; - assert!(matches!(children[0].kind, NodeKind::Compound { .. }), "{:?}", children[0].kind); - (children[0].appearance.stroke().map(|s| (s.paint.color(), s.width)), children[0].opacity, children[0].blend) + let NodeKind::Group { children: nested, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + [&children[0], &nested[0]].map(|c| { + assert!(matches!(c.kind, NodeKind::Path { clipping: true, .. }), "{:?}", c.kind); + (c.appearance.stroke().map(|s| (s.paint.color(), s.width)), c.opacity, c.blend) + }) }; - assert_eq!(compound_stroke("", ""), (Some((blue, 3.0)), 1.0, BlendMode::Normal)); - assert_eq!(compound_stroke("9 0.5 0 0 0 Xy\n", ""), (Some((blue, 3.0)), 0.5, BlendMode::Lighten)); - assert_eq!(compound_stroke("", "5 w\n"), (None, 1.0, BlendMode::Normal), "strokes that differ"); + let plain = (Some((blue, 3.0)), 1.0, BlendMode::Normal); + assert_eq!(strokes("", ""), [plain, plain]); + assert_eq!(strokes("", "9 0.5 0 0 0 Xy\n"), [plain, (Some((blue, 3.0)), 0.5, BlendMode::Lighten)]); + assert_eq!(strokes("", "5 w\n"), [plain, (Some((blue, 5.0)), 1.0, BlendMode::Normal)], "strokes that differ"); +} + +/// Several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection: each `W` +/// reduces the clip set by the ones before it (AI7 spec §5.6.2). Each clipping path after the first clips a clipping +/// group inside the one before it, and the innermost one holds the art; a clipping path's painted fill stays at its own +/// level. +#[test] +fn several_clipping_paths_clip_to_their_intersection() { + let square = rect_path(0.0, 0.0, 80.0, 80.0); + let (a, b) = (rect_path(20.0, 20.0, 60.0, 60.0), rect_path(25.0, 25.0, 70.0, 55.0)); + // (clipping, fill color, bounds) of a clipping group's children, with a nested clipping group's children listed + // after it. + type Level = Vec<(bool, Option, Option)>; + fn levels(children: &[Arc]) -> Vec { + let mut out = vec![]; + let mut at = children; + loop { + out.push(at.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color(), c.geometric_bounds())).collect()); + let Some(NodeKind::Group { children, clip: true }) = at.last().map(|c| &c.kind) else { return out }; + at = children; + } + } + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + // A rectangle as written, in the document's coordinates (y down from the 100 pt high page's top). + let r = |x0, y0, x1, y1| Some(Rect::new(x0, 100.0 - y1, x1, 100.0 - y0)); + let (ra, rb) = (r(20.0, 20.0, 60.0, 60.0), r(25.0, 25.0, 70.0, 55.0)); + let group = |body: &str| { + let doc = read_ok(&layer(body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + levels(children) + }; + // The art after both clipping paths, in a clipping group of the second inside the first's. + let two = group(&format!("0 Ae\nq\n{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((two.len(), two[0].len()), (2, 2), "{two:?}"); + assert_eq!(two[0][0], (true, None, ra)); + assert_eq!(two[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Three clipping paths nest twice; a filled clipping path's painted copy is clipped by the paths before it only. + let three = + group(&format!("0 Ae\nq\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{b}h\nW\nf\n{}h\nW\nn\n{RED}{square}f\nQ\n", rect_path(30.0, 10.0, 50.0, 90.0))); + assert_eq!(three.len(), 3, "{three:?}"); + assert_eq!(three[1][..2], [(true, None, rb), (false, blue, rb)]); + assert_eq!(three[2], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // As with one clipping path, every object in the group is clipped by all of them, in the order written, wherever + // it is written. + let small = rect_path(0.0, 0.0, 10.0, 10.0); + let before = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n{b}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\nQ\n")); + assert_eq!(before.len(), 2, "{before:?}"); + assert_eq!(before[1], [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0))]); + let between = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((between.len(), between[0].len()), (2, 2), "{between:?}"); + assert_eq!( + between[1], + [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))] + ); + // A compound clipping path and a clipping path after it: their union, then that intersected with the second. + let c = rect_path(30.0, 10.0, 50.0, 90.0); + let mixed = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{c}h\nW\nn\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&mixed)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + assert_eq!(levels(children)[1], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Clipping paths alone in a group (`u W n W n U`) clip the clipping group around it the same way. + let grouped = group(&format!("0 Ae\nq\n{RED}{square}f\n0 Ae\nu\n{a}h\nW\nn\n{b}h\nW\nn\nU\nQ\n")); + assert_eq!(grouped.len(), 2, "{grouped:?}"); + assert_eq!(grouped[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // A compound path of clipping paths is still one clipping path, their union. + let compound = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&compound)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + // Two clipping paths in a layer: the layer clips by the first, a clipping group in it by the second. + let doc = read_ok(&layer(&format!("{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\n"))).doc; + let NodeKind::Layer { clip: true, children, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + let in_layer = levels(children); + assert_eq!(in_layer.len(), 2, "{in_layer:?}"); + assert_eq!(in_layer[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Two clipping paths in an opacity mask's art: the art clips by the first, a clipping group in it by the second. + let mask_art: String = format!("{a}h\nW\nn\n{b}h\nW\nn\n1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let doc = read_ok(&layer(&format!("{RED}{square}f\n{mask}"))).doc; + let m = art(&doc)[0].extras().mask.clone().unwrap(); + let NodeKind::Group { children, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + let in_mask = levels(children); + assert_eq!(in_mask.len(), 2, "{in_mask:?}"); + assert_eq!((in_mask[0][0].0, in_mask[0][0].2, in_mask[1][0]), (true, ra, (true, None, rb))); + assert_eq!(in_mask[1].len(), 2, "{in_mask:?}"); + // Clipping paths are nested as far as the document's depth limit allows; past it they are refused rather than + // merged away, in a clipping group, a layer and an opacity mask's art. + let fits = |text: &dyn Fn(usize) -> String| (2..400).take_while(|n| read(stream(&layer(&text(*n))).as_bytes()).is_ok()).last().unwrap(); + let deep = |n: usize, last: &str| format!("0 Ae\nq\n{}{last}{RED}{square}f\nQ\n", format!("{a}h\nW\nn\n").repeat(n)); + // The layer is 1 deep, the clipping group 2, and the art in the innermost of `n` levels `n + 2`. + let in_group = fits(&|n| deep(n, "")); + assert_eq!(in_group, vectorcraft_doc::MAX_DEPTH - 2); + let r = read_ok(&layer(&deep(in_group, ""))); + let NodeKind::Group { children, clip: true } = &art(&r.doc)[0].kind else { panic!("{:?}", art(&r.doc)[0].kind) }; + assert_eq!(levels(children).len(), in_group, "{:?}", r.warnings); + assert!(read(stream(&layer(&deep(400, ""))).as_bytes()).unwrap_err().contains("nested too deeply")); + let in_layer = fits(&|n| format!("{}{RED}{square}f\n", format!("{a}h\nW\nn\n").repeat(n))); + assert_eq!(in_layer, vectorcraft_doc::MAX_DEPTH - 1); + let in_mask = fits(&|n| { + let art: String = format!("{}1 g\n{square}f\n", format!("{a}h\nW\nn\n").repeat(n)).lines().map(|l| format!("%_{l}\n")).collect(); + format!("{RED}{square}f\n%_/ArtDictionary :\n%_/Mask :\n%_X=\n{art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n") + }); + // The masked object is 2 deep and its mask's art 3. + assert_eq!(in_mask, vectorcraft_doc::MAX_DEPTH - 3); + // A compound clipping path holds its subpaths one level down: as the innermost one, it adds a level. + let compound_last = format!("*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n"); + assert!(read(stream(&layer(&deep(in_group - 1, &compound_last))).as_bytes()).unwrap_err().contains("nested too deeply")); } /// A clipping group's clipping path can sit alone in a group of its own, after the art it clips (`q … u W n U @@ -1259,6 +1735,35 @@ fn artboards() { assert_eq!(doc.artboards[0].rect, Rect::new(0.0, 0.0, 600.0, 400.0)); } +#[test] +fn the_active_artboard_is_the_one_crop_area_active_names() { + let board = |x: i32, w: i32| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x + w + ) + }; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + // Four artboards in the array, the second of no width (left out); `entry` follows the array. + let opened = |entry: &str| { + let boards = [board(0, 100), board(200, 0), board(400, 100), board(600, 100)].concat(); + let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n{entry}%_; /NotRecorded ,\n%_;\n{square}"); + let doc = read_ok(&data).doc; + doc.opened_artboard.map(|id| doc.artboards.iter().position(|a| a.id == id)) + }; + // The index counts every entry of the array, the one left out too. + assert_eq!(opened("%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + assert_eq!(opened("%_2 /Int (CropAreaActive) ,\n"), Some(Some(1))); + // After another entry of the dictionary that holds the array. + assert_eq!(opened("%_1 /Int (Other) ,\n%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + // The first artboard, the one left out, one past the end, a value of another type, or none. + for entry in + ["%_0 /Int (CropAreaActive) ,\n", "%_1 /Int (CropAreaActive) ,\n", "%_4 /Int (CropAreaActive) ,\n", "%_2 /Real (CropAreaActive) ,\n", ""] + { + assert_eq!(opened(entry), None, "{entry}"); + } +} + /// The document data of artboards side by side, 100 points wide, each with the entries `extra`. fn boards_with(extra: &[&str]) -> String { let boards: String = extra @@ -1799,6 +2304,35 @@ fn a_drawn_look_that_is_an_image_stands_for_its_object() { assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); } +/// The name and opacity mask after an image follow the operators that end its raster: `XH`, the +/// versioned `Xr` and the `N` after `%AI5_EndRaster`. +#[test] +fn an_images_name_and_mask_follow_the_end_of_its_raster() { + let mask = "%_/ArtDictionary :\r\n%_/Mask :\r\n%_X=\r\n%_0 g\r\n%_0 0 m\r\n%_5 0 l\r\n%_5 5 l\r\n%_f\r\n%_X+\r\n%_ (Art) ,\r\n\ + %_0 /Bool (Clipping) ,\r\n%_0 /Bool (Inverted) ,\r\n%_0 /Bool (Disabled) ,\r\n%_1 /Bool (Linked) ,\r\n%_; (AI9_Mask) ,\r\n\ + %_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n"; + for tail in [ + "XH\r\n%AI5_EndRaster\r\nN\r\n", + "XH\r\n%AI17_Begin_Content_if_version_gt:24 17\r\n72 72 Xr\r\n%AI17_End_Versioned_Content\r\n%AI5_EndRaster\r\nN\r\n", + ] { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let at = data.windows(6).position(|w| w == b"XH\r\n%A").unwrap(); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(at..end, [tail, mask].concat().into_bytes()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{:?}", a[0].kind); + assert_eq!(a[0].name.as_deref(), Some("Photo")); + assert!(a[0].extras().mask.is_some()); + } + // An operator of another kind in between ends the image: the name has no object. + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(end..end, b"0 A\r\n%_/ArtDictionary :\r\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n".to_vec()); + assert_eq!(art(&read(&data).unwrap().doc)[0].name, None); +} + fn pixels(doc: &Document) -> (image::RgbaImage, kurbo::Affine) { let a = art(doc); let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; @@ -1833,6 +2367,61 @@ fn one_bit_images_read_each_channel() { assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [255, 0, 255]); } +/// A gray image `w` × 1 in hex with ImageMask `mask` and `bits` bits a pixel, after the fill `fill`. +fn masked_gray(fill: &str, bits: u32, mask: u32, w: u32, hex: &[u8]) -> Vec { + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (w, 1), ("DeviceGray", 1, 0), hex, hex.len())).unwrap(); + text.replacen(" 8 1 0 0 1 0 ", &format!(" {bits} 1 0 0 0 {mask} "), 1).replacen("(L) Ln\n", &format!("(L) Ln\n{fill}"), 1).into_bytes() +} + +/// ImageMask 1 on a 1-bit gray image: the image is colorized with the fill color, so its black +/// pixels take the color and its white ones are transparent. ImageMask 0 keeps the opaque image. +#[test] +fn image_masks_are_colorized_with_the_fill() { + // 4 × 1 at 1 bit: black, white, white, black (0110). + let r = read(&masked_gray("0 0 1 0 k\n", 1, 1, 4, b"60")).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + let Some(Paint::Solid { color, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::cmyk(0.0, 0.0, 1.0, 0.0).to_rgba8(1.0)); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let blob = &r.doc.images[&im.key]; + assert!(blob.gray_source().is_some_and(|g| !g.alpha), "an image a fill color can colorize"); + let img = pixels(&r.doc).0; + assert_eq!( + (0..4).map(|x| img.get_pixel(x, 0).0).collect::>(), + [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]] + ); + // How much of the color each pixel shows: the black ones only. + assert_eq!(blob.coverage().map(|c| c.2), Some(vec![255, 0, 0, 255])); + // A spot color keeps its swatch and tint. + let spot = "0 0 1 0 (Ink) 0.5 0 Xx\n"; + let a = art(&read(&masked_gray(spot, 1, 1, 4, b"60")).unwrap().doc); + assert!( + matches!(a[0].extras().colorize.as_deref(), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (*tint - 0.5).abs() < 1e-6), + "{:?}", + a[0].extras().colorize + ); + // A fill that isn't a solid color (here a pattern) colorizes it black. + let patterned = String::from_utf8(masked_gray("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n", 1, 1, 4, b"60")).unwrap(); + let doc = read(patterned.replacen("%AI5_BeginLayer", &format!("{DOTS}%AI5_BeginLayer"), 1).as_bytes()).unwrap().doc; + let a = art(&doc); + let Some(Paint::Solid { color, swatch: None, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::BLACK.to_rgba8(1.0)); + // An 8-bit gray image with ImageMask 1 opens as before, with no color. + let doc = read(&masked_gray("0 1 0 0 k\n", 8, 1, 2, b"00ff")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(1, 0).0, [255, 255, 255, 255]); + // ImageMask 0: the opaque image, with no color. + let doc = read(&masked_gray("0 0 1 0 k\n", 1, 0, 4, b"60")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [0, 0, 0, 255]); + // An RGB image can't take a color: ImageMask 1 leaves it as it is. + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (1, 1), ("DeviceRGB", 3, 0), b"ff0000", 6)).unwrap(); + let doc = read(text.replacen(" 8 3 0 0 1 0 ", " 8 3 0 0 0 1 ", 1).as_bytes()).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [255, 0, 0, 255]); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). @@ -1915,6 +2504,111 @@ fn a_rotated_image_is_placed_as_its_matrix_maps_it() { } } +/// A raster object in the version 7 form (§8): `%AI5_BeginRaster`, `head` (a link's `XG`, or +/// nothing), the operands `[matrix] 0 0 w h w h 8 3 0 0 0 0`, the operator `op` and `tail` (an +/// `XI`'s samples on `%` lines), `%AI5_EndRaster`. +fn raster7(head: &str, matrix: &str, (w, h): (u32, u32), op: &str, tail: &str) -> String { + format!("%AI5_File:\n%AI5_BeginRaster\n{head}{matrix} 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 {op}\n{tail}%AI5_EndRaster\n") +} + +/// A linked 1-bit gray image with ImageMask 1 keeps the fill color as the color that colorizes it, +/// as an embedded one does. Other linked images have no color. +#[test] +fn linked_image_masks_are_colorized_with_the_fill() { + let m = "[ 1 0 0 1 0 0 ]"; + let linked = |bits_kind_mask: &str| { + let xf = raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", &format!(" {bits_kind_mask} XF")); + let r = read(stream7(&layer7("L", &format!("0 0 1 0 (Ink) 0.5 0 Xx\n{xf}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[0].kind, NodeKind::Image(im) if im.link.is_some()), "{:?} {:?}", a, r.warnings); + a[0].extras().colorize.as_deref().cloned() + }; + assert!( + matches!(linked("1 1 0 0 0 1"), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (tint - 0.5).abs() < 1e-6), + "a 1-bit image mask" + ); + assert_eq!(linked("1 1 0 0 0 0"), None, "ImageMask 0"); + assert_eq!(linked("8 1 0 0 0 1"), None, "8-bit gray"); + assert_eq!(linked("8 3 0 0 0 1"), None, "RGB"); +} + +/// A linked image in the version 7 form (§8.2, §8.3), `(path) modified XG` and then `XF` with no +/// samples, is a linked image of that file. The data keeps no pixels of it, so it shows a +/// placeholder over the place the matrix maps the image's pixels to, as an embedded image (`XI`) +/// of the same operands is placed. +#[test] +fn a_version_7_linked_image_shows_a_placeholder_where_the_image_is() { + let (s, c) = 30f64.to_radians().sin_cos(); + for m in [[2.0, 0.0, 0.0, 3.0, 100.0, 400.0], [3.0 * c, 3.0 * s, -2.0 * s, 2.0 * c, 40.0, 60.0]] { + let matrix = format!("[ {} ]", m.map(|v| v.to_string()).join(" ")); + let linked = raster7("(Macintosh HD:Images:photo.tif) 0 XG\n", &matrix, (10, 20), "XF", ""); + let embedded = raster7("", &matrix, (10, 20), "XI", &"%FF0000\n".repeat(200)); + let r = read(stream7(&layer7("L", &format!("{linked}{embedded}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{:?}", r.warnings); + let (NodeKind::Image(link), NodeKind::Image(emb)) = (&a[0].kind, &a[1].kind) else { panic!("{:?}", a) }; + assert_eq!(link.link.as_ref().map(|l| l.path.as_str()), Some("Macintosh HD:Images:photo.tif")); + assert_eq!(emb.link, None, "an image whose samples follow stays embedded"); + assert!(r.doc.images[&link.key].is_proxy(), "the placeholder is what a missing link shows"); + // The file's pixels, placed as the embedded image's are: relinking keeps that size. + assert_eq!((link.width, link.height, link.xf), (emb.width, emb.height, emb.xf)); + assert_eq!((link.width, link.height), (10, 20)); + assert_eq!(r.warnings.iter().filter(|w| *w == read::LINKED_PLACEHOLDERS).count(), 1, "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); + } + // Images of other files keep images of their own, though each shows the same placeholder; two + // of one file share theirs. + let m = "[ 1 0 0 1 0 100 ]"; + let three = ["(a.tif) 0 XG\n", "(b.tif) 0 XG\n", "(a.tif) 0 XG\n"].map(|xg| raster7(xg, m, (2, 2), "XF", "")).concat(); + let r = read(stream7(&layer7("L", &three)).as_bytes()).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + +/// `XG` names the file of the `XF` after it only: an `XF` without a file name before it, after an +/// `XG` with operands of another shape or an empty path, or after an image that took the name, +/// is left out with a warning, as is one whose operands `XI` couldn't read. Of two `XG`s, the +/// second names the file. +#[test] +fn a_version_7_linked_image_without_its_file_name_is_left_out_with_a_warning() { + let m = "[ 1 0 0 1 0 100 ]"; + let embedded = raster7("() 1 XG\n", m, (1, 1), "XI", "%FF0000\n"); + for (what, src) in [ + ("no XG", raster7("", m, (2, 2), "XF", "")), + ("a name, not a string", raster7("/photo 0 XG\n", m, (2, 2), "XF", "")), + ("no modified flag", raster7("(a.tif) XG\n", m, (2, 2), "XF", "")), + ("an empty path", raster7("() 0 XG\n", m, (2, 2), "XF", "")), + ("taken by an embedded image", format!("{}{}", raster7("(a.tif) 0 XG\n", m, (1, 1), "XI", "%FF0000\n"), raster7("", m, (2, 2), "XF", ""))), + ("named in an earlier raster object", format!("%AI5_BeginRaster\n(a.tif) 0 XG\n%AI5_EndRaster\n{}", raster7("", m, (2, 2), "XF", ""))), + ("named outside a raster object", format!("(a.tif) 0 XG\n{}", raster7("", m, (2, 2), "XF", ""))), + ("too few operands", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 8 3 0 XF")), + ("no matrix", raster7("(a.tif) 0 XG\n", "", (2, 2), "XF", "")), + ("a matrix with no area", raster7("(a.tif) 0 XG\n", "[ 0 0 0 0 0 0 ]", (2, 2), "XF", "")), + ("no pixels", raster7("(a.tif) 0 XG\n", m, (0, 2), "XF", "")), + ("a side past the largest", raster7("(a.tif) 0 XG\n", m, (2_000_000, 2), "XF", "")), + ("samples of 7 bits", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 7 3 0 0 0 0 XF")), + ] { + let body = format!("{embedded}{src}"); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), body.matches(" XI\n").count(), "{what}: {:?}", r.warnings); + assert!(a.iter().all(|n| matches!(&n.kind, NodeKind::Image(im) if im.link.is_none())), "{what}: the embedded images only"); + let left_out = r.warnings.iter().filter(|w| *w == "an image VectorCraft can't read was left out").count(); + assert_eq!(left_out, 1, "{what}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{what}: {:?}", r.warnings); + } + // More pixels than an embedded image may have: no pixels are read, so the linked image comes in. + let r = read(stream7(&layer7("L", &raster7("(a.tif) 0 XG\n", m, (100_000, 100_000), "XF", ""))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if (im.width, im.height) == (100_000, 100_000))), "{a:?}"); + assert!(!r.warnings.iter().any(|w| w == read::IMAGE_TOO_LARGE), "{:?}", r.warnings); + let twice = raster7("(a.tif) 0 XG\n(b.tif) 0 XG\n", m, (2, 2), "XF", ""); + let r = read(stream7(&layer7("L", &twice)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.as_ref().is_some_and(|l| l.path == "b.tif"))), "{a:?}"); +} + /// CMYK images keep their ink amounts, as the file's PDF part keeps them, and an alpha channel /// becomes their opacity mask: a grayscale image over the image. #[test] @@ -2039,10 +2733,11 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() { assert_eq!(relative_of(&placed_in("( art /)", path, &preview)).as_deref(), Some(" art /photo.png"), "spaces are part of names"); // On `%_` lines too. assert_eq!(relative_of(&hide_placed(&placed_in("(src/)", path, &preview))).as_deref(), Some("src/photo.png")); - // No folder, an absolute one, one too long or not a string: the path alone, and the file still - // opens. + // An empty folder is the document's own: the file's name. + assert_eq!(relative_of(&placed_in("()", path, &preview)).as_deref(), Some("photo.png")); + // An absolute folder, one too long or not a string: the path alone, and the file still opens. let long = format!("({})", "a/".repeat(3000)); - for folder in ["()", "(/elsewhere/)", "(C:\\\\art\\\\)", long.as_str(), "12", "/src"] { + for folder in ["(/elsewhere/)", "(C:\\\\art\\\\)", long.as_str(), "12", "/src"] { assert_eq!(relative_of(&placed_in(folder, path, &preview)), None, "{folder}"); } // A section that doesn't end leaves the folder unread. @@ -2285,6 +2980,25 @@ fn xml_ids_stay_within_their_byte_budget() { assert_eq!(bytes, super::read::MAX_XML_ID_BYTES); } +/// Placed files of other paths keep images of their own though their previews are alike; two of +/// one path share theirs. +#[test] +fn placed_files_of_other_paths_keep_images_of_their_own() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let object = |path: &str| { + let data = placed(true, "[5 0 0 -5 0 200]", path, Some(&preview), ""); + let find = |s: &[u8]| data.windows(s.len()).position(|w| w == s).unwrap(); + data[find(b"%AI5_BeginPlace")..find(b"%AI5_EndPlace\r") + 14].to_vec() + }; + let mut data = placed(true, "[5 0 0 -5 0 200]", "a.png", Some(&preview), ""); + let end = data.windows(14).position(|w| w == b"%AI5_EndPlace\r").unwrap() + 14; + data.splice(end..end, [object("b.png"), object("a.png")].concat()); + let r = read(&data).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + #[test] fn placed_files_are_linked_images_showing_their_preview() { // A 2×1 preview (premultiplied ARGB, a padded row) of a file of 4×2 pixels. @@ -2417,6 +3131,60 @@ fn legacy_texts(art: &str) -> Vec { art_texts(&doc) } +/// The characters of each text object of a legacy-format file whose setup is `setup` and whose +/// layer holds point type with the string `(chars)` in each font of `fonts`. +fn legacy_chars(setup: &str, fonts: &[&str], chars: &str) -> Vec { + let art: String = fonts.iter().map(|f| point_type("", chars).replace("/_Helvetica 12 Tf", &format!("/{f} 12 Tf"))).collect(); + let data = type_stream7(&art).replace("%%BeginSetup\n%%EndSetup", &format!("%%BeginSetup\n{setup}%%EndSetup")); + let doc = match read(data.as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc).iter().map(|t| t.runs.iter().map(|r| r.text.as_str()).collect()).collect() +} + +/// `TZ` (§3.3.1) gives a re-encoded font encoding pairs of its own: its strings decode by them +/// first, then by `TE`'s encoding when `useDefault` is 1, and other fonts' strings keep `TE`'s. `TZ` is read in an +/// `%AI3_BeginEncoding` section and in an `%%BeginEncoding` one, with a Multiple Master weight +/// vector after it, and without the direction operand. +#[test] +fn a_re_encoded_fonts_own_encoding_pairs_decode_only_its_strings() { + let setup = "[39/quoteright 96/grave 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle 200/eacute\n/_F/F 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %%BeginEncoding: _M M\n[ 39/quotesingle\n/_M/M 0 0 1 [0.5 0.25] TZ\n%%EndEncoding\n\ + %AI3_BeginEncoding: _N N\n[ 39/quotesingle\n/_N/N 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + let got = legacy_chars(setup, &["_F", "_M", "_N", "_G"], "\\047\\140\\200\\310"); + assert_eq!(got, ["'`Äé", "'`ÄÈ", "'`ÄÈ", "’`ÄÈ"]); + // The re-encoded fonts are the fonts they were made from. + let data = type_stream7(&point_type("", "a").replace("/_Helvetica", "/_M")) + .replace("%%BeginSetup\n%%EndSetup", "%%BeginSetup\n%%BeginEncoding: _M Courier\n[/_M/Courier 0 0 1 TZ\n%%EndEncoding\n%%EndSetup"); + let texts = art_texts(&read(data.as_bytes()).unwrap().doc); + assert_eq!(texts[0].runs[0].style.font_family, "Courier"); +} + +/// The reader does not use the pairs of a `TZ` whose font names aren't the last two operands, or +/// are followed by other values. The first `TZ` for a font is used, also when it has no pairs. +#[test] +fn a_tz_of_another_shape_changes_no_encoding() { + let setup = "[39/quoteright\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle\n/_F/F (x) 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _G G\n[ 39/quotesingle\n/_G 0 /G 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _H H\n[ 39/grave\n/_H/H 0 0 1 TZ\n[ 39/quotesingle\n/_H/H 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _K K\n[/_K/K 0 0 1 TZ\n[ 39/quotesingle\n/_K/K 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_G", "_H", "_K"], "\\047"), ["’", "’", "`", "’"]); +} + +/// A `TZ` whose `useDefault` is 0 leaves `TE`'s encoding out for its font (§3.3.1): the codes its +/// pairs leave out decode as Windows-1252. +#[test] +fn a_tz_with_use_default_0_leaves_te_out() { + let setup = "[39/quoteright 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 96/grave\n/_F/F 0 0 0 TZ\n%AI3_EndEncoding TrueType\n\ + %AI3_BeginEncoding: _S S\n[/_S/S 0 0 0 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _M M\n[ 96/grave\n/_M/M 0 0 [0.5] TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_S", "_M", "_G"], "\\047\\140\\200"), ["'`€", "'`€", "'`€", "’`Ä"]); +} + fn art_texts(doc: &Document) -> Vec { art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() } @@ -2481,6 +3249,81 @@ fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { assert_eq!(bad.xf, good.xf); } +/// `(text) justified TS` (special characters, §22.6) adds its characters to the story like `Tx` +/// and `Tj`, whichever its flag. Without a string, or outside a text object, it adds nothing. +#[test] +fn legacy_special_characters_join_the_story() { + let texts = legacy_texts(&point_type("", "One").replace("TO\n", "(\\t) 0 TS\n(Two\\r) 1 TS\n(Three) Tx\nTO\n")); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "One\tTwo\nThree"); + let texts = legacy_texts(&format!("(x) 0 TS\n{}", point_type("0 TS", "Hi"))); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "Hi"); +} + +/// A tab definition (`Xb`, `Xe`, `XB`, §22.6) sets the paragraph's tab stops, sorted by position +/// with one stop at each position; each paragraph keeps the stops in force at its first character, +/// and they last into the next text object. A definition with no stops leaves the default ones. +#[test] +fn legacy_tab_definitions_set_the_paragraph_tab_stops() { + use vectorcraft_doc::TabAlign; + let stops = |p: &vectorcraft_doc::ParaStyle| p.tabs.iter().map(|t| (t.position, t.align)).collect::>(); + let ruler = "36 5 Xb\n0 0 3 144 Xe\n0 0 1 72 Xe\n0 0 2 200.5 Xe\n0 0 4 250 Xe\n0 0 2 72 Xe\nXB"; + let two_paragraphs = point_type(ruler, "A\\tB\\r").replace("TO\n", "36 0 Xb\nXB\n(C\\tD) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "E"))); + assert_eq!(texts.len(), 2); + let want = vec![(72.0, TabAlign::Left), (144.0, TabAlign::Right), (200.5, TabAlign::Center), (250.0, TabAlign::Decimal)]; + let one = texts[0].para_at(0); + assert_eq!(stops(one), want); + assert!(one.tabs.iter().all(|t| t.leader.is_empty() && t.align_on == '.')); + assert!(texts[0].para_at(1).tabs.is_empty(), "an empty definition leaves the default stops"); + assert!(texts[1].para_at(0).tabs.is_empty(), "the next text object keeps the empty definition"); + let texts = legacy_texts(&format!("{}{}", point_type(ruler, "A"), point_type("", "B"))); + assert_eq!(stops(texts[1].para_at(0)), want, "the next text object keeps the stops"); +} + +/// A tab description whose type is not 1 to 4 or whose position is missing, not a number, +/// negative or past 100,000 pt is skipped; so is one outside a tab definition, and an `XB` without +/// an `Xb` leaves the stops as they were. +#[test] +fn legacy_tab_descriptions_out_of_range_are_skipped() { + let bad = "0 0 5 90 Xe\n0 0 0 90 Xe\n0 0 1.5 90 Xe\n0 0 1 -1 Xe\n0 0 1 100001 Xe\n0 0 1 /x Xe\n1 Xe"; + let texts = legacy_texts(&point_type(&format!("0 0 1 10 Xe\n36 2 Xb\n{bad}\n0 0 3 100000 Xe\n0 0 1 0 Xe\nXB\nXB\n0 0 1 50 Xe"), "Hi")); + let tabs: Vec = texts[0].para_at(0).tabs.iter().map(|t| t.position).collect(); + assert_eq!(tabs, [0.0, 100_000.0]); +} + +/// A tab definition whose descriptions were all skipped leaves the default stops; a definition +/// keeps its first 1024 stops; and a definition left open (an `Xb` with no `XB`) ends at the next +/// text object's `To`, so that object's descriptions outside a definition are skipped. +#[test] +fn legacy_tab_definitions_skipped_capped_and_left_open() { + let positions = |t: &vectorcraft_doc::TextObject| t.para_at(0).tabs.iter().map(|t| t.position).collect::>(); + let all_skipped = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe\nXB", "A"), point_type("36 1 Xb\n0 0 9 90 Xe\nXB", "B")); + let texts = legacy_texts(&all_skipped); + assert_eq!(positions(&texts[0]), [72.0]); + assert!(texts[1].para_at(0).tabs.is_empty(), "a definition with every stop skipped leaves the default stops"); + let many: String = (0..1100).map(|i| format!("0 0 1 {i} Xe\n")).collect(); + let texts = legacy_texts(&point_type(&format!("36 1100 Xb\n{many}XB"), "C")); + assert_eq!(positions(&texts[0]).len(), 1024); + assert_eq!(positions(&texts[0]).last(), Some(&1023.0)); + let open = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe", "D"), point_type("0 0 1 90 Xe\nXB", "E")); + let texts = legacy_texts(&open); + assert!(texts[0].para_at(0).tabs.is_empty(), "an unended definition sets no stops"); + assert!(texts[1].para_at(0).tabs.is_empty(), "the next object's `To` ends the open definition"); +} + +/// `Te` (end render, §22.6) reads in a text object with no operands and with four, inside a tab +/// definition too, and keeps nothing; so does `TM` (pop text matrix, §22.6). +#[test] +fn legacy_end_render_and_text_matrix_pop_read() { + for te in ["Te", "0 0 1 36 Te", "36 0 Xb\n0 0 1 36 Te\nXB", "1 0 0 1 10 50 Tm\nTM"] { + let texts = legacy_texts(&point_type(te, "Hi")); + let [t] = texts.as_slice() else { panic!("{te}: {texts:?}") }; + assert_eq!(t.plain_text(), "Hi", "{te}"); + } +} + /// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum /// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges /// `text.setFormat` takes. @@ -2507,6 +3350,361 @@ fn one_long_run_of_legacy_type_stops_at_the_allowance() { assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); } +/// The fill and stroke colors of a text object's first run (None: no paint). +fn run_paint(n: &Node) -> (Option, Option) { + let NodeKind::Text(t) = &n.kind else { panic!("type: {:?}", n.kind) }; + (t.runs[0].style.fill.color(), t.runs[0].style.stroke.color()) +} + +/// Legacy type set in rendering modes 4 to 7 is a mask (§5.7): the text object is the clipping +/// path of its clipping group (`q` … `Q`) and clips the objects with it. Modes 4, 5 and 6 also +/// fill, stroke, or fill and stroke it; 7 paints nothing. +#[test] +fn legacy_type_in_a_mask_rendering_mode_clips_its_clipping_group() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("4", (black, None)), ("5", (None, red)), ("6", (black, red)), ("7", (None, None))]; + for (mode, paint) in cases { + let text = point_type(&format!("{mode} Tr\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{mode} Tr"); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{mode} Tr: {:?}", a[0].kind) }; + assert_eq!(children.len(), 2, "{mode} Tr"); + assert_eq!(run_paint(&children[0]), paint, "{mode} Tr"); + assert!(matches!(children[1].kind, NodeKind::Path { clipping: false, .. }), "{mode} Tr"); + // The art takes its shape from the type: it is bounded by the characters, not the square. + let b = a[0].geometric_bounds().unwrap(); + assert!(b.width() < 50.0 && b.height() < 50.0, "{mode} Tr: {b:?}"); + } + // Directly in a layer, the layer clips. As with a `W` path in this reader, the art written before the + // type is clipped too. + let doc = legacy_read(&format!("{square}{}", point_type("7 Tr", "Hi"))).doc; + let NodeKind::Layer { children, clip: true, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && matches!(children[1].kind, NodeKind::Path { .. })); + // With a clipping path after it, the art shows where both are: the type clips a clipping group nested in it, and + // keeps its paint. + let doc = legacy_read(&format!("q\n{}{}h\nW\nn\n{square}Q\n", point_type("6 Tr\n1 0 0 XA\n1 w", "Hi"), rect_path(0.0, 0.0, 30.0, 30.0))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), (black, red)); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Path { clipping: true, .. }) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. })); +} + +/// A filled clipping path (`W` then `f`) beside type used as a mask: its painted fill stays at its own path's level, +/// as beside another clipping path (the reader's rule for `W` paths). Written after the type, it is painted within the +/// type's mask, since a later mask narrows the clip set by the earlier ones (§5.6.2); written before it, the type doesn't +/// clip it. +#[test] +fn a_filled_clipping_path_beside_legacy_type_used_as_a_mask() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let filled = format!("0 0 1 Xa\n{}h\nW\nf\n", rect_path(0.0, 0.0, 30.0, 30.0)); + let text = point_type("7 Tr", "Hi"); + let is_fill = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: false, .. }) && fill(n).color() == Some(Color::rgb(0.0, 0.0, 1.0)); + let is_art = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: false, .. }) && fill(n).color() == Some(Color::rgb(1.0, 0.0, 0.0)); + // The type first: the path's fill is in the clipping group the path clips, inside the type's. + let doc = legacy_read(&format!("q\n{text}{filled}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && children.len() == 2, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Path { clipping: true, .. }), "{inner:?}"); + assert!(is_fill(&inner[1]) && is_art(&inner[2]) && inner.len() == 3, "{inner:?}"); + // The path first: its fill is in the outer clipping group, which only the path clips; the type clips the art. + let doc = legacy_read(&format!("q\n{filled}{text}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }), "{children:?}"); + assert!(is_fill(&children[1]) && children.len() == 3, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[2].kind else { panic!("{:?}", children[2].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && is_art(&inner[1]) && inner.len() == 2, "{inner:?}"); +} + +/// `Tr` sets the rendering mode of all the type that follows (§15.3.2), in later text objects too: a second text +/// object with no `Tr` of its own is also a mask. +#[test] +fn a_legacy_mask_rendering_mode_lasts_into_the_next_text_object() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let second = point_type("", "Yo").replace("0 Tr\n", ""); + let doc = legacy_read(&format!("q\n{}{second}{square}Q\n", point_type("7 Tr", "Hi"))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)), "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. }), "{inner:?}"); +} + +/// Type in a mask rendering mode that can't be one clipping path doesn't clip, with a warning: area type with linked +/// areas (threaded frames), the type of wraparound text, and type in a compound path. +#[test] +fn legacy_type_used_as_a_mask_that_cannot_clip_is_left_unclipped() { + const WARNING: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let linked = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n7 Tr\n/_Helvetica 12 Tf\n(Linked ) Tx\n1 0 0 1 60 40 0 Tp\n{}n\nTP\n(areas) Tx\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(60.0, 0.0, 110.0, 40.0) + ); + let r = legacy_read(&format!("q\n{linked}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 3); + assert_eq!(r.doc.text_threads.len(), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Also when the reader's limits leave one frame of a long story in linked areas. + let long = linked.replace("(areas) Tx", &format!("({}) Tx", "a".repeat(3_000_000))); + let r = legacy_read(&format!("q\n{long}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 2); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Wraparound text: the type is what flows around the other objects, which it doesn't clip. + let area = format!("1 To\n1 0 0 1 0 0 0 Tp\n{}n\nTP\n7 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Around) Tx\nTO\n", rect_path(0.0, 0.0, 100.0, 80.0)); + let r = legacy_read(&format!("q\n*w\n{area}{square}*W\nQ\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, clip: false } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + assert!(matches!(wrap[0].kind, NodeKind::Text(_)) && wrap.len() == 2, "{wrap:?}"); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // A compound path: its type is no clipping subpath, and the compound path doesn't clip the group. + let r = legacy_read(&format!("q\n*u\n{}f\n{}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0), point_type("7 Tr", "Hi"))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // The same with the type in a group inside the compound path or the wraparound text. + let grouped = format!("u\n{}U\n", point_type("7 Tr", "Hi")); + let r = legacy_read(&format!("q\n*u\n{}f\n{grouped}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + let grouped = format!("u\n{area}U\n"); + let r = legacy_read(&format!("q\n*w\n{grouped}{square}*W\nQ\n")); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // An opacity mask's art clips on its own, also on an object in wraparound text. + let mask_art: String = + format!("{}1 g\n{}f\n", point_type("7 Tr", "Hi"), rect_path(0.0, 0.0, 100.0, 100.0)).lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let r = legacy_read(&format!("q\n*w\n{area}{square}{mask}*W\nQ\n")); + assert!(r.warnings.iter().filter(|w| *w == WARNING).count() == 1, "{:?}", r.warnings); + let a = art(&r.doc); + let NodeKind::Group { children, .. } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + let Some(m) = wrap.iter().find_map(|n| n.extras().mask.clone()) else { panic!("{wrap:?}") }; + let NodeKind::Group { children: in_mask, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + assert!(matches!(in_mask[0].kind, NodeKind::Text(_)) && in_mask.len() == 2, "{in_mask:?}"); +} + +/// The text objects in `nodes` and the groups and compound paths under them, checking that nothing among them clips. +#[track_caller] +fn unclipped_texts(nodes: &[Arc]) -> usize { + let mut texts = 0; + for n in nodes { + assert!(!matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Path { clipping: true, .. }), "{:?}", n.kind); + texts += usize::from(matches!(n.kind, NodeKind::Text(_))); + texts += n.children().map_or(0, |c| unclipped_texts(c)); + } + texts +} + +/// Legacy type in rendering modes 0 to 3 is no mask (3: invisible, painting nothing). A mode that is not a whole +/// number from 0 to 9 leaves the mode as it was. +#[test] +fn legacy_type_in_other_rendering_modes_does_not_clip() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("0 Tr", (black, None)), ("3 Tr", (None, None)), ("1 Tr\n4.5 Tr\n10 Tr\n-4 Tr\n/x Tr", (None, red))]; + for (modes, paint) in cases { + let text = point_type(&format!("{modes}\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{modes}"); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{modes}: {:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), paint, "{modes}"); + } +} + +/// A legacy-format file whose layer holds `art`, read. +fn legacy_read(art: &str) -> Structure { + match read(type_stream7(art).as_bytes()) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } +} + +/// The text objects of the first layer, with their ids, top to bottom: a threaded text object's +/// frames in file order. +fn art_frames(doc: &Document) -> Vec<(vectorcraft_doc::NodeId, vectorcraft_doc::TextObject)> { + art(doc).iter().rev().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((n.id, (**t).clone())) } else { None }).collect() +} + +/// An area's frame in the document. +fn frame_in_doc(t: &vectorcraft_doc::TextObject) -> Rect { + let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type: {:?}", t.kind) }; + kurbo::Shape::bounding_box(&(t.xf * frame.to_bezpath())) +} + +/// Do two matrices match? +fn same_matrix(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// Area type with linked areas (§15.5.3): each area's `Tp` … `TP` with its own matrix and frame, +/// the characters after each, and overflow text. It opens as one frame for each area, threaded in +/// file order, with the story in the first. +#[test] +fn legacy_area_type_with_linked_areas_is_threaded_frames() { + let text = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Linked ) Tx\n\ + 0 1 -1 0 150 20 0 Tp\n{}n\nTP\n(areas\\r) Tx\n(and more) TX\n(\\r) TX\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(110.0, 20.0, 150.0, 80.0) + ); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]], "threaded in file order"); + let in_doc = |x0, y0, x1, y1| r.to_doc.transform_rect_bbox(Rect::new(x0, y0, x1, y1)); + assert!(near(frame_in_doc(first), in_doc(0.0, 0.0, 50.0, 40.0)), "{:?}", frame_in_doc(first)); + assert!(near(frame_in_doc(second), in_doc(110.0, 20.0, 150.0, 80.0)), "{:?}", frame_in_doc(second)); + // Each frame keeps its own area's matrix: the second's type runs up the page. + let placed = |m: [f64; 6]| r.to_doc * Affine::new(m) * Affine::FLIP_Y; + assert!(same_matrix(first.xf, placed([1.0, 0.0, 0.0, 1.0, 0.0, 40.0])), "{:?}", first.xf); + assert!(same_matrix(second.xf, placed([0.0, 1.0, -1.0, 0.0, 150.0, 20.0])), "{:?}", second.xf); + // The story: the characters after every area and the overflow text, in the first frame. + assert_eq!(first.plain_text(), "Linked areas\nand more"); + assert_eq!(first.paragraph_styles().len(), 2); + assert_eq!(second.plain_text(), ""); +} + +/// A linked area without a path is left out; a single area with a path is area type in no thread. +#[test] +fn legacy_area_type_leaves_out_a_linked_area_without_a_path() { + let area = |m: &str, path: Option, chars: &str| { + let path = path.map(|p| format!("{}n\n", rect_path(p.x0, p.y0, p.x1, p.y1))).unwrap_or_default(); + format!("{m} Tp\n{path}TP\n{chars}") + }; + let style = "0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n"; + let three = format!( + "1 To\n{}{}{}TO\n", + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), &format!("{style}(One ) Tx\n")), + area("1 0 0 1 60 40 0", None, "(two ) Tx\n"), + area("1 0 0 1 110 40 0", Some(Rect::new(110.0, 0.0, 150.0, 40.0)), "(three) Tx\n"), + ); + let r = legacy_read(&three); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]]); + assert_eq!((first.plain_text().as_str(), second.plain_text().as_str()), ("One two three", "")); + let one = format!( + "1 To\n{}{}TO\n", + area("1 0 0 1 60 40 0", None, &format!("{style}(x) Tx\n")), + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), "(y) Tx\n") + ); + let r = legacy_read(&one); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one frame: {frames:?}") }; + assert!(r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "xy"); + // The frame's own matrix, not the pathless area's. + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((0.0, 40.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// One text object reads at most 4,096 linked areas: the paths of the rest are left out, not read as +/// art, and their characters stay in the story. +#[test] +fn legacy_area_type_reads_up_to_its_limit_of_linked_areas() { + const LIMIT: usize = 4096; + let area = format!("1 0 0 1 0 0 0 Tp\n{}n\nTP\n", rect_path(0.0, 0.0, 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n(a) Tx\n{area}(b) Tx\nTO\n", area.repeat(LIMIT)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), LIMIT); + assert_eq!(art(&r.doc).len(), LIMIT, "no art paths"); + assert_eq!(r.doc.text_threads.iter().map(Vec::len).collect::>(), [LIMIT]); + assert_eq!(frames[0].1.plain_text(), "ab"); + assert_eq!(r.warnings, [LINKED_AREAS_LEFT_OUT]); +} + +/// The warning when linked areas are left out. +const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out"; + +/// The frames of linked areas times the characters of their story are kept to the reader's +/// allowance of characters: a story of more than half of it gets one frame, and of a third, two. +#[test] +fn legacy_area_type_keeps_its_frames_times_characters_to_the_allowance() { + const ALLOWANCE: usize = 1 << 22; + let area = |x: f64| format!("1 0 0 1 {x} 0 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + for (chars, kept) in [(ALLOWANCE / 2 + 1, 1), (ALLOWANCE / 3, 3), (ALLOWANCE / 3 + 1, 2)] { + let text = format!("1 To\n{}0 Tr\n({}) Tx\n{}{}TO\n", area(0.0), "a".repeat(chars), area(60.0), area(120.0)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), kept, "{chars}"); + assert_eq!(r.doc.text_threads.len(), usize::from(kept > 1), "{chars}"); + assert_eq!(frames[0].1.plain_text().len(), chars); + assert_eq!(r.warnings.iter().any(|w| w == LINKED_AREAS_LEFT_OUT), kept < 3, "{chars}"); + } +} + +/// Point type and type on a path have one text path (§15.2): one with more is read at its first. +#[test] +fn legacy_point_and_path_type_with_several_text_paths_use_the_first() { + let point = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(point); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point) && r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "ab"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "the first text path's matrix: {:?}", only.xf); + let on_path = "2 To\n1 0 0 1 0 0 0.5 Tp\n0 0 m\n100 0 L\nN\nTP\n0 Tr\n(a) Tx\n1 0 0 1 0 0 0 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(on_path); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { path, start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "the first text path's start: {start}"); + let along = kurbo::Shape::bounding_box(&(only.xf * path.to_bezpath())); + assert!((along.y0 - r.to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, 100.0, 0.0)).y0).abs() < 1e-9, "{along:?}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::FLIP_Y), "{:?}", only.xf); + // Type on a path whose first text path has no path: the first one with a path, its matrix and + // start included. + let later = "2 To\n1 0 0 1 30 30 0.25 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 5 0 0.5 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(later); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "{start}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((5.0, 0.0)) * Affine::FLIP_Y), "{:?}", only.xf); + // Area type with no frame at all: point type at its first text path. + let frameless = "1 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(frameless); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point), "{:?}", only.kind); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// The dictionary that follows a threaded text object (version 9 and later): its opacity mask and +/// text wrap go on every frame, and its name on the first frame, which holds the story. +#[test] +fn the_dictionary_after_linked_area_type_applies_to_its_frames() { + let dict = "%_/ArtDictionary :\n%_(Story) /String (AIArtName) ,\n%_12.5 /Real (AI11TextWrapOffset) ,\n\ + %_0 /Bool (AI11TextWrapInvert) ,\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_0 /Bool (Disabled) ,\n%_X=\n\ + %_0 0 0 1 k\n%_0 0 m\n%_5 0 L\n%_5 5 L\n%_0 5 L\n%_0 0 L\n%_f\n%_X+\n%_ (Art) ,\n%_1 /Bool (Clipping) ,\n\ + %_0 /Bool (Inverted) ,\n%_; (AI9_Mask) ,\n%_;\n"; + let area = |x: f64| format!("1 0 0 1 {x} 40 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(a) Tx\n{}{}(b) Tx\nTO\n{dict}", area(0.0), area(60.0), area(120.0)); + let r = read_ok(&layer(&text)); + let ids: Vec<_> = art_frames(&r.doc).into_iter().map(|(id, _)| id).collect(); + assert_eq!(r.doc.text_threads, std::slice::from_ref(&ids), "{:?}", r.warnings); + let nodes: Vec<&Node> = ids.iter().filter_map(|id| r.doc.node(*id)).collect(); + assert_eq!(nodes.len(), 3); + for n in &nodes { + assert!(n.extras().mask.is_some(), "every frame is masked: {:?}", n.id); + assert_eq!(wrap_of(n), Some(vectorcraft_doc::TextWrap { offset: 12.5, invert: false })); + } + let names: Vec<_> = nodes.iter().map(|n| n.name.as_deref()).collect(); + assert_eq!(names, [Some("Story"), None, None]); +} + #[test] fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); @@ -2755,6 +3953,362 @@ fn sections_it_skips() { %_/Document :\n%_/Binary : /ASCII85Decode ,\n%_(]<[%\n%;;;~>\n%_; (Profile) ,\n%_;\n"; let doc = read_ok(&format!("{body}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))).doc; assert_eq!(art(&doc).len(), 1); + // A symbol whose art can't be read isn't kept. + assert!(doc.symbols.is_empty()); +} + +/// Symbol definitions as the editing data writes them, in a section that doesn't print. +fn symbols(defs: &str) -> String { + format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n") +} + +/// A symbol named `name` whose art is `art` (in the symbol's space, y down), with the registration +/// point `registration` (1 to 9 from the top left, row by row). +fn symbol(name: &str, art: &str, registration: u32) -> String { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{registration} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) +} + +/// An instance of the symbol named `name`, `m` taking the symbol's art to art space. +fn instance(name: &str, m: [f64; 6]) -> String { + let [a, b, c, d, e, f] = m; + format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{a} {b} {c} {d} {e} {f} /RTransformMatrix\n;\n") +} + +/// A red square of 4 points about the origin, as a symbol's art. +fn dot() -> String { + format!("{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)) +} + +/// The visual box of `n` in `doc`, its instances measured by their symbols' art. +fn instance_box(doc: &Document, n: &Node) -> Rect { + n.visual_bounds_with(&doc.symbol_boxes()).expect("a box") +} + +#[test] +fn a_symbol_comes_in_once_and_its_instances_stay_live() { + let body = symbols(&symbol("Dot", &dot(), 5)) + + &layer(&(instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]) + &instance("Dot", [2.0, 0.0, 0.0, -2.0, 100.0, 50.0]))); + let mut doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + assert_eq!(doc.symbols[0].name, "Dot"); + assert!(doc.symbol_registration("Dot").is_center()); + let a = art(&doc); + assert_eq!(a.len(), 2); + let xfs: Vec<_> = a + .iter() + .map(|n| if let NodeKind::SymbolInstance { symbol, xf } = &n.kind { (symbol.clone(), *xf) } else { panic!("{:?}", n.kind) }) + .collect(); + assert_eq!(xfs[0].0, "Dot"); + assert_ne!(xfs[0].1, xfs[1].1); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(18.0, 48.0, 22.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(96.0, 46.0, 104.0, 54.0)); + // Editing the symbol's art changes both instances. + let wider = read_ok(&(symbols(&symbol("Dot", &format!("{RED}{}f\n", rect_path(-4.0, -2.0, 4.0, 2.0)), 5)) + &layer(""))).doc; + doc.symbols[0].art = wider.symbols[0].art.clone(); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(16.0, 48.0, 24.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(92.0, 46.0, 108.0, 54.0)); +} + +#[test] +fn an_instance_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). + let nested = instance("Dot", [1.0, 0.0, 0.0, -1.0, -8081.0, 8237.0]); + let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &nested, 1))); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&instance("Pair", [1.0, 0.0, 0.0, -1.0, 50.0, 50.0]))); + let doc = read_ok(&body).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Dot", "Pair"]); + assert_eq!(doc.symbol_registration("Pair"), vectorcraft_doc::SymbolRegistration(0)); + // Dot sits at (10, 5) in Pair's art, which the page instance puts at (50, 50). + let a = art(&doc); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0)); +} + +#[test] +fn an_image_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). The + // image's matrix is in the canvas's space turned y up about that point, as an instance's in a + // symbol's art is: its top left pixel goes to (-5, -2.5) in the symbol's art. + let m = "[ 5 0 0 5 -8096 8244.5 ]"; + let raster = format!( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n{m} 2 1 0 Xh\n{m} 0 0 2 1 2 1 8 3 0 0 1 0 4 4 0 0\n\ + %%BeginData: 6\rXI\nABCDEF%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\n" + ); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Pic", &raster, 5)), layer("")); + let doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + let NodeKind::Image(im) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + for ((u, v), want) in [((0.0, 0.0), (-5.0, -2.5)), ((2.0, 0.0), (5.0, -2.5)), ((0.0, 1.0), (-5.0, 2.5))] { + let got = im.xf * Point::new(u, v); + assert!((got - Point::new(want.0, want.1)).hypot() < 1e-9, "pixel ({u}, {v}): {got:?}, want {want:?}"); + } + // A linked image (`XG` and `XF`) is placed the same way. + let linked = raster7("(a.tif) 0 XG\n", m, (2, 1), "XF", ""); + let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Link", &linked, 5)), layer(""))).doc; + let NodeKind::Image(link) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + assert!(link.link.is_some()); + assert!((link.xf * Point::new(0.0, 0.0) - Point::new(-5.0, -2.5)).hypot() < 1e-9, "{:?}", link.xf); + // Without a template box the image can't be placed, so the symbol isn't read whole: its + // instance comes in as the page draws it. + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Pic", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Pic", &raster, 5)) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_eq!(r.unread.len(), 1, "{:?}", r.warnings); +} + +#[test] +fn an_instance_keeps_its_hide_lock_transparency_and_clip() { + let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]; + let art_ = format!( + "1 Xw\n{}0 Xw\n1 A\n{}0 A\n{}1 0.5 1 1 1 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}{}h\nW\nn\nQ\n0 0.25 0 0 0 Xy\n{}", + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + rect_path(19.0, 49.0, 21.0, 51.0), + instance("Dot", m), + ); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&art_))).doc; + let a = art(&doc); + assert_eq!(a.len(), 5); + assert!(!a[0].visible && !a[0].locked); + assert!(a[1].visible && a[1].locked); + // An instance's transparency is the `Xy` after it, as a group's is; one set before it isn't its. + assert_eq!((a[2].opacity, a[2].blend, a[2].isolate, a[2].knockout, a[2].knockout_shape), (0.5, BlendMode::Multiply, true, Knockout::On, true)); + assert_eq!((a[1].opacity, a[1].blend, a[1].isolate, a[1].knockout), (1.0, BlendMode::Normal, false, Knockout::Neutral)); + assert_eq!((a[3].opacity, a[4].opacity), (0.25, 1.0)); + let NodeKind::Group { children, clip: true } = &a[3].kind else { panic!("a clipping group: {:?}", a[3].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::SymbolInstance { .. })); +} + +/// The art of an opacity mask in a symbol's art takes ids of the document, as the rest of the art +/// does: no two objects of the document, in its layers or its symbols, share an id. +#[test] +fn a_symbols_opacity_mask_art_takes_ids_of_the_document() { + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + if let Some(m) = n.extras().mask.as_ref() { + ids(&m.art, out); + } + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + let mask_art: String = format!("1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let defs = symbols(&symbol("Masked", &format!("{RED}{square}f\n{mask}{}", dot()), 5)); + let shapes: String = (0..6).map(|i| format!("{RED}{}f\n", rect_path(f64::from(i) * 10.0, 0.0, f64::from(i) * 10.0 + 4.0, 4.0))).collect(); + let doc = read_ok(&(defs + &layer(&format!("{shapes}{}", instance("Masked", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))).doc; + let mut all = Vec::new(); + for n in doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art)) { + ids(n, &mut all); + } + assert!(doc.symbols.iter().any(|s| s.art.children().into_iter().flatten().any(|c| c.extras().mask.is_some())), "the mask is read"); + let unique: std::collections::HashSet<_> = all.iter().copied().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +/// A layer's `Xy` right after its last object, an instance, before the layer's `0 0 Xd` and +/// `7 () XW`, is the layer's; the instance's own state block (`6 () XW`) keeps it the instance's. +#[test] +fn a_layers_state_after_its_last_symbol_instance_is_the_layers() { + let last = instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n7 () XW\n")))).doc; + assert_eq!((doc.layers[0].opacity, doc.layers[0].blend), (0.6, BlendMode::Multiply)); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (1.0, BlendMode::Normal)); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n6 () XW\n")))).doc; + assert_eq!(doc.layers[0].opacity, 1.0); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (0.6, BlendMode::Multiply)); +} + +#[test] +fn the_symbol_list_orders_the_symbols_and_names_stay_apart() { + let defs = symbol("A", &dot(), 5) + &symbol("B", &dot(), 5) + &symbol("A", &dot(), 5) + &symbol("C", &dot(), 9); + for list in [ + "%AI24_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI24_EndSymbolList\n", + "%AI10_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI10_EndSymbolList\n", + ] { + let doc = read_ok(&(symbols(&format!("{defs}{list}")) + &layer(&instance("A", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["C", "B", "A", "A 2"], "{list}"); + assert_eq!(doc.symbol_registration("C"), vectorcraft_doc::SymbolRegistration(8)); + // An instance names the first symbol the file gives that name. + assert!(matches!(&art(&doc)[0].kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "A")); + } +} + +/// A symbol whose art is filled with a pattern isn't kept: its instances come in as the page draws +/// them, within the box of its art. The pattern keeps the name it was numbered with. +#[test] +fn a_symbol_with_a_pattern_fill_isnt_kept() { + let pattern = DOTS.replace("(Dots)", "(Red\\n1)"); + let lawn = symbol("Lawn", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&lawn), layer(&instance("Lawn", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Red 2"]); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); + // A pattern chosen and then replaced by a color before the art is painted fills nothing. + let solid = symbol("Solid", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&solid), layer(&instance("Solid", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1); + assert!(r.unread.is_empty()); +} + +#[test] +fn an_instance_of_a_symbol_it_doesnt_have_is_the_unread_object() { + let missing = instance("Absent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + // Alone on the layer, the file isn't read: the page has no box for it. + let e = read(stream(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&missing))).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // In a group, the group is the unread object. + let group = format!("0 Ae\nu\n{missing}{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&group))); + assert_unread(&r, "symbols"); + // Nor is a symbol whose art holds an instance of one the file doesn't have: the page has no box + // for its instances. + let holder = symbol("Holder", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5); + let body = + format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&holder), layer(&instance("Holder", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let e = read(stream(&body).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // An instance whose matrix doesn't have six finite numbers isn't read either. + let bad = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 /RTransformMatrix\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("0 Ae\nu\n{bad}U\n")))); + assert_unread(&r, "symbols"); +} + +#[test] +fn an_instance_whose_appearance_differs_from_its_symbols_comes_in_as_the_page_draws_it() { + let edited = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(edited))); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "the box is the symbol's, placed"); + // The appearance changes are found in a dictionary that an array holds as a value without a key. + let in_array = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n\ + /Array :\n/Dictionary :\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n;\n; (Edits) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(in_array))); + assert_unread(&r, "symbols"); + // So does an instance of a symbol whose art isn't read whole, within that art's box. + let partial = symbol("Partial", &format!("{}f\n1 Xw\n1 2 frobnicate\n0 Xw\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&(symbols(&partial) + &layer(&instance("Partial", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); +} + +/// A symbol whose art holds an image that is left out (no matrix, a matrix with no area, data cut +/// short) isn't kept, so its instances don't draw it without the image. +#[test] +fn a_symbol_with_an_image_it_leaves_out_isnt_kept() { + for (what, image) in [ + ("no matrix", raster7("", "", (1, 1), "XI", "%FF0000\n")), + ("a matrix with no area", raster7("", "[ 0 0 0 0 0 0 ]", (1, 1), "XI", "%FF0000\n")), + ("data cut short", raster7("", "[ 1 0 0 1 0 0 ]", (2, 2), "XI", "%FF0000\n")), + ("no end", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n").replace("%AI5_EndRaster\n", "")), + ("art after a trailer", format!("%%PageTrailer\n{}", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"))), + ] { + // With a template box, so that the image could be placed. + let defs = symbols(&symbol("Photo", &(dot() + &image), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Photo", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&group))); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_eq!(r.unread.len(), 1, "{what}: {:?}", r.warnings); + } +} + +/// A symbol's art written as a group holding one object stays that group when the group is tagged +/// (`XT`), so the tag isn't lost. +#[test] +fn a_symbols_tagged_group_keeps_its_tag() { + let def = format!( + "%AI14_BeginSymbol\n(Tagged)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n/AdobeURL (https://example.com/a) XT\n%_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n", + dot() + ); + let doc = read_ok(&(symbols(&def) + &layer(&instance("Tagged", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let art = &doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{:?}", art.kind); + assert_eq!(tags(art).0, "https://example.com/a"); +} + +/// A definition whose art a trailer stops isn't kept, though the art before the trailer is whole. +#[test] +fn a_symbol_cut_off_by_a_trailer_isnt_kept() { + let cut = format!("%AI14_BeginSymbol\n(Cut)\n0 A\n0 Xw\n0 Ae\n{}%%PageTrailer\n{}%AI10_EndSymbol\n", dot(), dot()); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Cut", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&cut) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); +} + +/// A symbol whose art holds type, a placed file, non-native art, an image it can't place or a +/// gradient the file doesn't define isn't kept. Its instances come in as the page draws them, within the box of the rest of its art, an +/// instance right on a layer as well as one in a group. +#[test] +fn a_symbols_art_it_leaves_out_gives_its_instances_the_box_of_the_rest() { + let typed = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n".to_string(); + let placed = "%AI5_BeginPlace\n%AI5_EndPlace\n".to_string(); + let foreign = + "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%1H@\n;\n" + .to_string(); + let image = raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"); + let gradient = format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(-2.0, -2.0, 2.0, 2.0)); + let template = "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n"; + for (what, left, head) in [ + ("type", typed, template), + ("a placed file", placed, template), + ("non-native art", foreign, template), + ("an image without a template box", image, ""), + ("a gradient the file doesn't define", gradient, template), + ] { + let defs = symbols(&symbol("Mixed", &(dot() + &left), 5)); + let body = format!("{head}{defs}{}", layer(&instance("Mixed", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read(stream(&body).as_bytes()).unwrap_or_else(|e| panic!("{what}: {e}")); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "{what}"); + } + // A gradient the file doesn't define on a path that isn't painted paints nothing. + // Nor does one on a path that a group's start drops, for the paths after it. + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + for (what, unpainted) in [ + ("not painted", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}n\n0 BB\n")), + ("dropped", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}0 BB\nu\n{square}f\nU\n")), + ] { + let defs = symbols(&symbol("Kept", &(dot() + &unpainted), 5)); + let r = read_ok(&format!("{template}{defs}{}", layer(&instance("Kept", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1, "{what}: {:?}", r.warnings); + assert!(r.unread.is_empty(), "{what}"); + } +} + +#[test] +fn symbols_that_hold_each_other_lose_the_instances_that_close_the_loop() { + let m = [1.0, 0.0, 0.0, -1.0, 0.0, 0.0]; + let defs = symbols(&(symbol("S1", &instance("S2", m), 5) + &symbol("S2", &instance("S1", m), 5))); + let r = + read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&(dot() + &instance("S1", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))); + assert!(r.warnings.contains(&vectorcraft_doc::depth::symbols_note()), "{:?}", r.warnings); + assert!(!r.doc.clone().limit_depth(), "nothing is left that draws itself"); +} + +/// A definition after the first layer isn't read: the symbols were checked before that layer, and +/// one read later could hold an instance of a symbol the file doesn't have. +#[test] +fn a_symbol_defined_after_the_first_layer_is_not_read() { + let late = symbols(&symbol("Late", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Late", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{late}{}", layer(&dot()), layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); } /// A filled square at x = `10 × i` (5 pt wide), to tell the alternatives of versioned content apart. @@ -3160,7 +4714,7 @@ fn artboards_after_what_stops_the_reading() { let array = format!("%_/Array :\n{}{}%_; (ArtboardArray) ,\n", board("one", 0), board("two", 200)); // Art in the document's own data that the reader can't follow comes before the artboards. let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n%_/Dictionary :\nLB\n{array}%_; /NotRecorded ,\n%_;\n"); - let boards: Vec<_> = super::artboards(data.as_bytes()).into_iter().map(|(n, r)| (n, r.x0)).collect(); + let boards: Vec<_> = super::artboards(data.as_bytes()).0.into_iter().map(|(n, r)| (n, r.x0)).collect(); assert_eq!(boards, [("one".to_string(), 0.0), ("two".to_string(), 200.0)]); } @@ -3375,6 +4929,35 @@ fn a_style_name_outside_ascii_links_its_objects() { assert_eq!(art(&r.doc)[0].extras().graphic_style, Some(1)); } +#[test] +fn an_object_in_a_symbols_art_with_a_listed_style_is_linked() { + let defs = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + let body = + format!("{defs}{}{}", symbols(&symbol("Tile", &styled_square("Blue"), 5)), layer(&instance("Tile", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read_ok(&body); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let tile = &r.doc.symbols[0].art; + assert!(matches!(tile.kind, NodeKind::Path { .. }), "{tile:#?}"); + assert_eq!(fill(tile).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(tile.extras().graphic_style, Some(1), "{tile:#?}"); + // A symbol's art written as a group holding one object stays that group when the group is + // linked to the style. + let empty = "/KnownStyle :\n(Empty) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n"; + let defs = styles_and_list(&[empty.to_string()], &["Empty"]); + let square = rect_path(0.0, 0.0, 10.0, 10.0); + let hidden = square.replace('\n', "\n%_"); + // The styled group is the definition's own group, without one around it. + let group = format!( + "%AI14_BeginSymbol\n(Group)\n0 A\n0 Xw\n0 Ae\nu\n{RED}{square}f\nU\n%_u\n%_{hidden}f\n%_U\n1 (Empty) XW\n\ + %_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n%AI10_EndSymbol\n" + ); + let body = format!("{defs}{}{}", symbols(&group), layer(&instance("Group", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let art = &read_ok(&body).doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{art:#?}"); + assert_eq!(art.extras().graphic_style, Some(1), "{art:#?}"); +} + #[test] fn without_a_style_list_the_default_graphic_styles_stay() { let defaults = style_names(&Document::new(1.0, 1.0)); @@ -3561,6 +5144,206 @@ fn an_object_with_path_effects_comes_in_as_itself_with_them_live() { assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// The paint of a blue fill in a style. +const BLUE_FILL: Option<&str> = Some("0 0 0 0 0 0 1 Xa\n"); + +/// An art style section with style `Bent`: effect `name` with dictionary `keys` on the whole +/// object, over a fill painting with `paint`, or over a fill and stroke that paint nothing. +fn distort_styles(name: &str, keys: &str, paint: Option<&str>) -> String { + let (paints, color) = match paint { + Some(p) => ("0 1", p), + None => ("0 0", ""), + }; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Bent) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{color}{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// Free Distort's 16 entries for a 40 × 30 pt object whose source frame is its own box, with its +/// destination corners `dst` (top left, top right, bottom left, bottom right, art space). +fn free_distort_keys(dst: [[f64; 2]; 4]) -> String { + let src = [[20.0, 50.0], [60.0, 50.0], [20.0, 20.0], [60.0, 20.0]]; + let mut out = String::new(); + for (which, c) in [("src", src), ("dst", dst)] { + for (i, [h, v]) in c.into_iter().enumerate() { + out += &format!("{h} /Real ({which}{i}h) ,\n{v} /Real ({which}{i}v) ,\n"); + } + } + out +} + +#[test] +fn an_object_with_a_distort_effect_that_draws_alike_comes_in_as_itself_with_it_live() { + // GUARDS: only type took Distort & Transform effects; a path with Transform, Twist, a still Tweak, + // Pucker & Bloat at 0 or an affine Free Distort came in as its drawn look. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + // A slanted box: its corners make a parallelogram. + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys, id) in [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n", "distort.transform"), + ("Adobe Twirl", "45 /Real (angle) ,\n", "distort.twist"), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n0 /Bool (anch) ,\n0 /Bool (in) ,\n0 /Bool (out) ,\n", "distort.tweak"), + ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n", "distort.puckerBloat"), + ("Adobe Free Distort", slanted.as_str(), "distort.freeDistort"), + ("Adobe Free Distort", "", "distort.freeDistort"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{name}: the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (40.0, 30.0), "{name}: the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0)), "{name}"); + let ids: Vec<_> = a[0].appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, [id], "{name}"); + } +} + +#[test] +fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() { + // Pucker & Bloat and Zig Zag draw other outlines than the file's, a Free Distort whose corners + // aren't a parallelogram bends the curves differently, and Transform's copies paint as one path. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + let bent = free_distort_keys([[25.0, 50.0], [65.0, 52.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys) in [ + ("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n"), + ("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n"), + ("Adobe Free Distort", bent.as_str()), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n"), + ("Adobe Transform", "1 /Bool (randomize) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n2 /Int (numCopies) ,\n0 /Bool (transformPatterns) ,\n"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } +} + +/// The gradient `G`, white to black, defined for a document. +const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + +#[test] +fn an_object_whose_outline_moves_away_from_its_gradient_keeps_its_drawn_look() { + // GUARDS: a gradient stays where it is placed while Transform, Twist or Free Distort moves the + // outline, so the live object lost the gradient its drawn look shows. + let gradient = Some("Bb\n0 0 0 0 Bh\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n"); + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let object = format!( + "0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_1 (G) 20 35 0 40 1 0 0 1 0 0 Bg\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0) + ); + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + let shaded = format!("Bb\n1 (G) 5 5 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(5.0, 0.0, 15.0, 10.0)).replace('\n', "\n%_"); + let group = format!("0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{shaded}U\n1 (Bent) XW\n", rect_path(0.0, 0.0, 15.0, 10.0), hidden(RED, 0.0)); + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + let moves = [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Twirl", "45 /Real (angle) ,\n"), + ("Adobe Free Distort", slanted.as_str()), + ]; + for (name, keys) in moves { + // A gradient in the style, and one on a member of a group. + for (paint, art_) in [(gradient, &object), (None, &group)] { + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles(name, keys, paint), layer(art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } + } + // An effect that leaves the outline where it is keeps the gradient under it. + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles("Adobe Punk and Bloat", "", gradient), layer(&object))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{a:#?}"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + +/// A group with style `Bent`, its drawn look one path, holding a red and a blue square. +fn distort_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (Bent) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_transform_keeps_its_members_and_the_effect() { + // GUARDS: the group came in as its drawn look, one path with no effect. + let keys = "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"; + let r = read_ok(&format!("{}{}", distort_styles("Adobe Transform", keys, None), layer(&distort_group()))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["moveH"].as_f64()), ("distort.transform", Some(5.0))); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); +} + +/// `styles` (from [`distort_styles`]) with a red stroke 2 pt wide in place of the stroke that +/// paints nothing. +fn with_red_stroke(styles: &str) -> String { + styles.replace("/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd", "/StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd") +} + +#[test] +fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { + // GUARDS: Twist was read on curves, strokes and groups, and Transform scaling a stroked object, + // where the outline VectorCraft draws hasn't been checked. + let object = |hidden: &str| { + format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) + }; + let square = object(&rect_path(20.0, 20.0, 60.0, 50.0)); + let curved = object("20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"); + let twist = distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", BLUE_FILL); + let scale = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; + let corner = distort_styles("Adobe Transform", &format!("0 /Int (pinPoint) ,\n{scale}"), BLUE_FILL); + let center = distort_styles("Adobe Transform", scale, BLUE_FILL); + let moved = distort_styles("Adobe Transform", "0 /Int (pinPoint) ,\n5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n", BLUE_FILL); + let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); + for (what, r) in [ + ("a twisted curve", read(&twist, &curved)), + ("a twisted stroke", read(&with_red_stroke(&twist), &square)), + ("a twisted group", read(&distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", None), &distort_group())), + ("a stroke scaled from a corner", read(&with_red_stroke(&corner), &square)), + ("a stroke scaled from the center", read(&with_red_stroke(¢er), &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } + for (what, r) in [ + ("a twisted square", read(&twist, &square)), + ("a stroke moved from a corner", read(&with_red_stroke(&moved), &square)), + ("a fill scaled from a corner", read(&corner, &square)), + ("a fill scaled from the center", read(¢er, &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }) && a[0].appearance.effects.len() == 1, "{what}: {a:#?}"); + } + let r = read(&twist, &square); + let a = art(&r.doc); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["angle"].as_f64()), ("distort.twist", Some(45.0))); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. @@ -4512,6 +6295,15 @@ fn a_blend_comes_in_as_a_live_blend() { assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); } +/// The tags after a blend's drawn steps are the live blend's. +#[test] +fn a_live_blend_keeps_the_tags_of_its_drawn_steps() { + let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])); + let (blend, warnings) = read_blend(&body.replace("\nU\n9 () XW\n0 Ae\n", "\nU\n/sku (B-1) XT\n9 () XW\n0 Ae\n")); + assert!(matches!(blend.kind, NodeKind::Blend { .. }), "a live blend: {:?} {warnings:?}", blend.kind); + assert_eq!(tags(&blend).1, [tag("sku", "B-1")]); +} + /// A spine written from the right key to the left one keeps the keys in their order on it (the /// red key first), sitting on its last and first anchors. #[test] @@ -5212,6 +7004,41 @@ fn a_brushs_art_takes_the_patterns_defined_before_it() { assert!(matches!(fill(&s.art), Paint::Pattern { ref pattern, .. } if pattern == "Dots"), "{:?}", r.warnings); } +/// A brush's art filled with a pattern defined in the version 7 form places the tiles with the +/// fill's offset, scale, rotation, reflection and shear operands, and a brush whose art has such a +/// fill without all nine of them isn't read. +#[test] +fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { + let def = pattern7("Grid", "(0 g) @ _ &\n"); + let read_with = |ops: &str| { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n(Grid) {ops} p\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + read_ok(&format!("{def}{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))) + }; + let placed = |ops: &str| { + let r = read_with(ops); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + match fill(&s.art) { + Paint::Pattern { xf, .. } => xf, + p => panic!("{ops}: {p:?} {:?}", r.warnings), + } + }; + let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); + // The operands and the move they make from the plain placement (a b c d e f): those of + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the + // art's space has it. + let cases = [ + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ]; + for (ops, want) in cases { + let got = (placed(ops) * plain.inverse()).as_coeffs(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops}: {got:?}"); + } + let r = read_with("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"); + assert!(!vectorcraft_brush::library(&r.doc).iter().any(|b| b.name == "Spray"), "{:?}", r.warnings); +} + /// A file without brush objects keeps the default brushes. #[test] fn a_file_without_brushes_keeps_the_default_ones() { @@ -5274,6 +7101,107 @@ fn a_gradients_br_is_not_a_brush() { assert_eq!(g.gradient.stops.len(), 2); } +/// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation +/// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, +/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't +/// read: it varies at random, as an unknown code does. +#[test] +fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + let modes = |params: &str| { + let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); + let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; + c.modes.unwrap() + }; + assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); + assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); + assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); +} + +/// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and +/// angle -150 to 210 with the barrel's rotation. +const SIX_D: &str = "1 4 8 30 50 -150 210 2 5 6 0"; + +/// The style `Inked`: a stroke in red of weight `weight` with the Calligraphic brush `brush` at +/// diameter, roundness and angle `settings` (each its value and variation either side), varying by +/// the codes `codes`, its angle relative to `relative` (0 the page). +fn brushed_style(brush: &str, weight: f64, settings: [(f64, f64); 3], codes: [u8; 3], relative: u8) -> String { + let [(d, dv), (r, rv), (a, av)] = settings; + let [dm, rm, am] = codes; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Inked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({CALLIGRAPHIC}) 1 0 /Filter ,\n1 /Visible ,\n(Calligraphic Brush) /Title ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j {weight} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + {d} /Real (Diameter) ,\n{dv} /Real (DiameterVariation) ,\n{dm} /Int (DiameterDependsOn) ,\n\ + {r} /Real (Roundness) ,\n{rv} /Real (RoundnessVariation) ,\n{rm} /Int (RoundnessDependsOn) ,\n\ + {a} /Real (Angle) ,\n{av} /Real (AngleVariation) ,\n{am} /Int (AngleDependsOn) ,\n{relative} /Int (AngleRelativeTo) ,\n\ + ({brush}) /UnicodeString (DisplayString) ,\n/GObjRef : ({brush}) ({CALLIGRAPHIC}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n0 0 0 0 k\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// The settings [`SIX_D`] has, as an art style writes them. +const SIX_D_SETTINGS: [(f64, f64); 3] = [(6.0, 2.0), (40.0, 10.0), (30.0, 180.0)]; + +/// A brushed path as the file writes it: its drawn look (a filled outline) in a group, then the +/// path itself on `%_` lines, unpainted, with the style `Inked`. +fn brushed_path() -> String { + let line = "20 20 m\n100 60 L\n"; + format!("0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{}n\n1 (Inked) XW\n", rect_path(20.0, 18.0, 100.0, 62.0), line.replace('\n', "\n%_")) +} + +/// A path drawn with a Calligraphic brush comes in as the path, its stroke in that brush at its +/// weight (the weight scales the brush), not as its drawn look: here a 6D Art Pen brush, whose +/// channels the brush keeps (#372). +#[test] +fn a_path_with_a_calligraphic_brush_comes_in_brushed() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let style = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [2, 5, 6], 0); + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, not its look: {a:#?}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width, st.paint.color()), (Some("Six D"), 0.5, Some(Color::rgb(1.0, 0.0, 0.0)))); + assert!(a[0].appearance.fill().is_none_or(|f| f.paint.is_none()), "{:?}", a[0].appearance); + use vectorcraft_brush::{BrushKind, Variation}; + let lib = vectorcraft_brush::library(&r.doc); + let BrushKind::Calligraphic(c) = brush_named(&lib, "Six D") else { panic!("calligraphic") }; + assert_eq!(c.modes, Some([Variation::Rotation, Variation::Bearing, Variation::Pressure])); + // With no pen recorded on the path, the nib is the brush's own at the stroke's weight. + let pieces = vectorcraft_brush::stroke_pieces(&r.doc, &lib[0], &a[0].path_data().unwrap().to_bezpath(), st); + let height = pieces.iter().filter_map(|n| n.geometric_bounds()).map(|b| b.height()).fold(0.0, f64::max); + assert!(height > 40.0 && height < 46.0, "the line's rise and about half the nib's 3 pt: {height}"); +} + +/// A brushed path keeps its drawn look when its stroke can't be read as the brush: the object's +/// own settings differ from the brush's (Options of Selected Object), its angle follows the path, +/// or the file defines no brush of its name. +#[test] +fn a_brushed_path_the_brush_cant_draw_keeps_its_drawn_look() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let mut own = SIX_D_SETTINGS; + own[0] = (9.0, 2.0); + let cases = [ + ("its own settings", def.clone(), brushed_style("Six D", 1.0, own, [2, 5, 6], 0)), + ("its own modes", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 4], 0)), + ("an angle on the path", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 6], 1)), + ("no such brush", def, brushed_style("Other", 1.0, SIX_D_SETTINGS, [2, 5, 6], 0)), + ]; + for (why, def, style) in cases { + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; /// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index cb4c2594b5..ac5f38d6b8 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -396,6 +396,9 @@ pub(super) struct Texts { /// The document's character styles (`[Normal Character Style]` first), each a name, the /// character style it is based on (key 5, an index into these) and its attributes (key 6). char_sheets: Vec, + /// The document's paragraph styles (`[Normal Paragraph Style]` first), each a name, its + /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). + para_sheets: Vec, frames: Vec, } @@ -434,21 +437,17 @@ impl Texts { .map(|f| f.get("0").and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::str).unwrap_or_default().to_string()) .collect(); let main = doc.get("1")?; + let sheets = |key: &str| -> Vec { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; Some(Texts { stories: main.get("1")?.list().to_vec(), fonts, defaults: main.get("2")?.clone(), para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), - char_sheets: doc - .get("0")? - .get("5") - .and_then(|s| s.get("0")) - .map(Val::list) - .unwrap_or_default() - .iter() - .take(MAX_SHEETS) - .map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))) - .collect(), + char_sheets: sheets("5"), + para_sheets: sheets("6"), frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), }) } @@ -541,8 +540,10 @@ impl Texts { let mut paras = vec![]; for run in s.get("0")?.get("5").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { let n = run.get("1").and_then(Val::num)? as usize; - let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("5")); - paras.push((n, self.para(props))); + paras.push((n, self.para(run.get("0").and_then(|r| r.get("0"))))); + } + if paras.is_empty() { + paras.push((text.chars().count(), self.para(None))); } let mut runs = vec![]; for run in s.get("0")?.get("6").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { @@ -555,9 +556,19 @@ impl Texts { Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical }) } - /// A paragraph's attributes: its own keys, else the document's. - fn para(&self, p: Option<&Val>) -> Para { - let pick = |k: &str| p.and_then(|p| p.get(k)).or_else(|| self.para_defaults.get(k)); + /// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based + /// on, key 6): its own keys, else those of its paragraph style and the ones that is based on, + /// else those of `[Normal Paragraph Style]`, else the document's. + fn para(&self, run: Option<&Val>) -> Para { + let mut chain = vec![]; + let mut at = run; + for _ in 0..=MAX_SHEETS_BASED_ON { + let Some(style) = at else { break }; + chain.extend(style.get("5")); + at = style.get("6").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.para_sheets.get(i as usize)); + } + chain.extend(self.para_sheets.first().and_then(|s| s.get("5"))); + let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.para_defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num).filter(|v| v.abs() < 1e5).unwrap_or(0.0); Para { justify: pick("0").and_then(Val::num).map_or(0, |v| v.clamp(0.0, 6.0) as u8), @@ -573,7 +584,7 @@ impl Texts { /// A run's character style (`run`: its attributes, key 6, and the character style it is based /// on, key 5): its own keys, else those of its character style and the ones that is based on, - /// else the document's. + /// else those of `[Normal Character Style]`, else the document's. fn style(&self, run: Option<&Val>) -> Style { // The run's attributes, then its character style's, then the styles each is based on. let mut chain = vec![]; @@ -583,6 +594,7 @@ impl Texts { chain.extend(style.get("6")); at = style.get("5").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.char_sheets.get(i as usize)); } + chain.extend(self.char_sheets.first().and_then(|s| s.get("6"))); let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); @@ -1074,9 +1086,10 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], + para_sheets: vec![], frames: vec![], }; - let justify = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).justify; + let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; // Right to left from the document's defaults, or the paragraph's own. assert_eq!(justify(b"/0 0"), Justify::Right); assert_eq!(justify(b"/0 1 /33 1"), Justify::Left); @@ -1096,6 +1109,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![], } .para(None); @@ -1142,6 +1156,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: cases.iter().map(|c| frame(c)).collect(), }; let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); @@ -1157,13 +1172,14 @@ mod tests { fonts: vec![], defaults: read(b"/35 1").unwrap(), para_defaults: Val::Dict(BTreeMap::new()), - char_sheets: vec![read(b"/0 (Block) /6 << /35 3 >>").unwrap()], + char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], + para_sheets: vec![], frames: vec![], }; let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; assert!(tcy(b"/6 << /35 3 >>"), "the run's own"); - assert!(tcy(b"/5 0 /6 << >>"), "its character style's"); - assert!(!tcy(b"/5 0 /6 << /35 1 >>"), "the run's own wins"); + assert!(tcy(b"/5 1 /6 << >>"), "its character style's"); + assert!(!tcy(b"/5 1 /6 << /35 1 >>"), "the run's own wins"); for other in [&b"/6 << >>"[..], b"/6 << /35 2 >>", b"/6 << /35 3.5 >>", b"/6 << /35 (3) >>", b"/6 << /35 -3 >>", b"/6 << /35 1e308 >>"] { assert!(!tcy(other), "{}", String::from_utf8_lossy(other)); } @@ -1180,9 +1196,10 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], + para_sheets: vec![], frames: vec![], }; - let direction = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).direction; + let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; assert_eq!(direction(b"/0 2"), Some(ParaDirection::RightToLeft), "from the document's defaults"); assert_eq!(direction(b"/0 2 /33 0"), None, "the paragraph's own"); let plain = Texts { para_defaults: Val::Dict(BTreeMap::new()), ..texts }; @@ -1221,6 +1238,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0) @@ -1520,6 +1538,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0).unwrap() diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1498c730a0..698201be55 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -94,7 +94,7 @@ pub(super) type Built = Result<(Document, Vec), String>; /// `structure` (the editing copy `data` read) with nothing compared with the pages, when the file's /// text document makes the type of every text object (at least one shows, and none is type that a /// look draws), no object is unread or has another placement or drawn art that the page would -/// choose, and its artboards are the pages, one for one and of their size, in points or in the pages' +/// choose, no linked image shows a placeholder, and its artboards are the pages, one for one and of their size, in points or in the pages' /// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for /// [`build_from`] with the page. pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { @@ -116,9 +116,11 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6 /// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its /// place), no placed file with another placement, no live envelope with the drawn art it replaced -/// (the comparison with the page chooses between them)? +/// (the comparison with the page chooses between them), no linked image showing a placeholder +/// where the page has its pixels? fn nothing_waits_on_page(structure: &Structure) -> bool { - structure.unread.is_empty() + structure.placeholders.is_empty() + && structure.unread.is_empty() && structure.unread_elsewhere.is_empty() && structure.placed_elsewhere.is_empty() && structure.envelopes_drawn.is_empty() @@ -168,6 +170,16 @@ fn page_scale_alone(structure: &Structure, pages: &[(f64, f64)], unit: f64) -> O [1.0, unit].into_iter().find(|&k| k.is_finite() && k >= 1.0 && fits(k)) } +/// The areas left out of the comparisons with `page`: the `restyled` looks', and on a PostScript +/// page, which draws nothing for them, the linked images' `placeholders`. A PDF part draws those +/// images' pixels, which the placeholders don't match. +fn left_out_of_comparisons(page: Page, mut restyled: Vec, placeholders: Vec) -> Vec { + if matches!(page, Page::Art) { + restyled.extend(placeholders); + } + restyled +} + /// [`build`] from `structure`, the editing copy `data` already read. pub(super) fn build_from( structure: Structure, @@ -189,6 +201,7 @@ pub(super) fn build_from( unread_elsewhere, slot_names, restyled, + placeholders, placed_elsewhere, envelopes_drawn, styles_read, @@ -198,6 +211,7 @@ pub(super) fn build_from( bindings_skipped, warnings, } = structure; + let restyled = left_out_of_comparisons(page, restyled, placeholders); // Editing data in the units of the page's user space ([`in_units`]), or at its declared large // canvas scale ([`page_scale`]), is compared with the page scaled down to those units, and the // document read from it is scaled up by `unit`. @@ -317,6 +331,7 @@ pub(super) fn build_from( // Its page is the file's own (its bounding box), as when it comes in as its page: art // reaching past the editing data's artboard stays on it (#1102). doc.artboards.truncate(1); + doc.opened_artboard = None; if let Some(a) = doc.artboards.first_mut() { a.rect = rect; } @@ -1600,6 +1615,19 @@ mod candidate_tests { assert_eq!(more_pages(Some(&tiny_boards), &tiny, 1).len() + 1, MAX_PAGES_COMPARED); } + /// A linked image showing a placeholder (`XF`) waits on the page, whose PDF part draws its + /// pixels: the layers aren't used without it. + #[test] + fn a_linked_image_placeholder_waits_on_the_page() { + let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[ 1 0 0 1 0 4 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n%AI5_EndRaster\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{raster}LB\n%AI5_EndLayer--\n%%Trailer\n" + ); + let structure = ai::read(data.as_bytes(), false).unwrap(); + assert_eq!(structure.placeholders.len(), 1); + assert!(!nothing_waits_on_page(&structure)); + } + /// The pages a box touches with a margin round it include those it only comes near. #[test] fn the_pages_within_reach_of_a_box_count_as_touched() { diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 26cca96c0f..f355093cef 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -7,8 +7,8 @@ use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect /// hidden ones too), groups, compound paths, clipping groups and artboards, with the text and the /// strokes around it of the page. When the file has no editing copy, `visible` as it was; when it /// has one that can't be used, `visible` with a warning that says why, with the swatches of the -/// editing copy's palette ([`use_palette`]) and its variable library ([`use_variables`]) when it -/// could be read, and with its layer tree, empty, +/// editing copy's palette ([`use_palette`]), its graphic styles ([`use_styles`]) and its variable +/// library ([`use_variables`]) when it could be read, and with its layer tree, empty, /// below the page's layer when that could be read (#2033). A program in the legacy format without /// layers (`illustrator`, see [`program_alone`]) is read with its art on one layer; when that /// can't be used, the file is `visible` as it was. @@ -40,6 +40,7 @@ pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool, illus let have = v.document.patterns.len(); use_palette(data, &mut v.document); use_brushes(data, &mut v.document, have, &mut v.warnings); + use_styles(data, &mut v.document, true, 1.0, None); use_variables(data, &mut v.document, &mut v.warnings); } if tree.is_empty() { @@ -99,11 +100,11 @@ fn layer_tree(nodes: &[Arc]) -> Vec> { /// notes, or a note saying why the layers weren't read when the editing data can't be decompressed /// or its layers can't be read. The flag returned is `true` when the document is the one read from /// the layers; else the document is `visible`, its pages moved by `place_pages` when the editing -/// data was decompressed but its layers can't be read, and its swatches, brushes and variables those -/// of the editing data's palette ([`use_palette`]), brushes ([`use_brushes`]) and variable library -/// ([`use_variables`]) when it was -/// decompressed. `outlined`: the PDF part's type was read as -/// outlines (a file whose type shows then comes in as its PDF part). +/// data was decompressed but its layers can't be read, and its swatches, brushes, graphic styles and +/// variables those of the editing data's palette ([`use_palette`]), brushes ([`use_brushes`]), styles +/// ([`use_styles`]) and variable library ([`use_variables`]) when it was decompressed: a graphic +/// style library, which has no layers, opens with its styles. `outlined`: the PDF part's type was +/// read as outlines (a file whose type shows then comes in as its PDF part). /// `trust`: layers that draw differently from the PDF part are used all the same, with a warning. /// `unit`: the size in points of a unit of the PDF part's user space, its first page's `UserUnit`, /// by which its art came in scaled. Editing data whose artboard matches the page only in those @@ -136,16 +137,19 @@ pub fn layered_ai_from( let have = visible.patterns.len(); use_palette(&data, &mut visible); use_brushes(&data, &mut visible, have, &mut warnings); + use_styles(&data, &mut visible, false, unit, None); use_variables(&data, &mut visible, &mut warnings); return (visible, warnings, false); } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { - place_pages(&ai::artboards(&data), &mut visible, unit); + let (boards, active) = ai::artboards(&data); + place_pages(&boards, active, &mut visible, unit); let have = visible.patterns.len(); use_palette(&data, &mut visible); use_brushes(&data, &mut visible, have, &mut warnings); + use_styles(&data, &mut visible, false, unit, Some(&boards)); let mut all = unread(warnings, why); use_variables(&data, &mut visible, &mut all); (visible, all, false) @@ -275,32 +279,75 @@ fn use_brushes(data: &[u8], doc: &mut Document, have: usize, warnings: &mut Vec< warnings.extend(note.filter(|n| !warnings.contains(n))); } -/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as -/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on -/// each, to where they are, so the artboards keep their names and layout when the layers can't be -/// read (#1068). Left as they are unless there are as many artboards as pages, each the size of its -/// page in points, or, when `unit` is above 1, each the size of its page in units of `unit` points: -/// then the layout is drawn `unit` times as large. -fn place_pages(boards: &[(String, Rect)], doc: &mut Document, unit: f64) { - if boards.is_empty() || boards.len() != doc.artboards.len() { +/// `doc` (a file read as its page or PDF part, in place of its layers) with the graphic styles of +/// its editing data `data` in place of the default ones, as [`build`] gives a document read from +/// the layers ([`ai::graphic_styles`], `large_canvas` as it takes it). Unless `large_canvas` is set, +/// their strokes and effects are drawn `unit` times as large when the editing data's artboards are +/// the size of `doc`'s pages in units of `unit` points, else as many times as large as the data's +/// declared large canvas scale when they are the pages' size at that scale ([`board_scale`]). +/// `boards`: the editing data's artboards when they were already read. Left as it is when the +/// editing data has no style this reads. +fn use_styles(data: &[u8], doc: &mut Document, large_canvas: bool, unit: f64, boards: Option<&[(String, Rect)]>) { + let (mut styles, canvas) = ai::graphic_styles(data, large_canvas); + if styles.is_empty() { return; } + if !large_canvas && (unit != 1.0 || canvas != 1.0) { + let read; + let boards = match boards { + Some(b) => b, + None => { + read = ai::artboards(data).0; + &read + } + }; + let k = board_scale(boards, doc, unit).or_else(|| board_scale(boards, doc, canvas)); + if let Some(k) = k.filter(|k| *k != 1.0) { + for g in &mut styles { + g.appearance.scale_strokes(k); + g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + } + } + doc.graphic_styles = styles.into(); +} + +/// How many points a unit of `boards` (the artboards of a file's editing data, in art space) is in +/// `doc` (the file read as its PDF part: a page per artboard): 1 when there are as many artboards as +/// pages, each the size of its page in points, or `unit` when `unit` is above 1 and each is the size +/// of its page in units of `unit` points. `None` otherwise. +fn board_scale(boards: &[(String, Rect)], doc: &Document, unit: f64) -> Option { + if boards.is_empty() || boards.len() != doc.artboards.len() { + return None; + } let differ = |k: f64| { boards .iter() .zip(&doc.artboards) .any(|((_, b), a)| (b.width() - a.rect.width() / k).abs() > 0.5 || (b.height() - a.rect.height() / k).abs() > 0.5) }; - let k = if !differ(1.0) { - 1.0 + if !differ(1.0) { + Some(1.0) } else if unit.is_finite() && unit > 1.0 && !differ(unit) { - unit + Some(unit) } else { - return; - }; + None + } +} + +/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as +/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on +/// each, to where they are, so the artboards keep their names and layout when the layers can't be +/// read (#1068); the page of the artboard at `active` (the active one) is the active artboard. Left +/// as they are unless there are as many artboards as pages, each the size of its page in points, +/// or, when `unit` is above 1, each the size of its page in units of `unit` points: then the layout +/// is drawn `unit` times as large. +fn place_pages(boards: &[(String, Rect)], active: Option, doc: &mut Document, unit: f64) { + let Some(k) = board_scale(boards, doc, unit) else { return }; for ((name, _), a) in boards.iter().zip(&mut doc.artboards) { a.name.clone_from(name); } + doc.opened_artboard = active.filter(|i| *i > 0).and_then(|i| doc.artboards.get(i)).map(|a| a.id); let [(_, first), _, ..] = boards else { return }; // Art space (y up) → the document, the first artboard's top left at the origin, as `read` has it, // `k` points a unit. diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index d4ae4db83e..b896063aac 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -209,14 +209,14 @@ fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() { } /// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and -/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`XB` (a tab definition) and `Th` -/// (hyphen control). These keep no geometry, so the reader drops them rather than failing the -/// file the way it did before — the symptom seen on Illustrator 6/8 EPS files whose -/// `Adobe_level2_AI5` program can't be run. +/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition) and `Th` +/// (hyphen control). The reader drops `XL` and keeps the tab definition as the paragraph's tab +/// stops rather than failing the file the way it did before (the symptom seen on Illustrator 6/8 +/// EPS files whose `Adobe_level2_AI5` program can't be run). #[test] fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\ - %_ 0 XL\n36 0 Xb\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n"; + %_ 0 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n"; // The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped // on a hidden one), beside the square so the layer is never empty. let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer")); @@ -234,6 +234,8 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let [p] = texts.as_slice() else { panic!("{texts:?}") }; assert!(!p.hyphenate); assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25)); + let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect(); + assert_eq!(tabs, [(72.0, vectorcraft_doc::TabAlign::Right)]); } /// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036): @@ -350,6 +352,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings); } +/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then +/// `XF` with no samples) comes in through its layers, the image as a linked image of that file +/// showing a placeholder where the matrix puts the image. +#[test] +fn a_legacy_file_with_a_linked_image_comes_in_through_its_layers() { + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ + /XG {pop pop} def /XF {13 {pop} repeat} def"; + let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[2 0 0 3 20 80] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n"; + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{}\n{raster}LB\n%AI5_EndLayer--\n", tri(10)); + let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog")); + let r = import(file.as_bytes()).unwrap(); + assert!(!r.preview); + let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Back"], "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert_eq!(art.len(), 2, "{:?}", r.warnings); + let NodeKind::Image(im) = &art[1].kind else { panic!("{:?}", art[1].kind) }; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("photo.tif")); + // The image's 10 × 20 pixels from (20, 80) in art space, 2 and 3 points each: 20 20 40 80 on + // the page, y down. + assert_eq!((im.width, im.height), (10, 20)); + let (top_left, bottom_right) = (im.xf * Point::ZERO, im.xf * Point::new(10.0, 20.0)); + assert!( + (top_left - Point::new(20.0, 20.0)).hypot() < 0.01 && (bottom_right - Point::new(40.0, 80.0)).hypot() < 0.01, + "{top_left:?} {bottom_right:?}" + ); + assert!(r.warnings.iter().any(|w| w.contains("show a placeholder")), "{:?}", r.warnings); +} + /// A file in the legacy format without layers (Illustrator 3) whose prolog is included: its prolog, /// a setup, and `art`. fn layerless(art: &str) -> Vec { @@ -417,6 +448,47 @@ fn a_version_7_palette_keeps_its_swatches_without_names() { assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white"); } +/// A gradient's name in the file is shown up to its newline (the AI7 spec's §4): two gradients +/// named `Sky` apart from what follows the newline come in as swatches "Sky" and "Sky 2", and each +/// object keeps its own gradient, linked to its own swatch. A palette swatch that has the name +/// "Sky" of its own keeps it, and the gradients take the next free names. +#[test] +fn gradient_names_are_shown_up_to_their_newline() { + let gradient = |name: &str, gray: f64| { + format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_{gray} 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n") + }; + let cell = |name: &str| format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n"); + let fill = |name: &str, x: u32| format!("Bb\n1 ({name}) 0 0 0 100 1 0 0 1 0 0 Bg\n{}\n0 BB\n", tri(x)); + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n(Art) Ln\n0 A\n0 Xw\n{}{}LB\n%AI5_EndLayer--\n", + fill("Sky\\n2", 10), + fill("Sky\\n1", 30) + ); + let first_stop = |p: &Paint| match p { + Paint::Gradient(g) => (g.swatch.clone(), g.gradient.stops.first().map(|s| s.color)), + _ => panic!("{p:?}"), + }; + for (own, first, second) in [("", "Sky", "Sky 2"), ("0 1 1 0 (Sky) 0 x\nPc\n", "Sky 2", "Sky 3")] { + let setup = format!( + "{}{}%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n{own}{}{}PB\n%AI5_EndPalette\n", + gradient("Sky\\n1", 1.0), + gradient("Sky\\n2", 0.5), + cell("Sky\\n1"), + cell("Sky\\n2") + ); + let r = import(&stream7(&setup, &body)).unwrap(); + let d = &r.document; + let names: Vec<&str> = d.swatches.iter().map(|s| s.name.as_str()).collect(); + let expected: Vec<&str> = ["[None]"].into_iter().chain((!own.is_empty()).then_some("Sky")).chain([first, second]).collect(); + assert_eq!(names, expected, "{:?}", r.warnings); + assert_eq!(first_stop(&d.swatch(first).unwrap().paint), (Some(first.into()), Some(Color::gray(0.0)))); + assert_eq!(first_stop(&d.swatch(second).unwrap().paint), (Some(second.into()), Some(Color::gray(0.5)))); + let art = d.layers[0].children().unwrap(); + let fills: Vec<_> = art.iter().map(|n| first_stop(&n.appearance.fill().unwrap().paint)).collect(); + assert_eq!(fills, [(Some(second.into()), Some(Color::gray(0.5))), (Some(first.into()), Some(Color::gray(0.0)))]); + } +} + /// A version 8 file's paths keep their notes and Show Center. #[test] fn a_legacy_files_paths_keep_their_notes_and_show_center() { @@ -433,6 +505,26 @@ fn a_legacy_files_paths_keep_their_notes_and_show_center() { assert!(kids[0].shows_center() && !kids[1].shows_center()); } +/// A version 8 file's object tags open as each object's URL and data. +#[test] +fn a_legacy_files_object_tags_open_as_urls_and_data() { + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Tags) Ln\n0 A\n0 0 0 1 k\n{}\n/AdobeURL (https://example.com) XT\n/sku (B-7) XT\n\ + u\n{}\nU\n/part () XT\nLB\n%AI5_EndLayer--\n", + tri(10), + tri(40) + ); + let r = import(&ai(AI8, "", &body)).unwrap(); + let kids = r.document.layers[0].children().unwrap(); + let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone()))).collect(); + assert_eq!( + attrs, + [Some(("https://example.com".into(), vec![("sku".into(), "B-7".into())])), Some((String::new(), vec![("part".into(), String::new())]))], + "{:?}", + r.warnings + ); +} + #[test] fn unbalanced_and_runaway_groups_are_read_safely() { // Ends without a beginning end nothing; groups left open hold the rest. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index a571774262..33b467bee6 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -419,6 +419,18 @@ fn group_with_only_placed_file_without_preview_uses_page_art() { assert!(notes.iter().any(|n| n.contains("placed files (1)")), "{notes:?}"); } +/// A linked image whose pixels the editing data doesn't keep (`XF`) shows a placeholder where the +/// PDF part draws the image: the layers are compared with the PDF part there, and the file comes in +/// as its PDF part when they differ. +#[test] +fn a_linked_image_without_pixels_is_compared_with_the_pdf_part() { + let linked = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[ 10 0 0 10 50 54 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n%AI5_EndRaster"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Linked", true, linked))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); +} + #[test] fn top_level_pattern_uses_page_art_beside_live_path() { let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}\n{}", square_path(50, 10), square(70, 10)); @@ -1366,6 +1378,114 @@ fn an_ai_brush_library_without_layers_keeps_its_brushes() { assert!(d.pattern("Dots").is_some_and(|p| !p.art.is_empty()), "the pattern the brush's art paints with"); } +/// An art style that strokes with black at `width` units, after the effects `effects` (filters as +/// the format writes them), as the format writes it. +fn stroke_art_style(name: &str, width: f64, effects: &str) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{effects}\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n" + ) +} + +/// The art styles and the style list of a graphic style library: Thin, Medium and Thick, listed in +/// that order, 1, 2 and 3 units wide, Medium after an Offset Path of 4 units, and Unlisted, which +/// the list leaves out, with Thin listed twice. +fn style_list() -> String { + let offset = "/BasicFilter :\n(Adobe Offset Path) 1 0 /Filter ,\n1 /Visible ,\n(OffsetPath.aip) /PluginFileName ,\n(Offset Path) /Title ,\n\ + /Dictionary : /NotRecorded ,\n4 /Real (ofst) ,\n6 /Real (mlim) ,\n1 /Int (jntp) ,\n; /Dict ;\n /Part ,\n"; + format!( + "%AI9_BeginArtStyles\n{}{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Thin)\n(Medium)\n(Thick)\n(Thin)\n%AI9_EndArtStyleList\n", + stroke_art_style("Thick", 3.0, ""), + stroke_art_style("Unlisted", 4.0, ""), + stroke_art_style("Thin", 1.0, ""), + stroke_art_style("Medium", 2.0, offset) + ) +} + +/// The offset of each Offset Path in the graphic styles of `d`. +fn style_offsets(d: &Document) -> Vec { + let effects = d.graphic_styles.iter().flat_map(|g| &g.appearance.effects); + effects.filter(|e| e.id == "path.offsetPath").filter_map(|e| e.params["offset"].as_f64()).collect() +} + +/// A graphic style library (the art styles and list of [`style_list`], and no layers) with the +/// editing data's setup `setup` before them. +fn style_library(setup: &str) -> String { + let styles = style_list(); + format!("%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%BeginSetup\n{setup}{styles}%%EndSetup\n%%PageTrailer\n%%Trailer\n") +} + +/// A graphic style library (art styles and their list, no layers) comes in as its PDF part with the +/// library's graphic styles in place of the default ones, in the list's order: Other Library lists them. +#[test] +fn an_ai_graphic_style_library_without_layers_keeps_its_styles() { + let (d, warnings, read) = crate::layered_ai(&private(&style_library("")), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + let styles: Vec<(&str, u32, f64)> = d.graphic_styles.iter().map(|g| (g.name.as_str(), g.id, g.appearance.stroke_width())).collect(); + assert_eq!(styles, [("Thin", 1, 1.0), ("Medium", 2, 2.0), ("Thick", 3, 3.0)], "{warnings:?}"); + assert_eq!(style_offsets(&d), [4.0]); + assert!(warnings.is_empty(), "{warnings:?}"); + // Without a style list, the default styles stay. + let (d, warnings, _) = crate::layered_ai(&private(&native("")), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert_eq!(d.graphic_styles, Document::new(1.0, 1.0).graphic_styles, "{warnings:?}"); +} + +/// A graphic style library whose artboard is its page in the units of a `UserUnit` of 10 comes in +/// with its styles' stroke weights and effects ten times as large, as the page's art is; one whose +/// artboard is the page in points keeps them. Without a `UserUnit`, a Large Canvas library whose +/// artboard is the page at its declared scale of 10 comes in with them ten times as large too. +#[test] +fn an_ai_graphic_style_library_in_the_units_of_a_user_unit_page_comes_in_at_the_pages_size() { + let board = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let widths = |d: &Document| d.graphic_styles.iter().map(|g| g.appearance.stroke_width()).collect::>(); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, read) = crate::layered_ai(&private(&style_library(board)), page, vec![], false, true, 10.0); + assert!(!read, "{warnings:?}"); + assert_eq!(widths(&d), [10.0, 20.0, 30.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [40.0]); + let points = board.replace("0 100 /Real", "0 1000 /Real").replace("100 0 /Real", "1000 0 /Real"); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, _) = crate::layered_ai(&private(&style_library(&points)), page, vec![], false, true, 10.0); + assert_eq!(widths(&d), [1.0, 2.0, 3.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [4.0]); + let large = format!("%AI24_LargeCanvasScale: 10\n{board}"); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, _) = crate::layered_ai(&private(&style_library(&large)), page, vec![], false, true, 1.0); + assert_eq!(widths(&d), [10.0, 20.0, 30.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [40.0]); +} + +/// An EPS whose editing copy has graphic styles and no layers comes in as its page with those +/// styles, at the page's size when the copy is a Large Canvas one. +#[test] +fn an_eps_without_layers_keeps_its_graphic_styles() { + let r = import(&eps(&page_square(50, 50), &style_library(""))).unwrap(); + let names: Vec<&str> = r.document.graphic_styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Thin", "Medium", "Thick"], "{:?}", r.warnings); + let r = import(&eps(&page_square(50, 50), &style_library("%AI24_LargeCanvasScale: 10\n"))).unwrap(); + let widths: Vec = r.document.graphic_styles.iter().map(|g| g.appearance.stroke_width()).collect(); + assert_eq!(widths, [10.0, 20.0, 30.0], "{:?}", r.warnings); + assert_eq!(style_offsets(&r.document), [40.0]); +} + +/// A `.ai` that comes in as its PDF part, and an EPS that comes in as its page, because their +/// layers can't be used (their editing data is for another page) get the graphic styles of their +/// editing data's style list in place of the default ones. +#[test] +fn a_file_whose_layers_cant_be_used_keeps_its_graphic_styles() { + let art = native(&format!("{}{}", style_list(), layer("Art", true, &square(10, 10)))).replace(" 0 0 100 100", " 0 0 600 400"); + let names = |d: &Document| d.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let (d, warnings, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(!read && warnings.iter().any(|w| w.contains("600 × 400")), "{warnings:?}"); + assert_eq!(names(&d), ["Thin", "Medium", "Thick"], "{warnings:?}"); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("600 × 400")), "{:?}", r.warnings); + assert_eq!(names(&r.document), ["Thin", "Medium", "Thick"], "{:?}", r.warnings); +} + /// A PDF part whose tiling has the name of a pattern its editing data defines (the PDF part names /// its tilings `Pattern 1`, `Pattern 2` and so on): the editing data's pattern comes in under a free /// variant of the name, and the palette's swatch and the brush's art paint with it, not with the @@ -2165,6 +2285,56 @@ fn an_ai_file_read_as_its_pdf_part_keeps_its_artboard_layout() { assert!((moved[1] - vectorcraft_geom::Point::new(100.0, 1600.0)).hypot() < 1e-6, "the second's art goes with its page: {moved:?}"); } +/// A `.ai` read as its PDF part opens on the page of the artboard its editing data names as the +/// active one (`CropAreaActive`), also when the reading stops before the artboards. +#[test] +fn an_ai_file_read_as_its_pdf_part_keeps_its_active_artboard() { + let board = |x0: i32| { + format!( + "%_/Dictionary :\n%_{x0} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x0 + 100 + ) + }; + // `before` in the document's data, before the artboards; an operator this doesn't know, so the + // layers aren't read. + let unread = |before: &str, active: &str| { + let boards = format!( + "%_/Document :\n%_/Dictionary :\n{before}%_/Array :\n{}{}%_; (ArtboardArray) ,\n{active}%_; /NotRecorded ,\n%_;\n", + board(0), + board(120) + ); + native(&(boards + &layer("Art", true, &(square(10, 10) + "\n1 Zz")))) + }; + let mut pdf = pdf_part(10.0, 10.0); + let mut page = pdf.artboards[0].clone(); + (page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(page); + let opened = |before: &str, active: &str| { + let (d, w, read) = crate::layered_ai(&private(&unread(before, active)), pdf.clone(), vec![], false, false, 1.0); + assert!(!read && w.iter().any(|w| w.contains("layers weren't read")), "{w:?}"); + d.opened_artboard + }; + let stops = "%_/Array :\n%_/Dictionary :\nLB\n"; + // Another entry, a dictionary of its own, between the array and the entry. + let between = "%_/Dictionary :\n%_1 /Int (Other) ,\n%_; (Inner) ,\n%_1 /Int (CropAreaActive) ,\n"; + for before in ["", stops] { + assert_eq!(opened(before, "%_1 /Int (CropAreaActive) ,\n"), Some(2), "{before}"); + assert_eq!(opened(before, between), Some(2), "{before}"); + assert_eq!(opened(before, "%_0 /Int (CropAreaActive) ,\n"), None, "{before}"); + assert_eq!(opened(before, ""), None, "{before}"); + // A `CropAreaActive` of a dictionary inside the holder is not the holder's. + assert_eq!(opened(before, "%_/Dictionary :\n%_1 /Int (CropAreaActive) ,\n%_; (Inner) ,\n"), None, "{before}"); + } + // The entry before the array, after what stops the reading. + assert_eq!(opened(&format!("{stops}%_; ,\n%_; (Art) ,\n%_1 /Int (CropAreaActive) ,\n"), ""), Some(2)); + // What stops the reading between the array and the entry. + assert_eq!(opened("", "%_/Dictionary :\nLB\n%_; (Inner) ,\n%_1 /Int (CropAreaActive) ,\n"), Some(2)); + // Lines ended by carriage returns. + let (d, ..) = + crate::layered_ai(&private(&unread(stops, "%_1 /Int (CropAreaActive) ,\n").replace('\n', "\r")), pdf.clone(), vec![], false, false, 1.0); + assert_eq!(d.opened_artboard, Some(2)); +} + #[test] fn art_moved_with_its_page_moves_its_pattern_tile() { // Two 100-point artboards, the second 50 below the first; an operator this doesn't know, so @@ -2358,6 +2528,53 @@ fn type_from_the_text_document_takes_its_character_styles_attributes() { assert_eq!(style(2), (solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Some(18.0)), "the run's own colour"); } +/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character +/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large +/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point +/// indent) and the base attributes at the page's, so the type comes in at 12 points with a 6-point +/// indent. +#[test] +fn a_story_without_runs_takes_the_normal_styles() { + let own_style = "/5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >>"; + let doc = text_document(&[("Plain\r", 0, (8191.5, 8191.5), (0.0, 0.0), 0.0), ("Runs\r", 0, (8191.5, 8190.5), (0.0, -1.0), 0.0)]) + // The first story has no runs. + .replacen(&format!("/6 << /0 [ << /0 << /0 << /0 () {own_style} >> >> /1 6 >> ] >> "), "", 1) + .replacen("/5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 6 >> ] >> ", "", 1) + // The second story's runs name no style. + .replacen(own_style, "/6 << /0 0 >>", 1) + .replacen("/5 << /0 0 >> /6 0", "/5 << /0 0 >>", 1) + // The document's base attributes: 12 points, white, a 60-point indent, hyphenated. + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 60.0 /9 true >>", 1) + // The normal styles: 1.2 art units, blue; a 0.6 art unit indent, not hyphenated. + .replacen( + "/0 << /1 <<", + "/0 << /5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 1.2 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >> \ + /6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 0.6 /9 false >> >> >> ] >> /1 <<", + 1, + ); + assert!(!doc.contains("/1 14.0") && !doc.contains("/6 0 "), "{doc}"); + // A 10 × 10 unit copy of the page's 100 × 100 points, its template box centered at (5, 5). + let art = native_with_text( + &(layer("Back", true, "0 0 1 0 k\n5 5 m\n5.4 5 L\n5.4 5.4 L\n5 5.4 L\nf") + &layer("Spare", false, &(text_object(0) + &text_object(1)))), + &doc, + ) + .replace("0 0 100 100", "0 0 10 10") + .replace("%AI3_TemplateBox: 50 50 50 50\n", "%AI3_TemplateBox: 5 5 5 5\n%AI24_LargeCanvasScale: 10\n"); + let r = import(&eps(&page_square(50, 50), &art)).unwrap(); + assert_eq!(names(&r.document), ["Back", "Spare"], "{:?}", r.warnings); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.iter().map(|t| t.plain_text()).collect::>(), ["Plain", "Runs"], "{:?}", r.warnings); + let [.., e, f] = texts[0].xf.as_coeffs(); + assert!((e - 50.0).abs() < 1e-6 && (f - 50.0).abs() < 1e-6, "{:?}", texts[0].xf); + for t in texts { + let style = &t.runs[0].style; + assert!((style.size - 12.0).abs() < 1e-9, "{}: {}", t.plain_text(), style.size); + assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "{}", t.plain_text()); + assert!((t.para.first_line_indent - 6.0).abs() < 1e-9 && !t.para.hyphenate, "{}: {:?}", t.plain_text(), t.para); + } +} + #[test] fn type_from_the_text_document_keeps_its_case_setting() { // Key 12 of a character style is its case: 1 Small Caps, 2 All Caps. The characters stay as diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index b1847d9ce3..59a8f30660 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -547,17 +547,38 @@ impl PathData { /// Tight geometric bounds (curve extrema, not control points), measured by [`curve_bounds`]: a /// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured /// by its control points. + /// + /// Walks the segments in place, without building the path: the same segments in the same order, + /// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with + /// no segment, is `Rect::ZERO`, as there). pub fn bounds(&self) -> Option { if self.is_empty() { return None; } - let bp = self.to_bezpath(); if self.anchor_count() == 1 && let Some(a) = self.subpaths.iter().find_map(|s| s.anchors.first()) { return Some(Rect::from_points(a.p, a.p)); } - Some(curve_bounds(&bp)) + let mut bbox: Option = None; + for sp in &self.subpaths { + for i in 0..sp.segment_count() { + let c = sp.segment(i); + // `to_bezpath_into` writes a line where neither handle is out, else a cubic. + let seg = segment_bounds(if sp.segment_is_line(i) { PathSeg::Line(kurbo::Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) }); + bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); + } + // A closed subpath's last segment ends on its first anchor, so its `ClosePath` adds no + // line, unless that anchor is NaN: it then differs from itself, and kurbo closes with one. + if sp.closed + && let Some(a) = sp.anchors.first() + && (a.p.x.is_nan() || a.p.y.is_nan()) + { + let seg = segment_bounds(PathSeg::Line(kurbo::Line::new(a.p, a.p))); + bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); + } + } + Some(bbox.unwrap_or_default()) } /// Bounds including control handles (used for quick culling). pub fn control_bounds(&self) -> Option { @@ -720,6 +741,48 @@ fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: P mod tests { use super::*; + /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, + /// for lines, curves, open and closed subpaths, lone anchors and empty subpaths. + #[test] + fn bounds_match_the_bezpath_bit_for_bit() { + use proptest::prelude::*; + fn reference(pd: &PathData) -> Option { + if pd.is_empty() { + return None; + } + if pd.anchor_count() == 1 { + let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?; + return Some(Rect::from_points(a.p, a.p)); + } + Some(curve_bounds(&pd.to_bezpath())) + } + let bits = |r: Option| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits)); + let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)]; + let pt = move || (coord(), coord()).prop_map(|(x, y)| Point::new(x, y)); + // Handles retracted (equal to the anchor) a third of the time: lines and curves mix. + let handle = move || prop_oneof![Just(None), pt().prop_map(Some)]; + let anchor = + (pt(), handle(), handle()).prop_map(|(p, i, o)| Anchor { p, h_in: i.unwrap_or(p), h_out: o.unwrap_or(p), kind: AnchorKind::Corner }); + let sub = (proptest::collection::vec(anchor, 0..6), any::()).prop_map(|(a, c)| SubPath::new(a, c)); + let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); + proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { + prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + }); + // Two lone anchors: no segment, as the path has none. + let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); + assert_eq!(lone.bounds(), Some(Rect::ZERO)); + assert_eq!(bits(lone.bounds()), bits(reference(&lone))); + // A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own. + let nan = Point::new(f64::NAN, 1.0); + let closed = |pts: &[Point]| SubPath::polyline(pts, true); + for pd in [ + PathData::new(vec![closed(&[nan]), closed(&[Point::new(5.0, 5.0)])]), + PathData::new(vec![closed(&[nan, Point::new(3.0, 4.0), Point::new(6.0, 1.0)])]), + ] { + assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + } + } + fn square() -> PathData { PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)) } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 2747fdf45a..d66ab38606 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,15 +103,44 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// 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")] +pub enum EllipseMode { + /// Closed sector through the centre (pie slice). + #[default] + Slice, + /// Open arc curve without closing segments. + Arc, + /// Closed arc with a straight chord connecting the end back to the start. + Chord, + /// Whole closed shape (ignores start/end cut). + Whole, +} + /// The ellipse inscribed in `r` cut as a pie: from `start` to `end` degrees, measured /// counterclockwise on screen from 3 o'clock (as Illustrator's Pie Start and End Angle are), then /// back through the centre. A pie spanning the whole turn (or nothing) is the whole [`ellipse`]. /// The arc is one cubic per quarter turn at most: the centre, then the arc's anchors. pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { - let span = (end - start).rem_euclid(360.0); - if !(start.is_finite() && end.is_finite()) || span < 1e-9 || 360.0 - span < 1e-9 { + ellipse_arc(r, start, end, EllipseMode::Slice) +} + +/// The ellipse inscribed in `r` cut from `start` to `end` degrees according to `mode`: +/// - [`EllipseMode::Slice`]: closed through the centre (pie chart). +/// - [`EllipseMode::Chord`]: closed with a straight chord between the endpoints. +/// - [`EllipseMode::Arc`]: open elliptical arc (no centre lines, `closed = false`). +/// - [`EllipseMode::Whole`]: full closed [`ellipse`]. +pub fn ellipse_arc(r: Rect, start: f64, end: f64, mode: EllipseMode) -> PathData { + if mode == EllipseMode::Whole || !(start.is_finite() && end.is_finite()) { return ellipse(r); } + let raw_span = (end - start).rem_euclid(360.0); + let full = raw_span < 1e-9 || 360.0 - raw_span < 1e-9; + if full && mode != EllipseMode::Arc { + return ellipse(r); + } + let span = if full { 360.0 } else { raw_span }; let r = r.abs(); let c = r.center(); let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); @@ -135,7 +164,10 @@ pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { }; let step = span / f64::from(pieces); let k = 4.0 / 3.0 * (step.to_radians() / 4.0).tan(); - let mut anchors = vec![Anchor::corner(c)]; + let mut anchors = Vec::with_capacity(pieces as usize + 2); + if mode == EllipseMode::Slice { + anchors.push(Anchor::corner(c)); + } for i in 0..=pieces { let a = start + step * f64::from(i); let (p, d) = (at(a), tangent(a) * k); @@ -144,6 +176,123 @@ pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth }; anchors.push(Anchor { p, h_in, h_out, kind }); } + let closed = mode != EllipseMode::Arc; + PathData::single(SubPath::new(anchors, closed)) +} + +/// Cut or open any closed single-subpath `path` around `center` from `start_deg` to `end_deg` +/// according to `mode` ([`EllipseMode::Slice`], [`EllipseMode::Arc`], [`EllipseMode::Chord`], +/// [`EllipseMode::Whole`]). +pub fn apply_shape_arc(path: PathData, center: Point, start_deg: f64, end_deg: f64, mode: EllipseMode) -> PathData { + use kurbo::{BezPath, ParamCurve}; + if mode == EllipseMode::Whole || !(start_deg.is_finite() && end_deg.is_finite()) { + return path; + } + let Some(sp) = path.subpaths.first() else { + return path; + }; + let n = sp.segment_count(); + if !sp.closed || n == 0 { + return path; + } + let raw_span = (end_deg - start_deg).rem_euclid(360.0); + let full = raw_span < 1e-9 || 360.0 - raw_span < 1e-9; + if full { + if mode == EllipseMode::Arc { + let mut open_sp = sp.clone(); + open_sp.closed = false; + return PathData::single(open_sp); + } + return path; + } + let u0 = start_deg.rem_euclid(360.0) / 360.0; + let du = (raw_span / 360.0).clamp(1e-6, 1.0 - 1e-6); + let s0 = u0 * (n as f64); + let s1 = (u0 + du) * (n as f64); + let k0 = (s0.floor() as usize).min(n.saturating_sub(1)); + let t0 = (s0 - k0 as f64).clamp(0.0, 1.0); + let k1 = s1.floor() as usize; + let t1 = (s1 - k1 as f64).clamp(0.0, 1.0); + let mut cubics = Vec::new(); + if k0 == k1 { + if t1 > t0 + 1e-9 { + cubics.push(sp.segment(k0 % n).subsegment(t0..t1)); + } + } else { + if t0 < 1.0 - 1e-9 { + cubics.push(sp.segment(k0 % n).subsegment(t0..1.0)); + } + for k in (k0 + 1)..k1 { + cubics.push(sp.segment(k % n)); + } + if t1 > 1e-9 { + cubics.push(sp.segment(k1 % n).subsegment(0.0..t1)); + } + } + let Some(first) = cubics.first() else { + return path; + }; + let mut bp = BezPath::new(); + if mode == EllipseMode::Slice { + bp.move_to(center); + bp.line_to(first.p0); + } else { + bp.move_to(first.p0); + } + for c in &cubics { + if c.p0.distance(c.p1) <= 1e-9 && c.p3.distance(c.p2) <= 1e-9 { + bp.line_to(c.p3); + } else { + bp.curve_to(c.p1, c.p2, c.p3); + } + } + if mode != EllipseMode::Arc { + bp.close_path(); + } + PathData::from_bezpath(&bp) +} + +/// Deterministic vertex jitter for `randomized` polygons and stars (`(dr, da)` in `[-1, 1]`). +fn vertex_jitter(index: u32, total: u32) -> (f64, f64) { + let mut s = 0x9e37_79b9_7f4a_7c15_u64 + .wrapping_add((u64::from(index) + 1).wrapping_mul(0xbf58_476d_1ce4_e5b9)) + .wrapping_add(u64::from(total).wrapping_mul(0x94d0_49bb_1331_11eb)); + let mut next = || { + s ^= s >> 12; + s ^= s << 25; + s ^= s >> 27; + let v = s.wrapping_mul(0x2545_f491_4f6c_dd1d); + ((v >> 11) as f64 / ((1u64 << 53) as f64)) * 2.0 - 1.0 + }; + (next(), next()) +} + +/// Build a closed subpath from polygon/star vertices with optional smooth bezier `rounded` +/// tangents (`-10..=10`). +fn contour_with_rounding(pts: &[Point], rounded: f64) -> PathData { + let n = pts.len(); + if n == 0 || !rounded.is_finite() || rounded.abs() < 1e-9 { + return PathData::single(SubPath::polyline(pts, true)); + } + let r_factor = rounded.clamp(-10.0, 10.0) * 0.4; + let mut anchors = Vec::with_capacity(n); + for i in 0..n { + let p_prev = pts[(i + n - 1) % n]; + let p = pts[i]; + let p_next = pts[(i + 1) % n]; + let v_in = p - p_prev; + let v_out = p_next - p; + let len_in = v_in.hypot(); + let len_out = v_out.hypot(); + let u_in = if len_in > 1e-9 { v_in / len_in } else { Vec2::ZERO }; + let u_out = if len_out > 1e-9 { v_out / len_out } else { Vec2::ZERO }; + let sum = u_in + u_out; + let sum_len = sum.hypot(); + let tangent = if sum_len > 1e-9 { sum / sum_len } else { Vec2::new(-u_in.y, u_in.x) }; + let h_in = p - tangent * (len_in * r_factor); + let h_out = p + tangent * (len_out * r_factor); + anchors.push(Anchor { p, h_in, h_out, kind: AnchorKind::Smooth }); + } PathData::single(SubPath::new(anchors, true)) } @@ -160,6 +309,26 @@ pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> Pat PathData::single(SubPath::polyline(&pts, true)) } +/// Regular polygon with `sides` (≥ 3), bezier tangent `rounded` factor and deterministic +/// `randomized` vertex jitter. +pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg: f64, rounded: f64, randomized: f64) -> PathData { + if (!rounded.is_finite() || rounded.abs() < 1e-9) && (!randomized.is_finite() || randomized.abs() < 1e-9) { + return polygon(center, radius, sides.clamp(3, 1000), rotation_deg); + } + let n = sides.clamp(3, 1000); + let rot = if rotation_deg.is_finite() { rotation_deg.to_radians() } else { 0.0 }; + let rand_amt = if randomized.is_finite() { randomized.clamp(0.0, 10.0) } else { 0.0 }; + let pts: Vec = (0..n) + .map(|i| { + let (dr, da) = if rand_amt > 1e-9 { vertex_jitter(i, n) } else { (0.0, 0.0) }; + let r = (radius * (1.0 + rand_amt * 0.45 * dr)).max(0.01); + let a = -PI / 2.0 + rot + TAU * (i as f64 / n as f64) + rand_amt * (PI / n as f64) * da; + Point::new(center.x + r * a.cos(), center.y + r * a.sin()) + }) + .collect(); + contour_with_rounding(&pts, rounded) +} + /// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up. pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData { let n = points.max(2) * 2; @@ -174,6 +343,27 @@ pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData::single(SubPath::polyline(&pts, true)) } +/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, bezier tangent `rounded` +/// factor and deterministic `randomized` vertex jitter. +pub fn star_configured(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64, rounded: f64, randomized: f64) -> PathData { + if (!rounded.is_finite() || rounded.abs() < 1e-9) && (!randomized.is_finite() || randomized.abs() < 1e-9) { + return star(center, r1, r2, points.clamp(2, 1000), rotation_deg); + } + let n = points.clamp(2, 1000) * 2; + let rot = if rotation_deg.is_finite() { rotation_deg.to_radians() } else { 0.0 }; + let rand_amt = if randomized.is_finite() { randomized.clamp(0.0, 10.0) } else { 0.0 }; + let pts: Vec = (0..n) + .map(|i| { + let base_r = if i % 2 == 0 { r1 } else { r2 }; + let (dr, da) = if rand_amt > 1e-9 { vertex_jitter(i, n) } else { (0.0, 0.0) }; + let r = (base_r * (1.0 + rand_amt * 0.45 * dr)).max(0.01); + let a = -PI / 2.0 + rot + TAU * (i as f64 / n as f64) + rand_amt * (PI / n as f64) * da; + Point::new(center.x + r * a.cos(), center.y + r * a.sin()) + }) + .collect(); + contour_with_rounding(&pts, rounded) +} + /// Inner radius of a "straight-armed" star (Illustrator's Alt-drag behaviour): shoulders aligned. pub fn straight_star_inner_radius(r1: f64, points: u32) -> f64 { let n = points.max(3) as f64; @@ -249,6 +439,137 @@ pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clo PathData::single(sp) } +/// Configurable spiral with `turns` revolutions (`0.25..=50.0`), `divergence` radial growth power +/// (`0.05..=20.0`, `1.0` = uniform Archimedean spacing) and `inner_radius` fraction (`0.0..=0.99`). +pub fn spiral_configured(center: Point, radius: f64, turns: f64, divergence: f64, inner_radius: f64, clockwise: bool) -> PathData { + let turns = if turns.is_finite() { turns.clamp(0.25, 50.0) } else { 3.0 }; + let div = if divergence.is_finite() { divergence.clamp(0.05, 20.0) } else { 1.0 }; + let inner_frac = if inner_radius.is_finite() { inner_radius.clamp(0.0, 0.99) } else { 0.0 }; + let r_outer = if radius.is_finite() { radius.abs().max(0.01) } else { 50.0 }; + let r_inner = r_outer * inner_frac; + let steps = (turns * 4.0).round().clamp(1.0, 200.0) as usize; + let dir = if clockwise { 1.0 } else { -1.0 }; + let total_angle = dir * turns * TAU; + let dtheta = (turns * TAU) / (steps as f64); + let k = if dtheta > 1e-6 { KAPPA / dtheta } else { KAPPA }; + let mut anchors = Vec::with_capacity(steps + 1); + for i in 0..=steps { + let u = (i as f64) / (steps as f64); + let theta = u * total_angle; + let f = if u <= 0.0 { 0.0 } else { u.powf(div) }; + let r = r_inner + (r_outer - r_inner) * f; + let p = Point::new(center.x + r * theta.cos(), center.y + r * theta.sin()); + let dr_du = if u > 1e-9 { + (r_outer - r_inner) * div * u.powf(div - 1.0) + } else if (div - 1.0).abs() < 1e-9 { + r_outer - r_inner + } else { + 0.0 + }; + let dx_du = dr_du * theta.cos() - r * theta.sin() * total_angle; + let dy_du = dr_du * theta.sin() + r * theta.cos() * total_angle; + let d = Vec2::new(dx_du, dy_du) * (k / (steps as f64)); + let h_in = if i == 0 { p } else { p - d }; + let h_out = if i == steps { p } else { p + d }; + anchors.push(Anchor { p, h_in, h_out, kind: AnchorKind::Smooth }); + } + PathData::single(SubPath::new(anchors, false)) +} + +/// Rotatable 3D box inscribed in `r`, rotated by `(angle_x, angle_y, angle_z)` degrees and using +/// orthographic parallel projection per axis when `parallel_*` is true or perspective foreshortening +/// when false. Emits the visible front-facing quad faces with clockwise winding. +pub fn box3d(r: Rect, angle_x: f64, angle_y: f64, angle_z: f64, parallel_x: bool, parallel_y: bool, parallel_z: bool) -> PathData { + let r = r.abs(); + if r.width() <= 1e-9 || r.height() <= 1e-9 { + return rectangle(r); + } + let rx = if angle_x.is_finite() { angle_x.to_radians() } else { 30.0_f64.to_radians() }; + let ry = if angle_y.is_finite() { angle_y.to_radians() } else { 35.0_f64.to_radians() }; + let rz = if angle_z.is_finite() { angle_z.to_radians() } else { 0.0 }; + let (sx, cx) = rx.sin_cos(); + let (sy, cy) = ry.sin_cos(); + let (sz, cz) = rz.sin_cos(); + + let transform_pt = |mut x: f64, mut y: f64, mut z: f64| -> (f64, f64, f64) { + if !parallel_x { + let k = 1.0 - 0.22 * x; + y *= k; + z *= k; + } + if !parallel_y { + let k = 1.0 - 0.22 * y; + x *= k; + z *= k; + } + // Rotate around X + let (y1, z1) = (y * cx - z * sx, y * sx + z * cx); + // Rotate around Y + let (x2, z2) = (x * cy + z1 * sy, -x * sy + z1 * cy); + // Rotate around Z + let (x3, y3) = (x2 * cz - y1 * sz, x2 * sz + y1 * cz); + let persp = if parallel_z { 1.0 } else { 1.0 / (1.0 - 0.25 * z2).max(0.2) }; + (x3 * persp, y3 * persp, z2) + }; + + let raw_verts: [(f64, f64, f64); 8] = [ + transform_pt(-1.0, -1.0, -1.0), + transform_pt(1.0, -1.0, -1.0), + transform_pt(1.0, 1.0, -1.0), + transform_pt(-1.0, 1.0, -1.0), + transform_pt(-1.0, -1.0, 1.0), + transform_pt(1.0, -1.0, 1.0), + transform_pt(1.0, 1.0, 1.0), + transform_pt(-1.0, 1.0, 1.0), + ]; + + let mut min_x = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut min_y = f64::INFINITY; + let mut max_y = f64::NEG_INFINITY; + for &(vx, vy, _) in &raw_verts { + min_x = min_x.min(vx); + max_x = max_x.max(vx); + min_y = min_y.min(vy); + max_y = max_y.max(vy); + } + let span_x = (max_x - min_x).max(1e-6); + let span_y = (max_y - min_y).max(1e-6); + let proj = |i: usize| -> Point { + let (vx, vy, _) = raw_verts[i]; + Point::new(r.x0 + (vx - min_x) / span_x * r.width(), r.y0 + (vy - min_y) / span_y * r.height()) + }; + + // 6 cube faces with outward-pointing vertex order in 3D. + const FACES: [[usize; 4]; 6] = [ + [4, 5, 6, 7], // +Z front + [1, 0, 3, 2], // -Z back + [0, 4, 7, 3], // -X left + [5, 1, 2, 6], // +X right + [0, 1, 5, 4], // -Y top + [7, 6, 2, 3], // +Y bottom + ]; + + let mut faces_with_depth: Vec<(f64, SubPath)> = Vec::new(); + for idx in FACES { + let z_avg = (raw_verts[idx[0]].2 + raw_verts[idx[1]].2 + raw_verts[idx[2]].2 + raw_verts[idx[3]].2) * 0.25; + let mut pts = [proj(idx[0]), proj(idx[1]), proj(idx[2]), proj(idx[3])]; + let mut sp = SubPath::polyline(&pts, true); + let area = sp.signed_area(); + // Outward face in camera space has positive signed area (clockwise on screen, y down). + if area > 1e-4 { + faces_with_depth.push((z_avg, sp)); + } else if faces_with_depth.is_empty() && area.abs() > 1e-4 { + pts.reverse(); + sp = SubPath::polyline(&pts, true); + faces_with_depth.push((z_avg, sp)); + } + } + faces_with_depth.sort_by(|a, b| a.0.total_cmp(&b.0)); + let subpaths: Vec = faces_with_depth.into_iter().map(|(_, sp)| sp).collect(); + if subpaths.is_empty() { rectangle(r) } else { PathData::new(subpaths) } +} + /// The largest grid divider skew, in percent either way. pub const GRID_SKEW_MAX: f64 = 500.0; @@ -628,4 +949,41 @@ mod tests { let seg = arc_segment(Point::ZERO, 0, 100.0, 50.0, true, 50.0, false); assert_eq!(seg.anchor_count(), 2); } + + #[test] + fn ellipse_arc_modes_and_configured_shapes() { + let r = Rect::new(0.0, 0.0, 100.0, 100.0); + let slice = ellipse_arc(r, 0.0, 90.0, EllipseMode::Slice); + assert!(slice.is_closed() && slice.anchor_count() == 3); + assert_eq!(slice, ellipse_pie(r, 0.0, 90.0), "ellipse_pie matches Slice mode"); + let chord = ellipse_arc(r, 0.0, 90.0, EllipseMode::Chord); + assert!(chord.is_closed() && chord.anchor_count() == 2); + let open_arc = ellipse_arc(r, 0.0, 90.0, EllipseMode::Arc); + assert!(!open_arc.is_closed() && open_arc.anchor_count() == 2); + let whole = ellipse_arc(r, 0.0, 90.0, EllipseMode::Whole); + assert_eq!(whole, ellipse(r)); + + // Rectangle opened/cut with apply_shape_arc + let rect_open = apply_shape_arc(rectangle(r), r.center(), 30.0, 300.0, EllipseMode::Arc); + assert!(!rect_open.is_closed()); + let rect_slice = apply_shape_arc(rectangle(r), r.center(), 30.0, 300.0, EllipseMode::Slice); + assert!(rect_slice.is_closed() && rect_slice.subpaths[0].anchors[0].p == r.center()); + + // Polygon and Star with rounded and randomized, and unconfigured parity + assert_eq!(polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.0, 0.0), polygon(Point::ZERO, 50.0, 6, 0.0)); + assert_eq!(star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.0, 0.0), star(Point::ZERO, 50.0, 25.0, 5, 0.0)); + let poly_round = polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.5, 0.1); + assert_eq!(poly_round.anchor_count(), 6); + assert!(poly_round.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out())); + let star_round = star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.5, 0.1); + assert_eq!(star_round.anchor_count(), 10); + + // Spiral configured + let sp = spiral_configured(Point::ZERO, 100.0, 3.0, 1.5, 0.25, true); + assert!(!sp.is_closed() && sp.anchor_count() == 13); + + // 3D Box + let b3d = box3d(r, 30.0, 35.0, 0.0, true, true, true); + assert!(!b3d.subpaths.is_empty() && b3d.subpaths.iter().all(|s| s.closed && s.anchors.len() == 4)); + } } diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 64a7f0ea1f..0a81bb127f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -181,9 +181,11 @@ impl Headless { fn pointer(&mut self, p: &Value) -> Result { let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?; let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + let default = PointerEvent::json_backquote(p, false)?; + let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; self.ensure_document(); let mut requests = vec![]; - for e in events { + for (e, backquote) in events.iter().zip(held) { let kind = s(e, "kind").unwrap_or(""); let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; if s(e, "space") == Some("screen") { @@ -192,8 +194,6 @@ impl Headless { let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base); - let backquote = - e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); let ev = PointerEvent { kind, pos: Point::new(x, y), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2e153b62b7..90df3349ec 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1431,6 +1431,34 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. +#[test] +fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { + let mut s = server(); + let made = call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 50, "height": 50, "fill": "#ff0000"})); + let id = serde_json::from_str::(&text_of(&made)).unwrap()["id"].as_u64().unwrap(); + let drag = |top: Option, first: Option| { + let mut down = json!({"kind": "down", "x": 300, "y": 300}); + if let Some(b) = first { + down["backquote"] = b; + } + let mut a = json!({"tool": "rectangle", "events": [down, {"kind": "drag", "x": 350, "y": 350}, {"kind": "up", "x": 350, "y": 350}]}); + if let Some(b) = top { + a["backquote"] = b; + } + a + }; + for (n, args) in [drag(Some(json!("true")), None), drag(None, Some(json!(1)))].into_iter().enumerate() { + let r = call(&mut s, 2 + n as u64, "pointer_gesture", args); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("`backquote` must be a boolean"), "{r}"); + } + let inspected = call(&mut s, 4, "inspect_document", json!({})); + let doc = serde_json::from_str::(&text_of(&inspected)).unwrap(); + let children = doc["layers"][0]["children"].as_array().unwrap(); + assert_eq!(children.iter().map(|n| n["id"].as_u64()).collect::>(), vec![Some(id)], "{doc}"); +} + /// A Shift-drag marquee reaches agents (#483): `pointer_gesture` with `mods.shift` toggles the /// objects it reaches, so a selected one leaves the selection and an unselected one joins it. #[test] diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index 679a3f554e..0d9dc5c49d 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -16,6 +16,24 @@ fn three_boards() -> Headless { h } +#[test] +fn raster_export_uses_document_resolution_unless_overridden() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 72, "height": 36, "rasterEffectsPpi": 300}})).unwrap(); + for (args, size) in [ + (json!({}), (300, 150)), + (json!({"scale": 1}), (72, 36)), + (json!({"options": {"scale": 2}}), (144, 72)), + (json!({"scale": 2, "options": {"ppi": 150}}), (150, 75)), + ] { + let mut params = args.clone(); + params["format"] = json!("png"); + let r = text(&call_tool(&mut h, "export", ¶ms)); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().dimensions(), size, "{args}"); + } +} + #[test] fn export_with_a_range_writes_one_file_per_artboard() { let mut h = three_boards(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index c889c2237a..105dca3467 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -391,7 +391,7 @@ pub fn tool_definitions() -> Vec { json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), - "scale": num("Raster pixels per point (default 1)"), + "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF and WMF: one, or one file each with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 9e3af3dbaa..f9d768eaa5 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -125,6 +125,12 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result PathData; // delta < 0 insets +pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result; pub fn outline_stroke(path: &PathData, width: f64, cap: Cap, join: Join, miter_limit: f64) -> PathData; ``` diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index f61ac5e488..163fe7e7ca 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -296,11 +296,15 @@ impl Tidy { } impl Arrangement { - pub(crate) fn new(mut paths: Vec<(BezPath, FillRule)>) -> Result { + pub(crate) fn new(paths: Vec<(BezPath, FillRule)>) -> Result { + Self::new_budgeted(paths, crate::budget::MAX_SEGMENT_PAIRS) + } + + pub(crate) fn new_budgeted(mut paths: Vec<(BezPath, FillRule)>, cap: usize) -> Result { let eps = eps_for(paths.iter().map(|p| &p.0))?; snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::>(), eps); // Counted on the snapped geometry, which is what the sweep sees: snapping can bring boxes into contact. - if !crate::budget::sweep_fits(paths.iter().map(|p| &p.0)) { + if !crate::budget::sweep_fits_within(paths.iter().map(|p| &p.0), cap) { return Err(PathOpsError::TooComplex); } // The sweep can panic on rare near-degenerate input; that must never take the app down, @@ -835,6 +839,23 @@ mod tests { assert_eq!(tidy.repair(&lens), lens); } + #[test] + fn arrangement_new_budgeted_fails_on_complexity_and_open_paths() { + let mut bp = BezPath::new(); + for i in 0..100 { + let r = kurbo::Rect::new(0.0, 0.0, 10.0 + i as f64, 10.0 + i as f64); + bp.extend(r.to_path(0.1).iter()); + } + let too_complex = Arrangement::new_budgeted(vec![(bp, FillRule::NonZero)], 5); + assert_eq!(too_complex.err(), Some(PathOpsError::TooComplex)); + + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((10.0, 10.0)); + let failed_arr = Arrangement::new_budgeted(vec![(open, FillRule::NonZero)], 1000); + assert_eq!(failed_arr.err(), Some(PathOpsError::OpenPath)); + } + fn square(x: f64, y: f64, size: f64) -> PathData { PathData::single(vectorcraft_geom::SubPath::new( [(x, y), (x + size, y), (x + size, y + size), (x, y + size)] diff --git a/crates/pathops/src/budget.rs b/crates/pathops/src/budget.rs index 01559ce8a8..824af9fc2f 100644 --- a/crates/pathops/src/budget.rs +++ b/crates/pathops/src/budget.rs @@ -82,10 +82,15 @@ pub(crate) fn overlaps_within(boxes: &[Rect], cap: usize) -> bool { true } +/// Can a planar map be built of `paths` within `cap` segment pairs? +pub(crate) fn sweep_fits_within<'a>(paths: impl IntoIterator, cap: usize) -> bool { + let boxes: Vec = paths.into_iter().flat_map(|p| p.segments().map(|s| s.bounding_box())).collect(); + overlaps_within(&boxes, cap) +} + /// Can a planar map be built of `paths` within [`MAX_SEGMENT_PAIRS`]? pub(crate) fn sweep_fits<'a>(paths: impl IntoIterator) -> bool { - let boxes: Vec = paths.into_iter().flat_map(|p| p.segments().map(|s| s.bounding_box())).collect(); - overlaps_within(&boxes, MAX_SEGMENT_PAIRS) + sweep_fits_within(paths, MAX_SEGMENT_PAIRS) } #[cfg(test)] diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 980509a871..3d1b17fef9 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -25,7 +25,7 @@ pub use edit::{ remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, smooth_options, split_into_grid, }; -pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region}; +pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions}; pub use planar::{ BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point, diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index ec6b517f7a..f028c0704f 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -7,12 +7,26 @@ pub use kurbo::{Cap, Join}; use linesweeper::topology::{ContourIdx, Contours}; +use crate::PathOpsError; use crate::boolean::{Arrangement, DEFAULT_PRECISION, Tidy, all_contours_to_path, contours_to_path, fill_bezpath, normalize_bez}; use crate::edit::remove_redundant_points; /// Flattening/fit tolerance handed to kurbo's stroker. const STROKE_TOL: f64 = 1e-3; +/// Most overlapping segment pairs allowed for planar arrangement in offset path: 524,288 (1 << 19). +/// +/// Rationale: +/// - The global boolean sweep cap is `MAX_SEGMENT_PAIRS = 1 << 22` (4,194,304 pairs). +/// - An offset operation decomposes paths into outer rings, inner/fill boundaries, and open +/// subpath strokes. When applied to multi-copy transformations (e.g. 25–50 copies in #4145), +/// these parallel strokes create dense self- and cross-intersections where pairwise bounding-box +/// overlaps scale quadratically with the number of segments. +/// - At 1 << 19 (524,288 segment pairs), the planar sweep memory usage is bounded to tens of MBs +/// and completes within ~100 ms on typical CPUs, preventing exponential allocation spikes and +/// application hangs while still generously accommodating legitimate complex artwork. +pub const MAX_OFFSET_SEGMENT_PAIRS: usize = 1 << 19; + /// Drop collinear and coincident spine vertices before stroking (#3446). Uses `tol` only for /// redundancy; does not simplify or refit the spine. fn compact_stroke_spine(bp: &BezPath, tol: f64) -> BezPath { @@ -92,13 +106,23 @@ pub fn stroke_region(outlines: &[BezPath]) -> PathData { normalize_bez(&all, FillRule::NonZero).map(|c| all_contours_to_path(&c, &tidy)).unwrap_or_default() } -/// Object → Path → Offset Path. Positive `delta` grows the filled area, negative insets it. -/// Closed subpaths are treated as a non-zero filled region; open subpaths are outlined with a -/// stroke of width `2|delta|` (butt caps). An open subpath whose last anchor sits on its first is -/// offset as a closed one. -pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> PathData { - if !delta.is_finite() || path.is_empty() { - return PathData::default(); +/// Validate that all anchor coordinates and control handles of `path` are finite. +fn path_is_finite(path: &PathData) -> bool { + path.subpaths.iter().all(|sp| { + sp.anchors.iter().all(|a| { + a.p.x.is_finite() && a.p.y.is_finite() && a.h_in.x.is_finite() && a.h_in.y.is_finite() && a.h_out.x.is_finite() && a.h_out.y.is_finite() + }) + }) +} + +/// Fallible [`offset_path`] that returns an error when the input is non-finite or exceeds +/// the complexity bound ([`MAX_OFFSET_SEGMENT_PAIRS`]), or when planar arrangement fails. +pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result { + if !delta.is_finite() || !path_is_finite(path) { + return Err(PathOpsError::NonFinite); + } + if path.is_empty() { + return Ok(PathData::default()); } let subpaths: Vec = path.subpaths.iter().map(close_if_ends_meet).collect(); let closed = PathData::new(subpaths.iter().filter(|s| s.closed && s.anchors.len() > 1).cloned().collect()); @@ -111,9 +135,10 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> } else { BezPath::new() }; - let Ok(arr) = Arrangement::new(vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)]) else { - return PathData::default(); - }; + let arr = Arrangement::new_budgeted( + vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)], + MAX_OFFSET_SEGMENT_PAIRS, + )?; let c = if delta >= 0.0 { arr.contours(|m| m[0] || m[1] || m[2]) } else { arr.contours(|m| m[0] && !m[1]) }; // When `d` exceeds a curvature radius the stroker's inner offset inverts and its loops cancel // winding, leaving faces uncovered that are really within `d` of the path. Every face of the @@ -124,10 +149,25 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> let spurious: Vec = c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| any_within(&src, p, d * (1.0 - 1e-4) - 1e-6))).collect(); if !spurious.contains(&true) { - return all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION)); + return Ok(all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION))); } let keep = (0..spurious.len()).filter(|&i| !has_marked_ancestor(&c, i, &spurious)).map(ContourIdx); - contours_to_path(&c, keep, &Tidy::free(DEFAULT_PRECISION)) + Ok(contours_to_path(&c, keep, &Tidy::free(DEFAULT_PRECISION))) +} + +/// Object → Path → Offset Path. Positive `delta` grows the filled area, negative insets it. +/// Closed subpaths are treated as a non-zero filled region; open subpaths are outlined with a +/// stroke of width `2|delta|` (butt caps). An open subpath whose last anchor sits on its first is +/// offset as a closed one. +/// +/// If planar arrangement exceeds complexity or encounters a degenerate arrangement error, +/// gracefully preserves `path` unchanged to prevent rendering crashes or disappearing artwork (#4145). +/// Non-finite input returns an empty path. +pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> PathData { + try_offset_path(path, delta, join, miter_limit).unwrap_or_else(|e| match e { + PathOpsError::NonFinite => PathData::default(), + _ => path.clone(), + }) } /// An open subpath of three or more anchors whose last anchor lies within 1e-6 of its first (the @@ -442,4 +482,45 @@ mod tests { let arc_raw = stroke_bez_without_spine_compact(&arc_bez, width, cap, join, miter); assert!(outline_max_deviation(&arc_compact, &arc_raw) <= 1e-3, "curved spine compaction must not refit the stroke outline"); } + + #[test] + fn offset_path_recovers_gracefully_when_complexity_exceeds_budget() { + // Issue #4145: dense overlapping geometry must not hang or panic; if complexity passes + // the offset cap, try_offset_path reports PathOpsError::TooComplex and offset_path + // preserves the input path unchanged. + let mut bp = BezPath::new(); + for i in 0..300 { + let offset = i as f64 * 0.1; + let rect = kurbo::Rect::new(offset, offset, offset + 100.0, offset + 100.0); + bp.extend(rect.to_path(0.1).iter()); + } + let path = PathData::from_bezpath(&bp); + assert_eq!(try_offset_path(&path, 5.0, Join::Round, 4.0), Err(PathOpsError::TooComplex)); + let res = offset_path(&path, 5.0, Join::Round, 4.0); + assert_eq!(res, path); + } + + #[test] + fn offset_path_returns_empty_on_non_finite() { + let rect = kurbo::Rect::new(0.0, 0.0, 100.0, 100.0); + let path = PathData::from_bezpath(&rect.to_path(0.1)); + assert_eq!(try_offset_path(&path, f64::NAN, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert_eq!(try_offset_path(&path, f64::INFINITY, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert!(offset_path(&path, f64::NAN, Join::Round, 4.0).is_empty()); + assert!(offset_path(&path, f64::INFINITY, Join::Round, 4.0).is_empty()); + + // Even with dense overlapping geometry, non-finite points return NonFinite error and empty rather than fallback. + let mut bp = BezPath::new(); + for i in 0..300 { + let offset = i as f64 * 0.1; + let rect = kurbo::Rect::new(offset, offset, offset + 100.0, offset + 100.0); + bp.extend(rect.to_path(0.1).iter()); + } + let mut dense_non_finite = PathData::from_bezpath(&bp); + dense_non_finite + .subpaths + .push(SubPath::polyline(&[vectorcraft_geom::Point::new(f64::NAN, 0.0), vectorcraft_geom::Point::new(10.0, 10.0)], true)); + assert_eq!(try_offset_path(&dense_non_finite, 5.0, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert!(offset_path(&dense_non_finite, 5.0, Join::Round, 4.0).is_empty()); + } } diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 5e6f55135a..f0c5ab505b 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -155,7 +155,19 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve .collect(), // topmost(m) == Some(i) PathfinderOp::Trim => { - (0..n).flat_map(|i| one(all_contours_to_path(&arr.contours_where(|w| arr.covered(w).next_back() == Some(i)), p), shapes[i].key)).collect() + let mut subpaths = vec![Vec::new(); n]; + each_classified_face( + &arr, + n, + |w| arr.covered(w).next_back(), + |i, c, group| { + if let Some(sp) = subpaths.get_mut(i) { + let p = contours_to_path(c, group.iter().copied(), &arr.tidy); + sp.extend(p.subpaths); + } + }, + ); + subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } PathfinderOp::Merge => { let mut keys: Vec = Vec::new(); @@ -178,16 +190,22 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve if n < 2 { return Vec::new(); } - (0..n - 1) - .flat_map(|i| { - // m[n - 1] && topmost(&m[..n - 1]) == Some(i): the front shape, then i below it - let c = arr.contours_where(|w| { - let mut c = arr.covered(w).rev(); - c.next() == Some(n - 1) && c.next() == Some(i) - }); - one(all_contours_to_path(&c, p), shapes[i].key) - }) - .collect() + let mut subpaths = vec![Vec::new(); n - 1]; + each_classified_face( + &arr, + n - 1, + |w| { + let mut c = arr.covered(w).rev(); + if c.next() == Some(n - 1) { c.next() } else { None } + }, + |i, c, group| { + if let Some(sp) = subpaths.get_mut(i) { + let p = contours_to_path(c, group.iter().copied(), &arr.tidy); + sp.extend(p.subpaths); + } + }, + ); + subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } PathfinderOp::Outline => outline_edges(&arr, shapes), PathfinderOp::HardMix | PathfinderOp::SoftMix => regions_of(&arr) @@ -219,29 +237,29 @@ fn regions_of(arr: &Arrangement) -> Vec { out } -/// Calls `f` with each face of `arr` whose coverage is one of `masks` (distinct): the index of -/// its mask in `masks`, the contour pass it is in, and its contours, an outer contour and the -/// holes of its mask directly inside it ([`face_groups`]). Each mask's faces come in the order -/// of that mask's own contour pass. +/// Calls `f` with each face of `arr` classified by `classify: impl Fn(&Multi) -> Option` +/// into `0..num_classes`: the index of its class, the contour pass it is in, and its contours, +/// an outer contour and the holes of its class directly inside it ([`face_groups`]). /// -/// A contour pass walks the whole arrangement, so one pass per mask would cost masks × edges -/// (two blends crossing make thousands of each). Instead the masks go into batches whose faces -/// share no vertex (so no edge either): one pass per batch walks each face's contours exactly as -/// its own mask's pass would, and the mask a contour bounds is the one of its batch at its first -/// point. -fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Contours, &[ContourIdx])) { - if masks.is_empty() { +/// A contour pass walks the whole arrangement, so one pass per class would cost classes × edges. +/// Instead the classes go into batches whose faces share no vertex (so no edge either): one pass +/// per batch walks each face's contours exactly as its own class's pass would, and the class a +/// contour bounds is the one of its batch at its first point. +fn each_classified_face( + arr: &Arrangement, + num_classes: usize, + classify: impl Fn(&Multi) -> Option, + mut f: impl FnMut(usize, &Contours, &[ContourIdx]), +) { + if num_classes == 0 { return; } - // Each mask is found by the inputs it covers. - let ids = CoverIds::new(masks.iter().map(|m| m.iter().enumerate().filter(|(_, b)| **b).map(|(k, _)| k).collect()).collect()); - let id = |w: &Multi| ids.of(arr, w); let top = &arr.top; - // The masks of the faces around each vertex. + // The classes of the faces around each vertex. let mut around: HashMap<(u64, u64), Vec> = HashMap::new(); for s in top.segment_indices() { let h = s.first_half(); - let sides = [id(top.winding_clockwise(h)), id(top.winding_counter_clockwise(h))]; + let sides = [classify(top.winding_clockwise(h)), classify(top.winding_counter_clockwise(h))]; for end in [h, s.second_half()] { let at = around.entry(vertex_key(top.point(end).to_kurbo())).or_default(); for m in sides.into_iter().flatten() { @@ -251,16 +269,16 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con } } } - let mut near = vec![Vec::new(); masks.len()]; + let mut near = vec![Vec::new(); num_classes]; for at in around.values() { for &a in at { near[a].extend(at.iter().copied().filter(|&b| b != a)); } } - // Greedy colouring: each mask takes the first batch none of its neighbours is in. - let mut batch = vec![usize::MAX; masks.len()]; + // Greedy colouring: each class takes the first batch none of its neighbours is in. + let mut batch = vec![usize::MAX; num_classes]; let mut batches = 0; - for m in 0..masks.len() { + for m in 0..num_classes { let mut taken = vec![false; batches]; for &n in &near[m] { if let Some(t) = taken.get_mut(batch[n]) { @@ -271,7 +289,7 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con batches = batches.max(batch[m] + 1); } for b in 0..batches { - let c = arr.contours_where(|w| id(w).is_some_and(|m| batch[m] == b)); + let c = arr.contours_where(|w| classify(w).is_some_and(|m| batch[m] == b)); let owner: Option> = c .contours() .map(|ct| { @@ -281,9 +299,9 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con .collect(); let Some(owner) = owner else { // Not expected: every contour starts at a vertex of the arrangement. Fall back to a - // pass per mask for this batch. - for (m, mask) in masks.iter().enumerate().filter(|(m, _)| batch[*m] == b) { - let c = arr.contours(|k| k == *mask); + // pass per class for this batch. + for m in (0..num_classes).filter(|m| batch[*m] == b) { + let c = arr.contours_where(|w| classify(w) == Some(m)); let owner = vec![m; c.contours().count()]; for (_, group) in face_groups(&c, &owner) { f(m, &c, &group); @@ -297,6 +315,25 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con } } +/// Calls `f` with each face of `arr` whose coverage is one of `masks` (distinct): the index of +/// its mask in `masks`, the contour pass it is in, and its contours, an outer contour and the +/// holes of its mask directly inside it ([`face_groups`]). Each mask's faces come in the order +/// of that mask's own contour pass. +/// +/// A contour pass walks the whole arrangement, so one pass per mask would cost masks × edges +/// (two blends crossing make thousands of each). Instead the masks go into batches whose faces +/// share no vertex (so no edge either): one pass per batch walks each face's contours exactly as +/// its own mask's pass would, and the mask a contour bounds is the one of its batch at its first +/// point. +fn each_face(arr: &Arrangement, masks: &[&[bool]], f: impl FnMut(usize, &Contours, &[ContourIdx])) { + if masks.is_empty() { + return; + } + // Each mask is found by the inputs it covers. + let ids = CoverIds::new(masks.iter().map(|m| m.iter().enumerate().filter(|(_, b)| **b).map(|(k, _)| k).collect()).collect()); + each_classified_face(arr, masks.len(), |w| ids.of(arr, w), f); +} + /// Lists of inputs, each ascending as [`Arrangement::covered`] gives them, found by the inputs /// that cover a winding. struct CoverIds { @@ -1355,4 +1392,68 @@ mod tests { assert_eq!(faces[0].key, 7); assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6); } + + fn old_trim(shapes: &[Shape], precision: f64) -> Vec { + let n = shapes.len(); + let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; + (0..n) + .flat_map(|i| { + let c = arr.contours_where(|w| arr.covered(w).next_back() == Some(i)); + one(all_contours_to_path(&c, &arr.tidy), shapes[i].key) + }) + .collect() + } + + fn old_crop(shapes: &[Shape], precision: f64) -> Vec { + let n = shapes.len(); + if n < 2 { + return Vec::new(); + } + let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; + (0..n - 1) + .flat_map(|i| { + let c = arr.contours_where(|w| { + let mut c = arr.covered(w).rev(); + c.next() == Some(n - 1) && c.next() == Some(i) + }); + one(all_contours_to_path(&c, &arr.tidy), shapes[i].key) + }) + .collect() + } + + #[test] + fn trim_and_crop_differential_matches_reference_on_overlapping_shapes() { + let shapes = vec![ + Shape::new(rect(0.0, 0.0, 60.0, 60.0), FillRule::NonZero, 1), + Shape::new(rect(30.0, 0.0, 90.0, 60.0), FillRule::NonZero, 2), + Shape::new(rect(15.0, 15.0, 75.0, 75.0), FillRule::NonZero, 3), + Shape::new(rect(40.0, 40.0, 100.0, 100.0), FillRule::NonZero, 4), + ]; + + let trim_actual = pathfinder_with(PathfinderOp::Trim, &shapes, DEFAULT_PRECISION); + let trim_expected = old_trim(&shapes, DEFAULT_PRECISION); + assert_eq!(trim_actual.len(), trim_expected.len(), "trim shape count must match"); + for (actual, expected) in trim_actual.iter().zip(&trim_expected) { + assert_eq!(actual.key, expected.key); + assert_eq!(actual.path, expected.path, "subpath order and contours must match reference trim"); + } + + let crop_actual = pathfinder_with(PathfinderOp::Crop, &shapes, DEFAULT_PRECISION); + let crop_expected = old_crop(&shapes, DEFAULT_PRECISION); + assert_eq!(crop_actual.len(), crop_expected.len(), "crop shape count must match"); + for (actual, expected) in crop_actual.iter().zip(&crop_expected) { + assert_eq!(actual.key, expected.key); + assert_eq!(actual.path, expected.path, "subpath order and contours must match reference crop"); + } + + // Test with shape that has no face left (completely covered by front shape) + let covered = vec![ + Shape::new(rect(10.0, 10.0, 20.0, 20.0), FillRule::NonZero, 10), // inside shape 20 + Shape::new(rect(0.0, 0.0, 50.0, 50.0), FillRule::NonZero, 20), + ]; + let trim_cov_actual = pathfinder_with(PathfinderOp::Trim, &covered, DEFAULT_PRECISION); + let trim_cov_expected = old_trim(&covered, DEFAULT_PRECISION); + assert_eq!(trim_cov_actual.len(), 1); + assert_eq!(trim_cov_actual, trim_cov_expected); + } } diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 3abf7cfeaa..aa853b2469 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -423,8 +423,8 @@ impl Map { } /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) -/// that lie under the outline of a closed path in front of them, whose edges are that closed -/// path's. +/// that lie under another path in front of them, whose edges are that path's: under a closed +/// path's outline, or along an open path in front. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { let m = map_with(shapes, false, precision)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; @@ -461,61 +461,65 @@ pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Ve }) .collect() }; - let edge_shapes = to_shapes(chains_by(edges, around, |e| Some(e.source))); let is_line = |i: usize| shapes.get(i).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); - let under = to_shapes(chains_by(edges, around, |e| if is_line(e.source) { None } else { e.sources.iter().rev().copied().find(|&i| is_line(i)) })); + // An edge is the front-most input's. Every other open path along it has a piece there too. + let edge_shapes = to_shapes(chains_by(edges, around, |e| vec![e.source])); + let under = to_shapes(chains_by(edges, around, |e| e.sources.iter().rev().copied().filter(|&i| i != e.source && is_line(i)).collect())); Some((regions, edge_shapes, under)) } -/// The edges that `key` gives an input, joined into chains through the vertices where only two -/// edges of the same input meet, each with that input. A chain is closed when it comes back round -/// to where it started. -fn chains_by(edges: &[Edge], around: &[Vec], key: impl Fn(&Edge) -> Option) -> Vec<(Vec, bool, usize)> { - let keys: Vec> = edges.iter().map(&key).collect(); - let key_of = |h: usize| keys.get(h / 2).copied().flatten(); - let passes = |v: usize| -> Option<(usize, usize)> { +/// The edges that `keys` gives each input, joined into chains through the vertices where only two +/// edges of the same input meet, each with that input. An edge that several inputs share is in a +/// chain for each of them. A chain is closed when it comes back round to where it started. +fn chains_by(edges: &[Edge], around: &[Vec], keys: impl Fn(&Edge) -> Vec) -> Vec<(Vec, bool, usize)> { + let keys: Vec> = edges.iter().map(&keys).collect(); + // Where input `k` is among the inputs half-edge `h` gives. + let slot = |h: usize, k: usize| keys.get(h / 2).and_then(|ks| ks.iter().position(|&x| x == k)); + let passes = |v: usize, k: usize| -> Option<(usize, usize)> { let list = around.get(v)?; let (&a, &b) = (list.first()?, list.get(1)?); - (list.len() == 2 && key_of(a).is_some() && key_of(a) == key_of(b)).then_some((a, b)) + (list.len() == 2 && slot(a, k).is_some() && slot(b, k).is_some()).then_some((a, b)) }; - // Edges with no input to give are never walked. - let mut used: Vec = keys.iter().map(Option::is_none).collect(); + // Each edge's inputs, and whether its chain for each has been walked. + let mut used: Vec> = keys.iter().map(|ks| vec![false; ks.len()]).collect(); let mut chains: Vec<(Vec, bool, usize)> = Vec::new(); - // A chain from half-edge `h0` up to the next vertex where it doesn't pass straight through. - let walk = |h0: usize, used: &mut Vec| -> Option<(Vec, bool, usize)> { - let source = key_of(h0)?; + // A chain of input `k` from half-edge `h0` up to the next vertex where it doesn't pass straight through. + let walk = |h0: usize, k: usize, used: &mut Vec>| -> Option<(Vec, bool, usize)> { let mut segs = Vec::new(); let mut h = h0; loop { - let u = used.get_mut(h / 2)?; + let u = used.get_mut(h / 2)?.get_mut(slot(h, k)?)?; if *u { - return Some((segs, true, source)); + return Some((segs, true, k)); } *u = true; segs.extend(half_segs(edges, h)); let v = origin(edges, twin(h))?; - let Some((a, b)) = passes(v) else { return Some((segs, origin(edges, h0) == Some(v), source)) }; + let Some((a, b)) = passes(v, k) else { return Some((segs, origin(edges, h0) == Some(v), k)) }; h = if a == twin(h) { b } else { a }; } }; + let unwalked = |used: &[Vec], h: usize, k: usize| slot(h, k).is_some_and(|s| used.get(h / 2).and_then(|u| u.get(s)) == Some(&false)); for v in 0..around.len() { - if passes(v).is_some() { - continue; - } for &h in around.get(v).map(Vec::as_slice).unwrap_or_default() { - if !used.get(h / 2).copied().unwrap_or(true) - && let Some(c) = walk(h, &mut used) - { - chains.push(c); + for &k in keys.get(h / 2).map(Vec::as_slice).unwrap_or_default() { + if passes(v, k).is_none() + && unwalked(&used, h, k) + && let Some(c) = walk(h, k, &mut used) + { + chains.push(c); + } } } } // What's left are closed loops with no junction on them. for e in 0..edges.len() { - if !used.get(e).copied().unwrap_or(true) - && let Some(c) = walk(2 * e, &mut used) - { - chains.push(c); + for &k in keys.get(e).map(Vec::as_slice).unwrap_or_default() { + if unwalked(&used, 2 * e, k) + && let Some(c) = walk(2 * e, k, &mut used) + { + chains.push(c); + } } } chains diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 290bc270d4..fde156f9b3 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,8 +19,9 @@ pub struct BuilderArrangement { /// share one); only when asked for. pub edges: Vec, /// The pieces of the paths with no closed subpath that lie under the outline of a closed path - /// in front of them, keyed by input index. No piece of `lines` covers them; there the edge is - /// the closed path's (in `edges`, when asked for). + /// in front of them, or along another such path in front of them, keyed by input index. No + /// piece of theirs is in `lines`; there the edge is the path's in front (in `edges` when it is + /// a closed path's and they were asked for, else in `lines`). pub lines_under: Vec, } diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 654d7d5cb7..3cee370df8 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -444,6 +444,31 @@ fn shape_builder_keeps_the_pieces_of_a_line_under_an_outline_in_front() { assert!(shape_builder(&s, true).lines_under.is_empty()); } +#[test] +fn shape_builder_gives_each_coincident_line_its_pieces() { + // Two lines along the same stretch, whose left half lies under the bottom edge of a rectangle + // in front of them: each has its own pieces, under the edge and beyond it. Beyond the edge the + // front line's piece is the edge, and the back line's lies under it. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), rect(0.0, 0.0, 100.0, 50.0, 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + let spans = |pieces: &[Shape], key: u64| { + let mut v: Vec<_> = pieces.iter().filter(|l| l.key == key).filter_map(|l| l.path.bounds().map(|b| (b.x0, b.x1))).collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v + }; + assert_eq!(spans(&lines, 1), [(100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 1), [(0.0, 100.0)], "{lines_under:?}"); + assert_eq!(spans(&lines, 0), [], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Without the rectangle, both lines are cut where the line across them crosses. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), line((100.0, 0.0), (100.0, 100.0), 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + assert_eq!(spans(&lines, 1), [(0.0, 100.0), (100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Live Paint's edges stay one per stretch, the front line's. + assert_eq!(live_paint(&s).1.iter().filter(|e| e.key == 0).count(), 0); +} + #[test] fn shape_builder_merges_adjacent_gap_closed_faces_without_keeping_bridges() { let outline = Shape::new( diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 80a95ad167..389552948e 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -196,7 +196,7 @@ impl Exporter<'_> { } NodeKind::Text(t) => self.text(s, n, t, page), NodeKind::Image(im) => match n.extras().colorize.as_deref() { - Some(p @ Paint::Solid { .. }) => { + Some(p @ Paint::Solid { .. }) if self.doc.image_blob(im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) { self.image(s, im, Some(colorized), n.extras().pixelated); diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 7c84996427..a46d1137a7 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -9,7 +9,7 @@ use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_doc::inks::{Link, inks, plates, visit_node_colors}; use vectorcraft_doc::overprint::darken_overprints; -use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; +use vectorcraft_doc::{ColorMode, Document, ImageBlob, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings}; @@ -120,7 +120,7 @@ impl<'a> Separator<'a> { for n in nodes { darken_overprints(n, discard_white); self.node(plate, Arc::make_mut(n)); - keep_colorized_pixels(n, &mut colorized); + keep_colorized_pixels(n, &d.images, &mut colorized); } // A colorized image's pixels say where its color prints, on every plate: they are kept // under their own key, and only the color is separated. @@ -153,13 +153,20 @@ fn colorized_key(key: &str) -> String { } /// Point the colorized images in `n`'s subtree at [`colorized_key`], collecting their keys in -/// `keys`. -fn keep_colorized_pixels(n: &mut Arc, keys: &mut BTreeSet) { +/// `keys`. An image whose pixels in `images` don't take its colorize paint +/// ([`ImageBlob::takes_colorize`]) loses the paint instead, and is separated as the image it shows. +fn keep_colorized_pixels(n: &mut Arc, images: &BTreeMap, keys: &mut BTreeSet) { let colorized = |n: &Node| matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some(); if !colorized(n) && n.children().is_none_or(|ch| ch.is_empty()) { return; } let node = Arc::make_mut(n); + if colorized(node) + && let NodeKind::Image(im) = &node.kind + && images.get(&im.key).is_some_and(|b| !b.takes_colorize()) + { + node.extras_mut().colorize = None; + } if colorized(node) && let NodeKind::Image(im) = &mut node.kind { @@ -168,7 +175,7 @@ fn keep_colorized_pixels(n: &mut Arc, keys: &mut BTreeSet) { } if let Some(ch) = node.children_mut() { for c in ch.iter_mut() { - keep_colorized_pixels(c, keys); + keep_colorized_pixels(c, images, keys); } } } diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 406ae08b81..5ec2e813ab 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -166,6 +166,34 @@ fn separations_print_the_image_on_its_ink_plate() { } } +/// A linked image showing the missing-link placeholder is written in the placeholder's own colors +/// though it keeps a colorize paint for its file, and printed separations separate it as an +/// uncolorized image. +#[test] +fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() { + let placeholder = || { + let mut d = doc(ColorMode::Cmyk, None); + let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + d + }; + let plain = placeholder(); + let mut d = placeholder(); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))); + let (colorized, uncolorized) = (images(&pdf(&d)), images(&pdf(&plain))); + assert!(!colorized.is_empty()); + assert_eq!(colorized, uncolorized, "the placeholder as it is, without a soft mask from its coverage"); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + assert!(!job.plates.is_empty()); + for p in &job.plates { + let n = &p.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("the image") }; + assert_eq!((im.key.as_str(), n.extras().colorize.is_none()), ("pic", true), "separated as the image it shows"); + } +} + /// A pixelated colorized image (an envelope's with Anti-Alias off) is written without /// /Interpolate, as an uncolorized one is. #[test] diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index 88d7216380..ab5d831a0b 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -21,6 +21,7 @@ pub(crate) fn blob_key(blob: &vectorcraft_doc::ImageBlob) -> (images::ImageKey, luts: (lut.as_ref().map_or(0, |l| l.1), 0), plates: 0, mip: 0, + tile: None, }; (key, lut.map(|l| l.0), id.size) } @@ -77,18 +78,18 @@ pub(crate) fn mip_level(m: Affine, w: u16, h: u16) -> u8 { } /// Image pixels `pm` (stored as `key`) to draw through `m` (unit square → device pixels), shrunk -/// by halves while still at least as fine as the device pixels ([`images::mip_level`]); the -/// pixels drawn are marked used in the store. -pub(crate) fn image_mip(key: &images::ImageKey, pm: Arc, m: Affine) -> Arc { +/// by halves while still at least as fine as the device pixels ([`images::mip_level`]), and their +/// key; the pixels drawn are marked used in the store. +pub(crate) fn image_mip(key: images::ImageKey, pm: Arc, m: Affine) -> (images::ImageKey, Arc) { let level = mip_level(m, pm.width(), pm.height()); let mut s = images::store(); if level == 0 { - let _ = s.get(key); // Marks the full pixels used (they were only looked at). - return pm; + let _ = s.get(&key); // Marks the full pixels used (they were only looked at). + return (key, pm); } let at = |l: u8| images::ImageKey { mip: l, ..key.clone() }; if let Some(p) = s.get(&at(level)) { - return p; + return (at(level), p); } // From the finest level kept below it. let (mut l, mut cur) = (1..level).rev().find_map(|l| s.peek(&at(l)).map(|p| (l, p))).unwrap_or((0, pm)); @@ -98,7 +99,7 @@ pub(crate) fn image_mip(key: &images::ImageKey, pm: Arc, m: Affine) -> A let half = Arc::new(images::half(&cur)); cur = images::store().insert(at(l), half); } - cur + (at(level), cur) } /// Can image node `n` (`im`) clipped by `region` be painted straight into the region: visible, diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 53de33da6f..8159673cae 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -648,7 +648,7 @@ impl Renderer { AppearanceItem::Stroke(st) => { let st = &*f.stroke(st); let w = effects::stroke::aligned_width(st, effects::stroke::is_closed(ig)); - effects::stroke::line_outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) + crate::stroke::outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) } }; let outset = n.appearance.outset(); diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 987499710f..fae143a239 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -697,11 +697,48 @@ impl Renderer { } else { paint(self, ctx, f); } - // Above the content: inner glows, clipped to its outline. + // Above the content: inner glows, clipped to its outline. An image's glow follows its + // visible pixels, not its frame (#5308). let Some((g, rule)) = content.outline else { return }; + let pixels = matches!(content.node.kind, NodeKind::Image(_)); for fx in rfx { let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue }; let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color)); + if pixels { + self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| { + if let Some((m, o)) = comp { + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(blend_mode(m)), Some(o), None, None); + } + c.set_transform(fr.view); + c.set_fill_rule(fill_rule(rule)); + c.push_clip_layer(g); + c.push_layer(None, None, None, None, Some(filter)); + if !*center { + // Everything around the visible pixels, so the glow bleeds in from their edges. + let pad = blur * 2.0 + 4.0 * fr.px; + c.set_transform(fr.view); + c.set_paint(peniko::Color::BLACK); + c.fill_rect(&g.bounding_box().inflate(pad, pad)); + c.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestOut)), None, None, None); + } + // The glow is cast by the pixels' alpha alone (the filter takes no color from them). + paint(r, c, fr); + if !*center { + c.pop_layer(); + } + c.pop_layer(); + // Only where the image shows, as much as it shows. + c.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestIn)), None, None, None); + paint(r, c, fr); + c.pop_layer(); + c.pop_layer(); + if comp.is_some() { + c.pop_layer(); + } + }); + continue; + } self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| { // The blend layer goes outside the clip: a clip layer is isolated, so a blend // inside it would mix with nothing instead of the content below. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 031c5afa94..74ff632d67 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1076,3 +1076,44 @@ fn photoshop_filters_on_content_larger_than_the_budget() { assert!(lum(img.pixel(190, 100)) >= WHITE - 3 * 25, "{id}: outside {:?}", img.pixel(190, 100)); } } + +/// #5308: an image's Inner Glow follows its visible pixels, not its frame. A 40 × 40 image whose +/// left half is transparent and right half opaque black, on a black page, with a white glow from +/// the edges: the transparent half stays black, and the glow lights the opaque half's left edge +/// (inside the frame), on the single-threaded and the multithreaded renderer alike. +#[test] +fn an_image_inner_glow_follows_its_visible_pixels() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + let rgba: Vec = (0..40 * 40).flat_map(|i| if i % 40 < 20 { [0, 0, 0, 0] } else { [0, 0, 0, 255] }).collect(); + let png = crate::encode::png::encode(&rgba, 40, 40, &Default::default()).unwrap(); + let mut d = Document::new(100.0, 100.0); + d.images.insert("half".into(), ImageBlob::new("image/png", png)); + let im = ImageObject { + key: "half".into(), + width: 40, + height: 40, + xf: Affine::translate((30.0, 30.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.appearance.effects = vec![Effect { + id: "stylize.innerGlow".into(), + params: json!({"color": "#ffffff", "mode": "normal", "opacity": 100, "blur": 4}), + visible: true, + }]; + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let opts = RenderOptions { background: Some([0, 0, 0, 255]), ..Default::default() }; + for threads in [0, 3] { + let mut r = Renderer::new(); + r.threads = threads; + let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + for (x, y) in [(31, 50), (40, 31), (45, 50)] { + assert!(lum(img.pixel(x, y)) < 10, "threads {threads}: no glow on the transparent pixels at ({x}, {y}): {:?}", img.pixel(x, y)); + } + assert!(lum(img.pixel(51, 50)) > 60, "threads {threads}: the glow lights the visible pixels' edge: {:?}", img.pixel(51, 50)); + assert!(lum(img.pixel(68, 50)) > 60, "threads {threads}: and the frame's edge where the pixels reach it: {:?}", img.pixel(68, 50)); + assert!(lum(img.pixel(60, 50)) < lum(img.pixel(51, 50)), "threads {threads}: fading inward"); + } +} diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index a187be25e7..dbdbf00669 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -15,6 +15,7 @@ use std::collections::HashMap; use std::sync::{Arc, LazyLock, Mutex, MutexGuard, Weak}; use vectorcraft_doc::ImageBlob; +use vectorcraft_doc::cmyk::Inks; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -107,6 +108,8 @@ pub(crate) struct ImageKey { pub plates: u64, /// Halved this many times ([`half`]). pub mip: u8, + /// A [`TILE`]-pixel square of the pixels (column, row), when only part of them is made. + pub tile: Option<(u16, u16)>, } /// A blob's content key and whether it holds CMYK inks, worked out once per blob allocation, and @@ -375,21 +378,71 @@ pub fn newly_undecodable<'a>(blobs: impl IntoIterator) -> /// `pm` at half the size (rounded up), each pixel the mean of the 2×2 it covers (the last row and /// column repeat on odd sizes). pub(crate) fn half(pm: &Pixmap) -> Pixmap { - let (w, h) = (pm.width() as usize, pm.height() as usize); + let (data, ow, oh) = half_with(pm.data(), pm.width().into(), pm.height().into(), PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }, |q| PremulRgba8 { + r: mean(q.map(|p| p.r)), + g: mean(q.map(|p| p.g)), + b: mean(q.map(|p| p.b)), + a: mean(q.map(|p| p.a)), + }); + Pixmap::from_parts(data, ow as u16, oh as u16) +} + +/// CMYK image ink amounts `inks` at half the size, as [`half`] halves pixels: each ink the mean +/// of the 2×2 it covers. `None` only if the halved size were no CMYK image's, which a halved +/// image's never is. +pub(crate) fn half_inks(inks: &Inks) -> Option { + let (w, h) = (usize::try_from(inks.width).ok()?, usize::try_from(inks.height).ok()?); + let (data, ow, oh) = + half_with(inks.data.as_chunks::<4>().0, w, h, [0; 4], |q| std::array::from_fn(|c| mean(q.map(|p| p.get(c).copied().unwrap_or(0))))); + Inks::new(u32::try_from(ow).ok()?, u32::try_from(oh).ok()?, data.into_flattened()) +} + +/// `w`×`h` texels `src` at half the size (rounded up, at least 1×1), each the `mean` of the 2×2 +/// it covers (the last row and column repeat on odd sizes; `blank` stands in for texels `src` +/// is short of), and that size. +fn half_with(src: &[T], w: usize, h: usize, blank: T, mean: impl Fn([T; 4]) -> T) -> (Vec, usize, usize) { let (ow, oh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1)); - let src = pm.data(); - let at = |x: usize, y: usize| { - src.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or(PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }) - }; - let mut data = Vec::with_capacity(ow * oh); - for y in 0..oh { - for x in 0..ow { - let q = [at(2 * x, 2 * y), at(2 * x + 1, 2 * y), at(2 * x, 2 * y + 1), at(2 * x + 1, 2 * y + 1)]; - let mean = |c: fn(&PremulRgba8) -> u8| ((q.iter().map(|p| u32::from(c(p))).sum::() + 2) / 4) as u8; - data.push(PremulRgba8 { r: mean(|p| p.r), g: mean(|p| p.g), b: mean(|p| p.b), a: mean(|p| p.a) }); + let at = |x: usize, y: usize| src.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or(blank); + let data = (0..oh) + .flat_map(|y| (0..ow).map(move |x| (x, y))) + .map(|(x, y)| mean([at(2 * x, 2 * y), at(2 * x + 1, 2 * y), at(2 * x, 2 * y + 1), at(2 * x + 1, 2 * y + 1)])) + .collect(); + (data, ow, oh) +} + +/// The mean of four channel values, rounded to nearest. +fn mean(v: [u8; 4]) -> u8 { + ((v.iter().map(|&c| u32::from(c)).sum::() + 2) / 4) as u8 +} + +/// The side of the squares whose colours are made one by one when only part of an image's +/// pixels show ([`ImageKey::tile`]): a large photo zoomed in on is separated, colorized or proofed +/// only where it shows. +pub(crate) const TILE: u32 = 1024; + +/// The `w`×`h` pixels of `pm` from (`x`, `y`). `None` unless they lie inside `pm`. +pub(crate) fn crop(pm: &Pixmap, x: u32, y: u32, w: u32, h: u32) -> Option { + let (pw, ph) = (u32::from(pm.width()), u32::from(pm.height())); + if w == 0 || h == 0 || x.checked_add(w)? > pw || y.checked_add(h)? > ph { + return None; + } + let (stride, x, w) = (pw as usize, x as usize, w as usize); + let rows = pm.data().chunks_exact(stride).skip(y as usize).take(h as usize); + let data: Vec = rows.flat_map(|row| row.get(x..x + w).unwrap_or_default().iter().copied()).collect(); + (data.len() == w * h as usize).then(|| Pixmap::from_parts(data, w as u16, h as u16)) +} + +/// `src` copied into `dst` with its top left at (`x`, `y`), as far as `dst` reaches. +pub(crate) fn paste(dst: &mut Pixmap, src: &Pixmap, x: usize, y: usize) { + let (dw, sw) = (usize::from(dst.width()), usize::from(src.width())); + let dst_rows = dst.data_mut().chunks_exact_mut(dw).skip(y); + for (to, from) in dst_rows.zip(src.data().chunks_exact(sw)) { + let row = to.get_mut(x..).unwrap_or_default(); + let n = row.len().min(from.len()); + if let (Some(to), Some(from)) = (row.get_mut(..n), from.get(..n)) { + to.copy_from_slice(from); } } - Pixmap::from_parts(data, ow as u16, oh as u16) } /// Pixels `pm` colorized with `rgb`: each pixel takes the color, as opaque as the pixel is dark @@ -427,7 +480,7 @@ mod tests { use super::*; fn key(content: &str) -> ImageKey { - ImageKey { content: content.into(), adjust: None, grey: false, tint: None, ink: Ink::Display, luts: (0, 0), plates: 0, mip: 0 } + ImageKey { content: content.into(), adjust: None, grey: false, tint: None, ink: Ink::Display, luts: (0, 0), plates: 0, mip: 0, tile: None } } #[test] diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index d4a5629e56..dee93e9030 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -395,6 +395,22 @@ pub(crate) fn cmyk_pixmap(blob: &ImageBlob, lut: &InkLut) -> Option { inks_pixmap(&blob.cmyk()?, lut) } +/// Whether image pixels `key` are a CMYK image's inks as shown (not adjusted or greyscale), so +/// they paint those inks ([`key_inks`]). +pub(crate) fn shows_own_inks(key: &ImageKey) -> bool { + key.luts.0 != 0 && key.adjust.is_none() && !key.grey +} + +/// The ink amounts behind image pixels `key` when they are CMYK image `blob`'s inks as shown (not +/// adjusted or greyscale): its own inks, halved as its pixels are to `key`'s mip +/// ([`images::half_inks`]). `None` for other pixels. +pub(crate) fn key_inks(key: &ImageKey, blob: Option<&ImageBlob>) -> Option { + if !shows_own_inks(key) { + return None; + } + (0..key.mip).try_fold(blob?.cmyk()?, |inks, _| images::half_inks(&inks)) +} + /// The separation tables of placed images ([`Ink::Cmy`], [`Ink::K`]) and their generation. fn separation() -> (Arc<[ProofLut; 2]>, u64) { cached(&SEPARATE, |cms| { @@ -432,10 +448,7 @@ fn darkened_image(key: &ImageKey, pm: &Arc, ink: Ink, amount: f32, blob: } let base = ink.base(); let display = matches!(base, Ink::Display | Ink::RichBlack); - let raw_cmyk = (key.luts.0 != 0 && key.adjust.is_none() && !key.grey) - .then(|| blob.and_then(ImageBlob::cmyk)) - .flatten() - .filter(|i| (i.width, i.height) == (u32::from(pm.width()), u32::from(pm.height()))); + let raw_cmyk = key_inks(key, blob).filter(|i| (i.width, i.height) == (u32::from(pm.width()), u32::from(pm.height()))); let sep = (!display).then(separation); let shown = (display && raw_cmyk.is_some()).then(display_lut); let mut out = Pixmap::new(pm.width(), pm.height()); @@ -487,8 +500,7 @@ pub(crate) fn ink_image(key: &ImageKey, pm: &Arc, ink: Ink, blob: Option } // CMYK images (shown through the display table) paint their own inks; the others are separated. let size = (pm.width() as u32, pm.height() as u32); - let cmyk = key.luts.0 != 0 && key.adjust.is_none() && !key.grey; - let inks = blob.filter(|_| cmyk).and_then(ImageBlob::cmyk).filter(|i| (i.width, i.height) == size); + let inks = key_inks(key, blob).filter(|i| (i.width, i.height) == size); let planes = [Ink::Cmy, Ink::K].map(|plane| { let mut out = Pixmap::new(pm.width(), pm.height()); if let Some(inks) = &inks { @@ -532,6 +544,7 @@ mod tests { luts: (0, 0), plates: 0, mip: 0, + tile: None, }; let pm = Arc::new(Pixmap::from_parts(vec![PremulRgba8 { r: 204, g: 102, b: 51, a: 255 }, PremulRgba8 { r: 102, g: 51, b: 26, a: 128 }], 2, 1)); diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index 4525a0f1c3..293e824664 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -1,25 +1,39 @@ //! The paths of long paths and compound paths kept by object id, with the boxes of their segments //! and of their miter tips by runs of segments. When an object's anchors move, the renderer changes -//! only the path elements, boxes and tips of the segments that start or end at a moved anchor, -//! instead of making its path again and measuring it whole. +//! only the path elements, boxes and tips of the segments that start or end at a moved anchor. +//! When anchors are added or deleted, or a subpath is closed or opened, it replaces only the path +//! elements of the segments between the first and the last anchor that changed, and measures again +//! only the runs that hold them. When a compound path gains or loses members, or a member gains or +//! loses subpaths, it makes the path of those members again. In each case it does not make the +//! object's path again or measure it whole. use std::sync::Arc; use vectorcraft_doc::{LineJoin, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::bez::has_length; use vectorcraft_geom::path::segment_bounds; -use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Rect, SubPath}; +use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Point, Rect, SubPath}; /// Paths and compound paths with at least this many anchors are kept ([`KeptPath`]). pub(crate) const KEPT_ANCHORS: usize = 1024; -/// Segments measured together into one box. -const RUN: usize = 128; +/// Segments measured together into one box in a subpath measured whole. A run that anchors were +/// added to or deleted from holds more or fewer, and one that grows past twice this is split. +pub(crate) const RUN: usize = 128; + +/// The most subpaths one edit may add anchors to, delete anchors from, close or open: past this, +/// the kept path is made again whole. +const SPLICES: usize = 16; /// The boxes and the miter tips' boxes of a subpath's runs ([`KeptPath::runs`]). #[cfg(test)] pub(crate) type RunBoxes = (Vec>, Vec>); +/// A subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each of its +/// runs ([`KeptPath::layout`]). +#[cfg(test)] +pub(crate) type Layout = ((usize, usize, usize, bool), Vec); + /// A subpath of a kept path. struct Sub { /// Where its MoveTo is in the path's elements. @@ -28,7 +42,9 @@ struct Sub { segs: usize, anchors: usize, closed: bool, - /// The box of each run of [`RUN`] segments ([`segment_bounds`]). + /// The segment after the last of each run of segments. + ends: Vec, + /// The box of each run of segments ([`segment_bounds`]). boxes: Vec>, /// The box of the miter tips of `tips_of` at the joints whose first segment is in each run. tips: Vec>, @@ -72,8 +88,14 @@ pub(crate) fn kept(n: &Node) -> bool { /// Whether anchors `a` and `b` have the same points, bit for bit. fn same(a: &Anchor, b: &Anchor) -> bool { - let bits = |a: &Anchor| [a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits); - bits(a) == bits(b) + same_drawn(a, b, true, true) +} + +/// Whether anchors `a` and `b` have the same point, bit for bit, and the same incoming handle when +/// `h_in` and outgoing handle when `h_out`. +fn same_drawn(a: &Anchor, b: &Anchor, h_in: bool, h_out: bool) -> bool { + let bits = |p: Point| [p.x, p.y].map(f64::to_bits); + bits(a.p) == bits(b.p) && (!h_in || bits(a.h_in) == bits(b.h_in)) && (!h_out || bits(a.h_out) == bits(b.h_out)) } /// The path element of segment `i` of `sp`, as [`SubPath::to_bezpath_into`] writes it. @@ -82,15 +104,62 @@ fn element(sp: &SubPath, i: usize) -> PathEl { if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) } } +/// Element `o` of the elements [`SubPath::to_bezpath_into`] writes for `sp`, a subpath with +/// anchors: its MoveTo, then its segments, then its ClosePath. +fn element_at(sp: &SubPath, o: usize) -> PathEl { + match o { + 0 => PathEl::MoveTo(sp.anchors.first().map_or(Point::ORIGIN, |a| a.p)), + o if o <= sp.segment_count() => element(sp, o - 1), + _ => PathEl::ClosePath, + } +} + /// The point a path element ends at (`None` for a ClosePath). -fn end(el: &PathEl) -> Option { +fn end(el: &PathEl) -> Option { match *el { PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), PathEl::ClosePath => None, } } +/// The ends of the runs of a subpath of `segs` segments measured whole: [`RUN`] segments each. +fn whole_runs(segs: usize) -> Vec { + (1..=segs.div_ceil(RUN)).map(|r| (r * RUN).min(segs)).collect() +} + +/// The paths `ps` written over the `len` elements at `at` in `els`, and their subpaths measured +/// whole with the tips of `st`. `at` moves past them. +fn made_again(ps: &[&PathData], len: usize, els: &mut Vec, at: &mut usize, st: Option<&StrokeLayer>) -> Vec> { + let mut bp = BezPath::new(); + ps.iter().flat_map(|p| &p.subpaths).for_each(|sp| sp.to_bezpath_into(&mut bp)); + let to = (*at + len).min(els.len()); + els.splice((*at).min(to)..to, bp.into_elements()); + let mut measure = |sp: &SubPath| { + let sub = Sub::measured(sp, *at, els, st); + *at += sub.len(); + sub + }; + ps.iter().map(|p| p.subpaths.iter().map(&mut measure).collect()).collect() +} + impl Sub { + /// Subpath `sp`, its MoveTo at `start` in `els`, measured whole, with the tips of `st`. + fn measured(sp: &SubPath, start: usize, els: &[PathEl], st: Option<&StrokeLayer>) -> Self { + let segs = sp.segment_count(); + let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, ends: whole_runs(segs), boxes: vec![], tips: vec![] }; + sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); + if let Some(st) = st { + sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); + } + sub + } + + /// Its elements in the path: none without anchors, otherwise its MoveTo, its segments and + /// its ClosePath when closed. + fn len(&self) -> usize { + if self.anchors == 0 { 0 } else { 1 + self.segs + usize::from(self.closed) } + } + /// Segment `i`, as kurbo's `segments` makes it from the path's elements. fn seg(&self, els: &[PathEl], i: usize) -> Option { let p0 = end(els.get(self.start + i)?)?; @@ -103,12 +172,23 @@ impl Sub { } fn runs(&self) -> usize { - self.segs.div_ceil(RUN) + self.ends.len() + } + + /// The segments of run `r`. + fn range(&self, r: usize) -> std::ops::Range { + let from = r.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0); + from..self.ends.get(r).copied().unwrap_or(from) + } + + /// The run that holds segment `i` (the last run for a segment past the end). + fn run_of(&self, i: usize) -> usize { + self.ends.partition_point(|&e| e <= i).min(self.runs().saturating_sub(1)) } /// The box of the segments of run `r`. fn run_box(&self, els: &[PathEl], r: usize) -> Option { - (r * RUN..((r + 1) * RUN).min(self.segs)).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) + self.range(r).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) } /// The segment with length that follows segment `i` (round to the start when closed), or @@ -140,7 +220,7 @@ impl Sub { /// ([`StrokeLayer::miter_tip`]). fn run_tips(&self, els: &[PathEl], r: usize, st: &StrokeLayer) -> Option { let mut out: Option = None; - for i in r * RUN..((r + 1) * RUN).min(self.segs) { + for i in self.range(r) { let Some(a) = self.seg(els, i).filter(has_length) else { continue }; let Some(b) = self.next_drawn(els, i) else { continue }; if let Some(tip) = st.miter_tip(self.closed, &a, &b) { @@ -149,6 +229,229 @@ impl Sub { } out } + + /// Bring the subpath, its MoveTo now at `at` in `els`, up to date from `was` to `now`, with the + /// tips of `st`. + fn update(&mut self, was: &SubPath, now: &SubPath, at: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + self.start = at; + if was.anchors.len() == now.anchors.len() && was.closed == now.closed { + self.moved(was, now, els, st); + } else if was.anchors.len() < 2 || now.anchors.len() < 2 { + self.remade(now, at, self.len(), els, st); + } else { + let mut span = self.len(); + if self.spliced(was, now, els, st, &mut span).is_none() { + self.remade(now, at, span, els, st); + } + } + } + + /// Write the elements of `now` over the `span` elements at `at` in `els` that the subpath holds, + /// and measure it whole with the tips of `st`. + fn remade(&mut self, now: &SubPath, at: usize, span: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + let to = at.saturating_add(span).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } + + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of + /// the segments that start or end at an anchor that moved are made again, with the boxes of + /// their runs and the tips of those runs and of the runs of the segments with length before + /// them. + fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) { + let (mut first, mut segs) = (false, vec![]); + for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() { + if same(a, b) { + continue; + } + if k >= 1 && k - 1 < self.segs { + segs.push(k - 1); + } + if k == 0 { + first = true; + if self.closed && self.segs > 0 { + segs.push(self.segs - 1); + } + } + if k < self.segs { + segs.push(k); + } + } + if !first && segs.is_empty() { + return; + } + segs.sort_unstable(); + segs.dedup(); + if first && let (Some(a), Some(el)) = (now.anchors.first(), els.get_mut(self.start)) { + *el = PathEl::MoveTo(a.p); + } + for &i in &segs { + if let Some(el) = els.get_mut(self.start + 1 + i) { + *el = element(now, i); + } + } + let els: &[PathEl] = els; + // Many moved: the subpath is measured again whole. + let all = segs.len() * 4 > self.segs; + let mut boxes: Vec = if all { (0..self.runs()).collect() } else { segs.iter().map(|&i| self.run_of(i)).collect() }; + boxes.dedup(); + for r in boxes { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + // A joint's tip changes with its segments and with which segment with length comes next: + // the runs of the moved segments and of the segments with length before them. + let mut runs = vec![]; + let mut whole = all; + for &i in &segs { + runs.push(self.run_of(i)); + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// [`Self::update`] for a subpath of at least two anchors before and after that gained or lost + /// anchors or was closed or opened. Its elements from the first anchor that changed to the + /// last are written again, and the closing segment and the ClosePath when the first or last + /// anchor changed or it was closed or opened; the elements before and after stay. The runs + /// that held the segments written are measured again, with the tips of the runs of the + /// segments with length before them. `span` is the count of elements the subpath holds in + /// `els`, kept up to date as they are written. `None` when the segments and runs kept do not + /// fit `was`: the caller then makes the subpath again from those `span` elements. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>, span: &mut usize) -> Option<()> { + let (n0, n1) = (was.anchors.len(), now.anchors.len()); + let least = n0.min(n1); + // On a subpath open before and after, the handle before the first anchor and the one after + // the last draw nothing. + let open = !was.closed && !now.closed; + let a = was.anchors.iter().zip(&now.anchors).enumerate().take_while(|(i, (x, y))| same_drawn(x, y, !open || *i > 0, true)).count().min(least); + let b = was + .anchors + .iter() + .rev() + .zip(now.anchors.iter().rev()) + .take(least - a) + .enumerate() + .take_while(|(i, (x, y))| same_drawn(x, y, true, !open || *i > 0)) + .count(); + let (s0, s1) = (self.segs, now.segment_count()); + let (c0, c1) = (self.closed, now.closed); + let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); + // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up + // to the first of those between the last `b` anchors. + let (mid0, mid1) = ((1 + n0.checked_sub(b)?).min(1 + s0), (1 + n1.checked_sub(b)?).min(1 + s1)); + // Elements `tail..len` follow the segments between the last `b` anchors: the closing + // segment and the ClosePath. They stay when the anchors either side of the closing segment + // stayed and the subpath was neither closed nor opened. + let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; + let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + // The `old` segments from segment `lo` become `new` segments, and when the tail is written, + // the segments from the one before it do too. + let lo = a.saturating_sub(1); + let (old, new) = (mid0.checked_sub(1)?.checked_sub(lo)?, mid1.checked_sub(1)?.checked_sub(lo)?); + let tail = match keep_tail { + true => None, + false => Some((tail0.checked_sub(1)?, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1), tail1.checked_sub(1)?)), + }; + let at = self.start; + let mut stale = vec![false; self.runs()]; + let tips = st.is_some(); + // Writes elements `e0..e1` of `now` over elements `o0..o1` of the subpath and updates `span`. + let mut write = |els: &mut Vec, (o0, o1): (usize, usize), (e0, e1): (usize, usize)| { + let to = at.saturating_add(o1).min(els.len()); + let from = at.saturating_add(o0).min(to); + els.splice(from..to, (e0..e1).map(|o| element_at(now, o))); + *span = from.saturating_sub(at) + e1.saturating_sub(e0) + at.saturating_add(*span).saturating_sub(to); + }; + if let Some((lo, old, new, _)) = tail { + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (tail0, len0), (tail1, len1)); + } + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (a, mid0), (a, mid1)); + self.anchors = n1; + self.closed = c1; + let els: &[PathEl] = els; + for (r, _) in stale.iter().enumerate().filter(|(_, s)| **s) { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return Some(()) }; + let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); + // Closed or opened: the tips of every joint change when the stroke reaches farther from one + // than from the other. + let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); + for i in [lo].into_iter().chain(tail.map(|(.., last)| last)) { + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + Some(()) + } + + /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that + /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. `None`, and + /// nothing changed, when the runs kept do not hold those `old` segments. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) -> Option<()> { + if old == 0 && new == 0 { + return Some(()); + } + let (r0, r1, first, last) = match self.runs() { + 0 => (0, 0, 0, new), + _ => { + let r0 = self.run_of(lo); + let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; + let last = self.ends.get(r1).copied().unwrap_or(lo + old).checked_add(new)?.checked_sub(old)?; + (r0, r1 + 1, self.range(r0).start, last) + } + }; + let len = last.checked_sub(first)?; + let segs = self.segs.checked_add(new)?.checked_sub(old)?; + let after: Vec = self.ends.get(r1..)?.iter().map(|&e| e.checked_add(new)?.checked_sub(old)).collect::>()?; + if r1 > self.boxes.len() || r1 > stale.len() { + return None; + } + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + self.ends.truncate(r1); + self.ends.extend(after); + self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); + self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); + if tips { + self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); + } + stale.splice(r0..r1, std::iter::repeat_n(true, count)); + self.segs = segs; + Some(()) + } + + /// Measure again the tips of `st` in `runs`, or in every run when `whole`. + fn measure_tips(&mut self, els: &[PathEl], mut runs: Vec, whole: bool, st: &StrokeLayer) { + if whole { + runs = (0..self.runs()).collect(); + } + runs.sort_unstable(); + runs.dedup(); + for r in runs { + let t = self.run_tips(els, r, st); + if let Some(slot) = self.tips.get_mut(r) { + *slot = t; + } + } + } } /// What [`KeptPath::tips`] measures `st`'s tips by: its reach from an open and a closed path and @@ -157,6 +460,24 @@ fn tips_key(st: &StrokeLayer) -> [u64; 3] { [st.side_reach(false).to_bits(), st.side_reach(true).to_bits(), st.miter_limit.to_bits()] } +/// Whether the subpaths of `was` and `now` differ: in number, in anchors or in being closed. +fn differs(was: &PathData, now: &PathData) -> bool { + !std::ptr::eq(was, now) + && (was.subpaths.len() != now.subpaths.len() + || was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| { + w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b)) + })) +} + +/// The subpaths of `was` and `now`, paths with as many subpaths, whose anchors were added or +/// deleted or that were closed or opened. +fn splices(was: &PathData, now: &PathData) -> usize { + if std::ptr::eq(was, now) || was.subpaths.len() != now.subpaths.len() { + return 0; + } + was.subpaths.iter().zip(&now.subpaths).filter(|(w, p)| w.anchors.len() != p.anchors.len() || w.closed != p.closed).count() +} + impl KeptPath { /// The kept path of `n`, or `None` when it has none ([`kept`]). pub(crate) fn new(n: &Arc, stamp: u64) -> Option { @@ -170,12 +491,8 @@ impl KeptPath { for pd in paths(n)? { let mut subs = vec![]; for sp in &pd.subpaths { - let segs = sp.segment_count(); - let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, boxes: vec![], tips: vec![] }; - sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); - if !sp.anchors.is_empty() { - start += 1 + segs + usize::from(sp.closed); - } + let sub = Sub::measured(sp, start, els, None); + start += sub.len(); subs.push(sub); } parts.push(subs); @@ -183,106 +500,90 @@ impl KeptPath { (start == els.len()).then(|| Self { node: n.clone(), path: Arc::new(path), parts, tips_of: None, stamp }) } - /// Bring the path up to date with `n`, a path with the same subpaths and anchor counts as the - /// object it was made from: the elements of the segments that start or end at an anchor that - /// moved are made again, with the boxes of their runs and the tips of those runs and of the - /// runs of the segments with length before them. False, and nothing changed, when `n` has - /// other subpaths, other anchor counts or no kept path. + /// Bring the path up to date with `n`, a later version of the object it was made from. The + /// subpaths whose anchors moved change as [`Sub::moved`] says, and those whose anchors were + /// added or deleted or that were closed or opened as [`Sub::spliced`] says. A member of a + /// compound path that gained or lost subpaths is made again, and so are the members added + /// between the first and the last member that the edit left as they were, when the edit added + /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths, or when the + /// members kept do not pair with those of `n`. A subpath whose segments or runs kept do not fit + /// its anchors before the edit is made again whole ([`Sub::spliced`]). False as well + /// when the path written does not end where the subpaths measured end. The renderer makes the + /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { let old = self.node.clone(); let (Some(was), Some(now)) = (paths(&old), paths(n)) else { return false }; - let shape = - |ps: &[&PathData]| ps.iter().map(|p| p.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::>()).collect::>(); - if !kept(n) || shape(&was) != shape(&now) { + if !kept(n) || self.parts.len() != was.len() || self.parts.iter().zip(&was).any(|(s, p)| s.len() != p.subpaths.len()) { return false; } - // Per subpath whose anchors moved: (member, subpath, whether its first anchor moved, the - // segments that start or end at a moved anchor). - let mut moved: Vec<(usize, usize, bool, Vec)> = vec![]; - for (pi, (w, p)) in was.iter().zip(&now).enumerate() { - if std::ptr::eq(*w, *p) { - continue; - } - for (si, (ws, ps)) in w.subpaths.iter().zip(&p.subpaths).enumerate() { - let Some(sub) = self.parts.get(pi).and_then(|s| s.get(si)) else { return false }; - let (mut first, mut segs) = (false, vec![]); - for (k, (a, b)) in ws.anchors.iter().zip(&ps.anchors).enumerate() { - if same(a, b) { - continue; - } - if k >= 1 && k - 1 < sub.segs { - segs.push(k - 1); - } - if k == 0 { - first = true; - if sub.closed && sub.segs > 0 { - segs.push(sub.segs - 1); - } - } - if k < sub.segs { - segs.push(k); - } - } - if first || !segs.is_empty() { - segs.sort_unstable(); - segs.dedup(); - moved.push((pi, si, first, segs)); - } - } + // The members paired with one of `was`: all when there are as many, otherwise those + // before the first and after the last that is not the same. The others are made again. + let (head, tail) = if was.len() == now.len() { + (was.len(), 0) + } else { + let head = was.iter().zip(&now).take_while(|(w, p)| std::ptr::eq(**w, **p)).count(); + let rest = (was.len() - head).min(now.len() - head); + (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) + }; + // Where the members that are not paired end in `was` and in `now`. + let (Some(was_end), Some(now_end)) = (was.len().checked_sub(tail), now.len().checked_sub(tail)) else { return false }; + if head > was_end || head > now_end { + return false; + } + let paired = |i: usize| match i < head { + true => Some(i), + false => now.len().checked_sub(i).filter(|&back| back <= tail).and_then(|back| was.len().checked_sub(back)), + }; + let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); + if spliced > SPLICES { + return false; } self.node = n.clone(); - if moved.is_empty() { + // Nothing to change: the path is left as it is, shared or not. + if was.len() == now.len() && was.iter().zip(&now).all(|(w, p)| !differs(w, p)) { return true; } + let st = self.tips_of.clone(); + let st = st.as_ref(); let path = Arc::make_mut(&mut self.path); - let els = path.elements_mut(); - for (pi, si, first, segs) in &moved { - let (Some(sub), Some(sp)) = (self.parts.get(*pi).and_then(|s| s.get(*si)), now.get(*pi).and_then(|p| p.subpaths.get(*si))) else { + let mut els = std::mem::take(path).into_elements(); + let mut old_parts: Vec>> = std::mem::take(&mut self.parts).into_iter().map(Some).collect(); + let mut at = 0; + let mut parts = Vec::with_capacity(now.len()); + for (i, p) in now.iter().enumerate() { + if i == head { + // The members of `was` that are not paired give way to those of `now`. + let gone: usize = + old_parts.get_mut(head..was_end).into_iter().flatten().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(now.get(head..now_end).unwrap_or_default(), gone, &mut els, &mut at, st)); + } + let Some(w) = paired(i) else { continue }; + let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; + if was[w].subpaths.len() != p.subpaths.len() { + let len = subs.iter().map(Sub::len).sum(); + parts.extend(made_again(&[*p], len, &mut els, &mut at, st)); continue; - }; - if *first && let (Some(a), Some(el)) = (sp.anchors.first(), els.get_mut(sub.start)) { - *el = PathEl::MoveTo(a.p); } - for &i in segs { - if let Some(el) = els.get_mut(sub.start + 1 + i) { - *el = element(sp, i); + let moved = !std::ptr::eq(was[w], *p); + for (sub, (ws, ps)) in subs.iter_mut().zip(was[w].subpaths.iter().zip(&p.subpaths)) { + if moved { + sub.update(ws, ps, at, &mut els, st); } + sub.start = at; + at += sub.len(); } + parts.push(subs); } - let els = path.elements(); - for (pi, si, _, segs) in moved { - let tips_of = self.tips_of.as_ref(); - let Some(sub) = self.parts.get_mut(pi).and_then(|s| s.get_mut(si)) else { continue }; - // Many moved: the subpath is measured again whole. - let all = segs.len() * 4 > sub.segs; - let mut boxes: Vec = if all { (0..sub.runs()).collect() } else { segs.iter().map(|i| i / RUN).collect() }; - boxes.dedup(); - for r in boxes { - sub.boxes[r] = sub.run_box(els, r); - } - let Some(st) = tips_of else { continue }; - // A joint's tip changes with its segments and with which segment with length comes - // next: the runs of the moved segments and of the segments with length before them. - let mut runs = vec![]; - let mut whole = all; - for &i in &segs { - runs.push(i / RUN); - match sub.prev_drawn(els, i) { - Ok(Some(j)) => runs.push(j / RUN), - Ok(None) => {} - Err(()) => whole = true, - } - } - if whole { - runs = (0..sub.runs()).collect(); - } - runs.sort_unstable(); - runs.dedup(); - for r in runs { - sub.tips[r] = sub.run_tips(els, r, st); - } + if head == now.len() && head < was.len() { + // Members were removed from the end. + let gone: usize = old_parts[head..].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&[], gone, &mut els, &mut at, st)); } - true + let made = at == els.len(); + *path = BezPath::from_vec(els); + self.parts = parts; + made } /// The object's geometric bounds ([`Node::geometric_bounds`]): each path's as @@ -318,9 +619,25 @@ impl KeptPath { self.parts.iter().flatten().flat_map(|s| s.tips.iter().flatten()).copied().reduce(|a, b| a.union(b)) } - /// The boxes and tips kept per run of each subpath, and the stroke the tips were measured for. + /// Each subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each + /// of its runs. #[cfg(test)] - pub(crate) fn runs(&self) -> (Vec, Option) { - (self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(), self.tips_of.clone()) + pub(crate) fn layout(&self) -> Vec { + let runs = |s: &Sub| (0..s.runs()).map(|r| s.range(r).len()).collect(); + self.parts.iter().flatten().map(|s| ((s.start, s.segs, s.anchors, s.closed), runs(s))).collect() + } + + /// The boxes and tips kept per run of each subpath, the same measured again from the path + /// over the same runs, and the stroke the tips were measured for. + #[cfg(test)] + pub(crate) fn runs(&self) -> (Vec, Vec, Option) { + let els = self.path.elements(); + let kept = self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(); + let again = self.parts.iter().flatten().map(|s| { + let boxes = (0..s.runs()).map(|r| s.run_box(els, r)).collect(); + let tips = self.tips_of.as_ref().map_or(vec![], |st| (0..s.runs()).map(|r| s.run_tips(els, r, st)).collect()); + (boxes, tips) + }); + (kept, again.collect(), self.tips_of.clone()) } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index cf9114846c..36c8c1d00c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -24,6 +24,7 @@ pub use paint::{decode_failures, image_decodes, reduced_size}; mod pattern; pub mod placed_document; pub mod proof; +mod stroke; use std::collections::HashMap; use std::sync::Arc; diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index 0eb25b720e..15d5b4644a 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -135,7 +135,7 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt return (want, p); } let size = (u32::from(pm.width()), u32::from(pm.height())); - let raw = blob.filter(|_| key.luts.0 != 0 && key.adjust.is_none() && !key.grey).and_then(ImageBlob::cmyk).filter(|i| (i.width, i.height) == size); + let raw = crate::ink::key_inks(key, blob).filter(|i| (i.width, i.height) == size); let mut out = pm.clone(); match raw { Some(inks) => { diff --git a/crates/render/src/renderer/images.rs b/crates/render/src/renderer/images.rs index 6cabfc5bfc..a604481dd4 100644 --- a/crates/render/src/renderer/images.rs +++ b/crates/render/src/renderer/images.rs @@ -1,14 +1,20 @@ use super::{ - Affine, Arc, BezPath, Document, FillRule, Frame, HashMap, Ink, Node, Pixmap, Rect, RenderContext, Renderer, Shape, blob_key, blob_pixmap, - fill_rule, image_mip, ink, lookup, mip_level, peniko, proof, vello_cpu, + Affine, Arc, BezPath, Document, FillRule, Frame, HashMap, Ink, Node, NodeKind, Pixmap, Rect, RenderContext, Renderer, Shape, blob_key, + blob_pixmap, fill_rule, image_mip, ink, lookup, mip_level, peniko, proof, vello_cpu, }; use crate::images; -/// The color image node `n` is colorized with ([`vectorcraft_doc::NodeExtras::colorize`]), if it -/// is, as `ink` paints it: the display color, or on an ink plane the color's own inks, as a fill -/// of that color paints them. -pub(super) fn image_tint(n: &Node, ink: Ink) -> Option<[u8; 3]> { +/// The color image node `n` of `doc` is colorized with ([`vectorcraft_doc::NodeExtras::colorize`]), +/// if it is and its pixels take it ([`vectorcraft_doc::ImageBlob::takes_colorize`]), as `ink` +/// paints it: the display color, or on an ink plane the color's own inks, as a fill of that color +/// paints them. +pub(super) fn image_tint(doc: &Document, n: &Node, ink: Ink) -> Option<[u8; 3]> { let c = n.extras().colorize.as_deref()?.color()?; + if let NodeKind::Image(im) = &n.kind + && doc.image_blob(im).is_some_and(|b| !b.takes_colorize()) + { + return None; + } Some(ink.rgb(&c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) } @@ -65,42 +71,48 @@ impl Renderer { } } } - kept + kept.map(Shown::whole) } else if let Some(pm) = mips.then(|| self.kept_mip(f, &im.key, im.pixels.as_deref(), outline, tint, unit)).flatten() { - Some(pm) + Some(Shown::whole(pm)) } else { self.image_pixmap(f.doc, &im.key, im.pixels.as_deref(), outline, !mips).map(|(key, pm)| { - let (key, pm) = match tint { - Some(rgb) => colorized_pixmap(key, &pm, rgb, !mips), - None => (key, pm), - }; - // A colorized image is already in the frame's ink ([`image_tint`]), and with - // Separations Preview its color is already the visible plates' (`proof::prepare`). - let (key, pm) = if outline || tint.is_some() { (key, pm) } else { ink::ink_image(&key, &pm, f.ink, f.doc.image_blob(im), !mips) }; - let (key, pm) = match f.plates.filter(|_| !outline && tint.is_none()) { - Some(lut) => proof::plate_image(lut, &key, &pm, f.doc.image_blob(im), !mips), - None => (key, pm), - }; - if mips { image_mip(&key, pm, unit) } else { pm } + // Shrunk first, so what is made of the pixels below is made of the ones drawn: a + // 141-megapixel photo is separated at the size it shows, not at its own (#4155). + let (key, pm) = if mips { image_mip(key, pm, unit) } else { (key, pm) }; + let blob = f.doc.image_blob(im); + // Zoomed in on it, only the tiles in view. + if let Some(window) = in_view(f, im, &key, &pm, outline, tint) { + return window_pixmap(f, &key, &pm, window, outline, tint, blob); + } + Shown::whole(shown_pixmap(f, key, pm, outline, tint, blob)) }) }; - if let Some(pm) = shown { - let sx = im.width as f64 / pm.width().max(1) as f64; - let sy = im.height as f64 / pm.height().max(1) as f64; + if let Some(Shown { pm, level: (lw, lh), at: (ax, ay) }) = shown { + // The pixels drawn are `pm`, from (`ax`, `ay`) of the `lw`×`lh` pixels of the level. + let sx = im.width as f64 / f64::from(lw.max(1)); + let sy = im.height as f64 / f64::from(lh.max(1)); + let drawn = Affine::scale_non_uniform(sx, sy) * Affine::translate((f64::from(ax), f64::from(ay))); + let part = Rect::new( + f64::from(ax) * sx, + f64::from(ay) * sy, + f64::from(ax + u32::from(pm.width())) * sx, + f64::from(ay + u32::from(pm.height())) * sy, + ) + .intersect(rect); let quality = if f.opts.smooth_images && !pixelated { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low }; let sampler = peniko::ImageSampler { quality, ..Default::default() }; ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler }); match area { Some((bp, rule)) => { ctx.set_transform(f.view); - ctx.set_paint_transform(im.xf * Affine::scale_non_uniform(sx, sy)); + ctx.set_paint_transform(im.xf * drawn); ctx.set_fill_rule(fill_rule(*rule)); ctx.fill_path(bp); } None => { ctx.set_transform(f.view * im.xf); - ctx.set_paint_transform(Affine::scale_non_uniform(sx, sy)); - ctx.fill_rect(&rect); + ctx.set_paint_transform(drawn); + ctx.fill_rect(&part); } } ctx.reset_paint_transform(); @@ -298,6 +310,117 @@ impl Renderer { } } +/// Image pixels [`Renderer::draw_image_in`] draws: `pm`, from (`at`) of the `level` pixels of the +/// mip drawn (all of them, or the tiles in view). +struct Shown { + pm: Arc, + level: (u32, u32), + at: (u32, u32), +} + +impl Shown { + /// All of the pixels of a level. + fn whole(pm: Arc) -> Self { + let level = (u32::from(pm.width()), u32::from(pm.height())); + Self { pm, level, at: (0, 0) } + } +} + +/// Image pixels `pm` (kept as `key`) as [`Renderer::draw_image_in`] draws them: in greyscale with +/// `grey` (the outline view's) or colorized with `tint` as they are, else painted with the frame's +/// ink and shown through its Separations Preview plates. Kept with the images under +/// [`shown_key`], and marked used there. +fn shown_pixmap( + f: &Frame, + key: images::ImageKey, + pm: Arc, + grey: bool, + tint: Option<[u8; 3]>, + blob: Option<&vectorcraft_doc::ImageBlob>, +) -> Arc { + let (key, pm) = match tint { + Some(rgb) => colorized_pixmap(key, &pm, rgb), + None => (key, pm), + }; + // A colorized image is already in the frame's ink ([`image_tint`]), and with Separations + // Preview its color is already the visible plates' (`proof::prepare`). + if grey || tint.is_some() { + return pm; + } + let (key, pm) = ink::ink_image(&key, &pm, f.ink, blob, true); + match f.plates { + Some(lut) => proof::plate_image(lut, &key, &pm, blob, true).1, + None => pm, + } +} + +/// The tiles of image pixels `pm` (kept as `key`, the level of image `im` drawn) in the frame's +/// view, as a range of columns and rows, when the pixels' colours are made again +/// ([`shown_pixmap`]: colorized, separated or proofed), more than one tile of them is made, and +/// some are out of view. `None` otherwise: all the pixels are made, as they are for a CMYK image's +/// own inks (made from the whole image's). +fn in_view( + f: &Frame, + im: &vectorcraft_doc::ImageObject, + key: &images::ImageKey, + pm: &Pixmap, + grey: bool, + tint: Option<[u8; 3]>, +) -> Option<([u32; 2], [u32; 2])> { + let made = !grey && (tint.is_some() || ink::ink_key(key, f.ink) != *key || f.plates.is_some()); + let (w, h) = (u32::from(pm.width()), u32::from(pm.height())); + if !made || (w <= images::TILE && h <= images::TILE) || ink::shows_own_inks(key) { + return None; + } + // The view in the level's pixels, a couple wider for smoothing at its edge. + let to_level = (im.xf * Affine::scale_non_uniform(im.width as f64 / f64::from(w), im.height as f64 / f64::from(h))).inverse(); + let v = f.visible; + let corners = [(v.x0, v.y0), (v.x1, v.y0), (v.x1, v.y1), (v.x0, v.y1)].map(|c| to_level * vectorcraft_geom::Point::from(c)); + let (x0, x1) = corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.x), b.max(p.x))); + let (y0, y1) = corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.y), b.max(p.y))); + if ![x0, x1, y0, y1].iter().all(|v| v.is_finite()) { + return None; + } + let tiles = |lo: f64, hi: f64, n: u32| { + let last = n.saturating_sub(1) / images::TILE; + let at = |v: f64| ((v.clamp(0.0, f64::from(n.saturating_sub(1))) as u32) / images::TILE).min(last); + ([at(lo - 2.0), at(hi + 2.0)], last) + }; + let ((cols, last_col), (rows, last_row)) = (tiles(x0, x1, w), tiles(y0, y1, h)); + // All of them in view: made whole, as without tiles. + (cols != [0, last_col] || rows != [0, last_row]).then_some((cols, rows)) +} + +/// The tiles `cols` × `rows` of image pixels `pm` (kept as `key`) as [`shown_pixmap`] makes them, +/// each made and kept on its own ([`images::ImageKey::tile`]), in one pixmap. +fn window_pixmap( + f: &Frame, + key: &images::ImageKey, + pm: &Pixmap, + (cols, rows): ([u32; 2], [u32; 2]), + grey: bool, + tint: Option<[u8; 3]>, + blob: Option<&vectorcraft_doc::ImageBlob>, +) -> Shown { + let (w, h) = (u32::from(pm.width()), u32::from(pm.height())); + let t = images::TILE; + let at = (cols[0] * t, rows[0] * t); + let size = (((cols[1] + 1) * t).min(w) - at.0, ((rows[1] + 1) * t).min(h) - at.1); + let mut window = Pixmap::new(size.0 as u16, size.1 as u16); + for (col, row) in (rows[0]..=rows[1]).flat_map(|r| (cols[0]..=cols[1]).map(move |c| (c, r))) { + let tile_key = images::ImageKey { tile: Some((col as u16, row as u16)), ..key.clone() }; + let (x, y) = (col * t, row * t); + let made = lookup(&shown_key(f, tile_key.clone(), grey, tint), true).or_else(|| { + let part = images::crop(pm, x, y, t.min(w - x), t.min(h - y))?; + Some(shown_pixmap(f, tile_key, Arc::new(part), grey, tint, blob)) + }); + if let Some(made) = made { + images::paste(&mut window, &made, (x - at.0) as usize, (y - at.1) as usize); + } + } + Shown { pm: Arc::new(window), level: (w, h), at } +} + /// The key [`Renderer::draw_image_in`] gives the pixels it draws of image pixels `key`: in /// greyscale with `grey` (the outline view's) or colorized with `tint` as they are, else painted /// with the frame's ink and shown through its Separations Preview plates. @@ -314,10 +437,10 @@ fn shown_key(f: &Frame, key: images::ImageKey, grey: bool, tint: Option<[u8; 3]> } /// Image pixels `pm` (kept as `key`) colorized with `rgb` ([`images::colorized`]), kept with the -/// images, and their key. `touch` marks them used there. -fn colorized_pixmap(key: images::ImageKey, pm: &Pixmap, rgb: [u8; 3], touch: bool) -> (images::ImageKey, Arc) { +/// images and marked used there, and their key. +fn colorized_pixmap(key: images::ImageKey, pm: &Pixmap, rgb: [u8; 3]) -> (images::ImageKey, Arc) { let key = images::ImageKey { tint: Some(rgb), ..key }; - if let Some(p) = lookup(&key, touch) { + if let Some(p) = lookup(&key, true) { return (key, p); } let pm = images::store().insert(key.clone(), Arc::new(images::colorized(pm, rgb))); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index b69ecb10f0..176739c31b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -218,7 +218,7 @@ impl Renderer { && let Some(region) = self.clip_of(&m.art) && shape_masked_image(a, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(a, f.ink), a.extras().pixelated); + self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, a, f.ink), a.extras().pixelated); self.stats.drawn += 1; return; } @@ -486,7 +486,7 @@ impl Renderer { && let NodeKind::Image(im) = &image.kind && plain_image(image, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(image, f.ink), image.extras().pixelated); + self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, image, f.ink), image.extras().pixelated); self.stats.drawn += 1; return; } @@ -536,7 +536,7 @@ impl Renderer { } } NodeKind::Text(t) => self.draw_text(ctx, f, n, t), - NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(n, f.ink), n.extras().pixelated), + NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated), NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { // The instance draws when the frame has room for its art's objects; a symbol diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 9e6080428a..ae65cf8456 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -136,7 +136,7 @@ impl Renderer { ctx.set_fill_rule(peniko::Fill::NonZero); match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => ctx.fill_path(&o), - None => ctx.fill_path(&effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), + None => ctx.fill_path(&crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)), } for head in &pieces.heads { ctx.fill_path(&head.outline); @@ -231,7 +231,7 @@ impl Renderer { }; let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => o, - None => Arc::new(effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), + None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)), }; ctx.set_fill_rule(peniko::Fill::NonZero); for clip in std::iter::once(&*line).chain(pieces.heads.iter().map(|h| &h.outline)) { @@ -277,7 +277,7 @@ impl Renderer { width: f64, ) -> Option> { let level = (f.px * 0.25).log2().floor() as i32; - let expand = || Arc::new(effects::stroke::line_outline(line, st, width, 2f64.powi(level))); + let expand = || Arc::new(crate::stroke::outline(line, st, width, 2f64.powi(level))); if let Some((g, run)) = chars { let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), level); if let Some((kept, outline)) = self.char_strokes.get(&key, self.stamp) @@ -332,7 +332,7 @@ impl Renderer { .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) .flatten(); let (outline, crop) = match cropped { - Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), + Some(part) => (Arc::new(crate::stroke::outline(&part, st, width, tol)), Some(region)), None => (expand(), None), }; self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index a2488556a9..e9dd7f6649 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -304,13 +304,14 @@ impl Renderer { /// decoded once and kept with the images' pixels. fn draw_glyph_image(&mut self, ctx: &mut RenderContext, f: &Frame, image: &vectorcraft_text::GlyphImage, xf: Affine) { let Some((key, pm)) = blob_pixmap(&image.blob, true) else { return }; - let (key, pm) = ink::ink_image(&key, &pm, f.ink, Some(&image.blob), true); - let (key, pm) = match f.plates { - Some(lut) => proof::plate_image(lut, &key, &pm, Some(&image.blob), true), - None => (key, pm), - }; + // Shrunk before it is inked, as images are (`draw_image_in`). let unit = f.view * xf * Affine::scale_non_uniform(image.width as f64, image.height as f64); - let pm = image_mip(&key, pm, unit); + let (key, pm) = image_mip(key, pm, unit); + let (key, pm) = ink::ink_image(&key, &pm, f.ink, Some(&image.blob), true); + let pm = match f.plates { + Some(lut) => proof::plate_image(lut, &key, &pm, Some(&image.blob), true).1, + None => pm, + }; let sx = image.width as f64 / pm.width().max(1) as f64; let sy = image.height as f64 / pm.height().max(1) as f64; let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low }; diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs new file mode 100644 index 0000000000..137bb10abd --- /dev/null +++ b/crates/render/src/stroke.rs @@ -0,0 +1,21 @@ +//! Raster-only stroke fitting: preserve thin curved bands through fill flattening. + +use crate::effects; +use vectorcraft_doc::StrokeLayer; +use vectorcraft_geom::BezPath; + +/// Vello flattens the two sides of a filled stroke independently at 0.25 device pixels. +/// For strokes narrower than four times the raster tolerance, fit and preflatten the +/// band more tightly. Wider strokes and the document/export geometry are unchanged. +pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> BezPath { + if width >= tol * 4.0 { + return effects::stroke::line_outline(line, st, width, tol); + } + // Closed endpoint rounding must not consume a substantial part of a subpixel band. + let fine = (tol / 8.0).min(width / 32.0).max(1e-4); + let outline = effects::stroke::line_outline(line, st, width, fine); + let mut flat = BezPath::new(); + // Keep upstream's per-curve work cap for untrusted or extreme coordinates. + vectorcraft_geom::flatten(outline.iter(), fine, |el| flat.push(el)); + flat +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index b7884026b7..82a1374dab 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -30,6 +30,7 @@ mod placed_document; mod rasterize; mod setup; mod strokegradient; +mod thincoverage; mod tileedge; mod viewraster; mod widthzoom; diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 15eb3c5a02..49e14e5e68 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -142,6 +142,27 @@ fn colorize_dims_with_the_grays() { assert!(px[1].abs_diff(128) <= 3 && px[2].abs_diff(127) <= 3 && px[0] <= 2, "got {px:?}"); } +/// A linked image showing the missing-link placeholder draws it in its own colors though it keeps +/// a colorize paint for its file; a grayscale preview still draws colorized. +#[test] +fn a_colorized_missing_link_placeholder_draws_in_its_own_colors() { + let proxy = |bytes: Vec| { + let bytes = std::sync::Arc::new(bytes); + ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) } + }; + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let sharp = RenderOptions { smooth_images: false, ..Default::default() }; + let placeholder = proxy(vectorcraft_doc::links::missing_placeholder().unwrap()); + // 64 pixels at 0.5 pt: (16, 5) is the light tile, (5, 5) the cross. + let d = doc_of(placeholder, Some(blue.clone()), (64, 64), 0.5); + let out = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &sharp); + assert!(near(out.pixel(16, 5), [236, 236, 236, 255], 2), "the light tile, got {:?}", out.pixel(16, 5)); + assert!(near(out.pixel(5, 5), [200, 60, 60, 255], 2), "the red cross, got {:?}", out.pixel(5, 5)); + let d = doc(proxy(gray_png()), Some(blue)); + let px = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &sharp).pixel(10, 10); + assert!(px[2] >= 250 && px[0] <= 5 && px[1] <= 5, "a grayscale preview takes the color, got {px:?}"); +} + /// Separations Preview shows a spot-colorized image on its ink's plate only. #[test] fn separations_preview_shows_the_image_on_its_spot_plate() { diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 94c5621b97..a2f8b3ad85 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -71,19 +71,43 @@ fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { } let k = r.kept.get(&id).unwrap_or_else(|| panic!("{what}: its path kept")); assert!(std::ptr::eq(Arc::as_ptr(&k.node), n), "{what}: its path kept"); - // The boxes and miter tips kept, run by run, are those of the path measured whole. - let (runs, tips_of) = k.runs(); - let mut whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); - if let Some(st) = &tips_of { - whole.tips(st); + // The subpaths kept are those of the path measured whole, each run holds from one segment to + // twice the segments of a run, and the boxes and miter tips kept, run by run, are those + // measured again from the path. + let whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); + let (layout, fresh) = (k.layout(), whole.layout()); + assert!(layout.iter().map(|l| l.0).eq(fresh.iter().map(|l| l.0)), "{what}: the same subpaths as the path measured whole"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&fresh) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); +} + +/// Check `d` as [`check`] does, then the document before the edit (undone) and `d` again (redone). +fn check_undo(r: &mut Renderer, before: &Document, d: &Document, id: NodeId, what: &str) { + check(r, d, id, what); + check(r, before, id, &format!("{what}, undone")); + check(r, d, id, &format!("{what}, redone")); +} + +/// The members of compound path `id` of `d`. +fn members(d: &mut Document, id: NodeId) -> &mut Vec> { + match d.node_mut(id).map(|n| &mut n.kind) { + Some(NodeKind::Compound { children, .. }) => children, + _ => panic!("a compound path"), } - assert!(runs == whole.runs().0, "{what}: the same boxes and tips as the path measured whole"); } fn path_of(d: &mut Document, id: NodeId) -> &mut PathData { d.node_mut(id).and_then(|n| n.path_data_mut()).unwrap() } +fn corner(x: f64, y: f64) -> Anchor { + Anchor::corner(Point::new(x, y)) +} + fn moved(a: &mut Anchor, by: Vec2) { *a = a.transform(Affine::translate(by)); } @@ -194,6 +218,352 @@ fn edits_in_runs_of_segments_without_length_measure_as_when_the_path_is_made_aga } } +#[test] +fn a_long_path_draws_and_culls_after_anchors_are_added_or_deleted_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let path = PathData::new(vec![ + zigzag(3000, 0.0), + ring(1200, Point::new(12_000.0, 15.0), 45.0), + SubPath::new(vec![Anchor::corner(Point::new(11_990.0, 20.0))], false), + SubPath::new(vec![], false), + SubPath::new(vec![Anchor::corner(Point::new(11_995.0, 0.0)), Anchor::corner(Point::new(12_005.0, 30.0))], false), + ]); + let n = Node::path(d.alloc_id(), path, look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt), stroke(14.0, LineJoin::Round, LineCap::Round)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 28] = [ + // Anchor 1,152, a corner at (9,032, 30), ends the segments of the first nine runs: the + // joint there is in the run before. + ("an anchor added where a run of segments starts", |p| p.subpaths[0].anchors.insert(1153, corner(9_036.0, -30.0))), + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), + ("an anchor added at the start", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 30.0))), + ("an anchor added at the end", |p| p.subpaths[0].anchors.push(corner(24_100.0, 0.0))), + ("the first anchor deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("an anchor added onto the one before it", |p| { + let a = p.subpaths[0].anchors[1499]; + p.subpaths[0].anchors.insert(1500, Anchor::corner(a.p)); + }), + ("300 anchors deleted", |p| _ = p.subpaths[0].anchors.drain(1100..1400)), + ("400 anchors added", |p| { + let at: Vec = (0..400).map(|i| corner(8_800.0 + f64::from(i) * 0.5, if i % 2 == 0 { -20.0 } else { 50.0 })).collect(); + p.subpaths[0].anchors.splice(1100..1100, at); + }), + ("anchors moved and others deleted", |p| { + p.subpaths[0].anchors[10] = corner(80.0, -40.0); + p.subpaths[0].anchors.drain(2000..2010); + }), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ("an anchor added at the start of the closed subpath", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 60.0))), + ("an anchor added after the first of the closed subpath", |p| p.subpaths[0].anchors.insert(1, corner(-20.0, -30.0))), + ("an anchor added at the end of the closed subpath", |p| p.subpaths[0].anchors.push(corner(24_000.0, 60.0))), + ("the first anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("the subpath opened", |p| p.subpaths[0].closed = false), + ("an anchor of the ring added in the view", |p| p.subpaths[1].anchors.insert(300, corner(12_010.0, 10.0))), + ("an anchor of the ring deleted", |p| _ = p.subpaths[1].anchors.remove(600)), + ("the ring opened", |p| p.subpaths[1].closed = false), + ("the ring closed", |p| p.subpaths[1].closed = true), + ("the one-anchor subpath given a second anchor", |p| p.subpaths[2].anchors.push(corner(12_000.0, 40.0))), + ("the second anchor deleted again", |p| _ = p.subpaths[2].anchors.pop()), + ("the one-anchor subpath emptied", |p| p.subpaths[2].anchors.clear()), + ("the empty subpath given an anchor", |p| p.subpaths[3].anchors.push(corner(12_015.0, 5.0))), + ("the two-anchor subpath closed", |p| p.subpaths[4].closed = true), + ("an anchor deleted from the two-anchor subpath", |p| _ = p.subpaths[4].anchors.remove(0)), + ]; + for (what, edit) in edits { + let before = d.clone(); + edit(path_of(&mut d, id)); + check_undo(&mut r, &before, &d, id, what); + } +} + +#[test] +fn a_long_compound_path_draws_and_culls_after_members_are_added_or_removed_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let none = Appearance::default(); + let member = |d: &mut Document, p: PathData| Arc::new(Node::path(d.alloc_id(), p, none.clone())); + let children = vec![ + member(&mut d, PathData::single(zigzag(1500, 6000.0))), + member(&mut d, PathData::single(ring(1500, Point::new(12_000.0, 15.0), 45.0))), + member(&mut d, PathData::single(SubPath::new(vec![Anchor::corner(Point::new(11_980.0, 0.0))], false))), + ]; + let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![stroke(4.0, LineJoin::Miter, LineCap::Square)]).into(); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + let edits: [(&str, PathData, usize); 4] = [ + ("a member added at the end", PathData::single(ring(40, Point::new(12_010.0, 20.0), 8.0)), 3), + ("a member added at the start", PathData::single(zigzag(30, 11_950.0)), 0), + ("a member added between", PathData::new(vec![]), 2), + ("a member of two subpaths added between", PathData::new(vec![ring(5, Point::new(11_990.0, 25.0), 4.0), zigzag(3, 11_970.0)]), 1), + ]; + for (what, p, at) in edits { + let before = d.clone(); + let m = member(&mut d, p); + members(&mut d, id).insert(at, m); + check_undo(&mut r, &before, &d, id, what); + } + // Seven members: the first, the last, then the third removed. + for (what, at) in [("the first member removed", 0), ("the last member removed", 5), ("a member removed between", 2)] { + let before = d.clone(); + members(&mut d, id).remove(at); + check_undo(&mut r, &before, &d, id, what); + } + // Left: the member of two subpaths, the zigzag, the ring and the one-anchor member. + let ids: Vec = members(&mut d, id).iter().map(|m| m.id).collect(); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths.push(SubPath::new(vec![corner(12_020.0, 30.0)], false)); + check_undo(&mut r, &before, &d, id, "a subpath added to a member"); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths[0].anchors.insert(10, corner(12_000.0, 60.0)); + path_of(&mut d, ids[2]).subpaths[0].anchors.remove(700); + check_undo(&mut r, &before, &d, id, "anchors added and deleted in two members"); +} + +#[test] +fn adding_and_deleting_anchors_of_a_long_path_changes_its_kept_path_in_place() { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::single(zigzag(3000, 0.0)), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let kept = |r: &Renderer| r.kept.get(&id).map(|k| Arc::as_ptr(&k.path) as usize); + let before = kept(&r); + assert!(before.is_some(), "the path is kept"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 3] = [ + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1500, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1700)), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ]; + for (what, edit) in edits { + edit(path_of(&mut d, id)); + check(&mut r, &d, id, what); + assert_eq!(kept(&r), before, "{what}: the kept path changed in place"); + } + // An edit that leaves the anchors as they were leaves the kept path as it is, also while + // something else holds it. + let held = r.kept.get(&id).map(|k| k.path.clone()).unwrap(); + d.node_mut(id).unwrap().appearance = look(vec![stroke(8.0, LineJoin::Miter, LineCap::Butt)]).into(); + check(&mut r, &d, id, "the stroke changed"); + assert!(Arc::ptr_eq(&held, &r.kept.get(&id).unwrap().path), "the stroke changed: the kept path left as it is"); +} + +#[test] +fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_measures_one_run_again() { + let mut d = Document::new(1000.0, 1000.0); + let mut sp = zigzag(3000, 0.0); + if let Some(a) = sp.anchors.last_mut() { + a.h_out = a.p + Vec2::new(3.0, 4.0); + } + assert!(sp.anchors[0].has_in(), "the first anchor has a handle before it"); + let n = Node::path(d.alloc_id(), PathData::single(sp), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let runs = |r: &Renderer| r.kept.get(&id).map(|k| k.layout()[0].1.clone()).unwrap(); + let before = runs(&r); + // Anchor 1,500 deleted, and the handles before the first anchor and after the last cleared: + // they draw nothing on an open subpath. + let p = &mut path_of(&mut d, id).subpaths[0]; + p.anchors.remove(1500); + if let Some(a) = p.anchors.first_mut() { + a.h_in = a.p; + } + if let Some(a) = p.anchors.last_mut() { + a.h_out = a.p; + } + check(&mut r, &d, id, "an anchor deleted and the end handles cleared"); + let after = runs(&r); + let changed: Vec = (0..before.len().max(after.len())).filter(|&i| before.get(i) != after.get(i)).collect(); + assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); +} + +/// Numbers from a fixed seed (a linear congruential generator). +struct Seeded(u64); + +impl Seeded { + /// A number below `m` (0 when `m` is 0). + fn below(&mut self, m: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as usize % m.max(1) + } + + /// A whole number of points from -`r` to `r`. + fn offset(&mut self, r: usize) -> f64 { + self.below(2 * r + 1) as f64 - r as f64 + } + + /// Where in a subpath of `n` anchors to edit: at the start, at the end, where a run of segments + /// ends, or anywhere. + fn at(&mut self, n: usize) -> usize { + match self.below(4) { + 0 => self.below(3).min(n), + 1 => n.saturating_sub(self.below(3)), + 2 => (crate::kept_paths::RUN * (1 + self.below(24)) + self.below(3)).min(n), + _ => self.below(n + 1), + } + } +} + +/// An anchor to add after `before`: on it (a segment without length), a corner near it, or a +/// smooth anchor near it. +fn anchor_after(g: &mut Seeded, before: Point) -> Anchor { + let p = before + Vec2::new(g.offset(20), g.offset(40)); + match g.below(5) { + 0 => Anchor::corner(before), + 1 => Anchor::smooth(p, p + Vec2::new(g.offset(6), g.offset(6))), + _ => Anchor::corner(p), + } +} + +/// Edit `p` at random: anchors added or deleted at the start, middle or end of a subpath, a +/// subpath closed or opened, an anchor or a handle moved, or many anchors moved. Says what it did. +fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { + let s = g.below(p.subpaths.len()); + let Some(sp) = p.subpaths.get_mut(s) else { return "nothing".into() }; + let n = sp.anchors.len(); + match g.below(6) { + 0 | 1 => { + let (at, k) = (g.at(n), 1 + g.below(3)); + for j in 0..k { + let before = sp.anchors.get((at + j).saturating_sub(1)).map_or(Point::new(12_000.0, 15.0), |a| a.p); + let a = anchor_after(g, before); + sp.anchors.insert(at + j, a); + } + format!("{k} anchors added at {at} of subpath {s} of {n}") + } + 2 | 3 if n > 0 => { + let at = g.at(n - 1); + let k = (1 + g.below(3)).min(n - at); + sp.anchors.drain(at..at + k); + format!("{k} anchors deleted at {at} of subpath {s} of {n}") + } + 4 => { + sp.closed = !sp.closed; + format!("subpath {s} of {n} closed: {}", sp.closed) + } + _ if n > 0 => { + let at = g.below(n); + match g.below(3) { + 0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))), + 1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)), + _ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), + } + format!("anchors moved at {at} of subpath {s} of {n}") + } + _ => "nothing".into(), + } +} + +/// Bring `k` up to date with `n` and check that it holds what [`KeptPath::new`] makes from `n`: +/// the same path elements and subpaths, runs that hold each subpath's segments, the boxes and miter +/// tips of `st` measured again over its runs, and the same bounds and tips in all. +fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &StrokeLayer, what: &str) { + assert!(k.update(n), "{what}: brought up to date"); + let mut fresh = crate::kept_paths::KeptPath::new(n, 0).unwrap_or_else(|| panic!("{what}: kept")); + assert!(*k.path == *fresh.path, "{what}: the same path elements"); + let (layout, whole) = (k.layout(), fresh.layout()); + assert!(layout.iter().map(|l| l.0).eq(whole.iter().map(|l| l.0)), "{what}: the same subpaths: {layout:?}"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&whole) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); + assert_eq!(k.geometric(), fresh.geometric(), "{what}: the same bounds"); + assert_eq!(k.tips(st), fresh.tips(st), "{what}: the same miter tips"); +} + +#[test] +fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() { + let st = stroke(6.0, LineJoin::Miter, LineCap::Butt); + let mut g = Seeded(5744); + let closed = |sp: SubPath| SubPath::new(sp.anchors, true); + let path = PathData::new(vec![ + zigzag(2, 11_990.0), + closed(zigzag(3, 12_000.0)), + zigzag(7, 11_960.0), + closed(zigzag(40, 11_800.0)), + ring(300, Point::new(12_000.0, 15.0), 60.0), + zigzag(3000, 0.0), + closed(zigzag(2000, 4000.0)), + ]); + let mut n = Arc::new(Node::path(NodeId(1), path, look(vec![st.clone()]))); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let what = random_edit(&mut g, next.path_data_mut().unwrap()); + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + +#[test] +fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes() { + let st = stroke(4.0, LineJoin::Miter, LineCap::Square); + let mut g = Seeded(1050); + let ids = std::cell::Cell::new(10); + let member = |p: PathData| { + ids.set(ids.get() + 1); + Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default())) + }; + let children = vec![ + member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), + member(PathData::single(zigzag(3000, 0.0))), + member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))), + member(PathData::single(zigzag(2, 12_020.0))), + ]; + let mut n = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![st.clone()]).into(); + let mut n = Arc::new(n); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let NodeKind::Compound { children, .. } = &mut next.kind else { panic!("a compound path") }; + let what = match g.below(8) { + 0 => { + let at = [0, children.len(), g.below(children.len() + 1)][g.below(3)]; + let size = [1, 2, 4, 30, 200][g.below(5)]; + let mut sp = zigzag(size, 11_900.0 + g.offset(100)); + sp.closed = g.below(2) == 0; + children.insert(at, member(PathData::single(sp))); + format!("a member of {size} anchors added at {at}") + } + // The member of 3,000 anchors stays, so that the path stays kept. + 1 if children.len() > 2 => { + let at = [0, children.len() - 1, g.below(children.len())][g.below(3)]; + if children[at].path_data().is_some_and(|p| p.subpaths.iter().map(|s| s.anchors.len()).sum::() > 1000) { + "nothing".into() + } else { + children.remove(at); + format!("member {at} removed") + } + } + 2 => { + let at = g.below(children.len()); + let m = Arc::make_mut(&mut children[at]).path_data_mut().unwrap(); + m.subpaths.push(zigzag(1 + g.below(4), 12_030.0)); + format!("a subpath added to member {at}") + } + _ => { + let at = g.below(children.len()); + let what = random_edit(&mut g, Arc::make_mut(&mut children[at]).path_data_mut().unwrap()); + format!("member {at}: {what}") + } + }; + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index f0c4b40e1f..d8b267cb9e 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2422,3 +2422,125 @@ fn compound_paths_draw_from_kept_paths_and_let_old_ones_go() { assert!(r.geom.len() < 1024); assert_eq!(Arc::strong_count(&old), 1, "the renderer no longer keeps the compound path drawn before the move"); } + +/// A `w`×`h` CMYK document showing `blob` as image `key` of `w`×`h` pixels, one point a pixel. +fn cmyk_doc_with(key: &str, blob: ImageBlob, w: u32, h: u32) -> Document { + let mut d = Document::new_with_mode(w as f64, h as f64, vectorcraft_doc::ColorMode::Cmyk); + d.images.insert(key.into(), blob); + let (id, layer) = (d.alloc_id(), d.layers[0].id); + let im = ImageObject { key: key.into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + d +} + +/// #4155: an image drawn reduced on the ink planes is separated from the mip it draws, never at +/// its full size. Separating a 141-megapixel image for each plane before shrinking it took +/// seconds a frame, and its full-size planes overflowed the store, so every frame did it again. +#[test] +fn a_reduced_image_is_separated_from_its_mip_not_its_full_pixels() { + let _fonts = fonts_steady(); + let d = cmyk_doc_with("img", ImageBlob::new("image/png", png(64, 64, 111)), 64, 64); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let _ = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 64.0, 64.0), 0.25, &on); + let full = blob_key(&d.images["img"]).0; + let quarter = images::ImageKey { mip: 2, ..full.clone() }; + let s = images::store(); + for plane in [Ink::Cmy, Ink::K] { + assert!(s.peek(&ink::ink_key(&full, plane)).is_none(), "the {plane:?} plane was made at full size"); + let made = s.peek(&ink::ink_key(&quarter, plane)).unwrap_or_else(|| panic!("no {plane:?} plane of the quarter mip")); + assert_eq!((made.width(), made.height()), (16, 16)); + } +} + +/// A CMYK image drawn reduced paints its own inks, averaged, as at full size: not its displayed +/// colours separated again, which would change how much of its dark is black ink. +#[test] +fn a_reduced_cmyk_image_paints_its_own_inks() { + let _fonts = fonts_steady(); + // Inks a separation of their displayed colour would not give back: rich in black. + let ink = [0u8, 102, 255, 140]; + let blob = ImageBlob::cmyk_tiff(&vectorcraft_doc::cmyk::Inks::new(8, 8, ink.repeat(64)).unwrap()).unwrap(); + let d = cmyk_doc_with("inks", blob, 8, 8); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 8.0, 8.0), 0.25, &on); + for px in inks.as_chunks::<4>().0 { + assert!(px.iter().zip(ink).all(|(a, b)| a.abs_diff(b) <= 1), "{px:?} vs {ink:?}"); + } +} + +/// On the ink planes, a reduced image shows the average of its pixels as they show at full size: +/// 1-pixel black and white lines show as the mid grey they make. Separating the full pixels and +/// averaging the planes made that grey a dark brown, 44 levels off. +#[test] +fn a_reduced_image_on_the_ink_planes_shows_its_average() { + let _fonts = fonts_steady(); + let lines = image::RgbaImage::from_fn(64, 64, |x, _| image::Rgba(if x % 2 == 0 { [0, 0, 0, 255] } else { [255; 4] })); + let mut bytes = vec![]; + lines.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let mut d = cmyk_doc_with("lines", ImageBlob::new("image/png", bytes), 64, 64); + // Transparency beside the image: the document blends in CMYK, drawing on its ink planes. + let shape = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 0.0, 110.0, 10.0)); + let mut veil = Node::path(d.alloc_id(), shape, vectorcraft_doc::Appearance::basic(Paint::solid(Color::gray(0.5)), Paint::None, 0.0)); + veil.opacity = 0.5; + let layer = d.layers[0].id; + d.insert(Some(layer), 1, veil).unwrap(); + let full = Renderer::new().render(&d, 64, 64, Affine::IDENTITY, &RenderOptions::default()).pixels; + let on = RenderOptions { image_mips: true, ..Default::default() }; + let reduced = Renderer::new().render(&d, 16, 16, Affine::scale(0.25), &on).pixels; + for (i, px) in reduced.as_chunks::<4>().0.iter().enumerate() { + let (bx, by) = (i % 16 * 4, i / 16 * 4); + let block = |c: usize| (0..16).map(|j| u32::from(full[((by + j / 4) * 64 + bx + j % 4) * 4 + c])).sum::().div_ceil(16) as u8; + let want = [block(0), block(1), block(2)]; + assert!(px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2), "pixel {i}: {px:?}, the full frame averages {want:?}"); + } +} + +/// A `w`×`h` PNG with a different colour in every pixel, so a pixel drawn from the wrong place +/// shows; its pixels depend on `seed` (each test its own image: the store is shared). +fn varied_png(w: u32, h: u32, seed: u8) -> Vec { + let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 5 + y) as u8, (x / 3 + y * 7) as u8, (x ^ y) as u8 ^ seed, 255])); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// #4155: an image drawn larger than a tile with its colours made again (here separated into ink +/// planes) has them made only for the tiles in view. Zoomed in on a 141-megapixel photo, the whole +/// photo was separated for every view, taking seconds each time. +#[test] +fn a_zoomed_in_image_is_separated_only_where_it_shows() { + let _fonts = fonts_steady(); + let (w, h) = (2 * images::TILE + 100, 40); + let d = cmyk_doc_with("wide", ImageBlob::new("image/png", varied_png(w, h, 1)), w, h); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let _ = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 300.0, 40.0), 1.0, &on); + let full = blob_key(&d.images["wide"]).0; + let s = images::store(); + for plane in [Ink::Cmy, Ink::K] { + assert!(s.peek(&ink::ink_key(&full, plane)).is_none(), "the whole {plane:?} plane was made"); + let tile = |col: u16| ink::ink_key(&images::ImageKey { tile: Some((col, 0)), ..full.clone() }, plane); + assert!(s.peek(&tile(0)).is_some(), "the {plane:?} plane of the tile in view was made"); + assert!(s.peek(&tile(1)).is_none() && s.peek(&tile(2)).is_none(), "tiles out of view were made"); + } +} + +/// An image drawn from tiles draws the pixels it draws whole, across the tiles' edges too. +#[test] +fn a_tiled_image_draws_what_the_whole_image_draws() { + let _fonts = fonts_steady(); + let (w, h) = (2 * images::TILE + 100, 40); + let d = cmyk_doc_with("seams", ImageBlob::new("image/png", varied_png(w, h, 2)), w, h); + let on = RenderOptions { image_mips: true, ..Default::default() }; + // Across the edge between the first two tiles. + let (x0, x1) = (f64::from(images::TILE) - 150.0, f64::from(images::TILE) + 150.0); + let drawn = Renderer::new().render_region_inks(&d, Rect::new(x0, 0.0, x1, 40.0), 1.0, &on); + let (key, full) = crate::blobs::blob_pixmap(&d.images["seams"], false).unwrap(); + let plane = |ink| ink::ink_image(&key, &full, ink, d.images.get("seams"), false).1; + let bytes = |pm: &Pixmap| pm.data().iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect::>(); + let whole = ink::amounts(&bytes(&plane(Ink::Cmy)), &bytes(&plane(Ink::K))); + for (i, got) in drawn.as_chunks::<4>().0.iter().enumerate() { + let (x, y) = (x0 as usize + i % 300, i / 300); + let want = &whole[(y * w as usize + x) * 4..][..4]; + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(*b) <= 1), "pixel ({x}, {y}): {got:?}, whole {want:?}"); + } +} diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs new file mode 100644 index 0000000000..05bbc23573 --- /dev/null +++ b/crates/render/src/tests/thincoverage.rs @@ -0,0 +1,124 @@ +use super::*; +use crate::stroke::outline as raster_stroke_outline; +use vectorcraft_doc::StrokeLayer; + +/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking +/// only the outline geometry misses raster flattening that cancels its two nearby contours. +#[test] +fn fractional_curved_strokes_retain_coverage_between_notches() { + for rounded in [false, true] { + for (weight, rotation, phase, opacity) in + [(1.0 / 3.0, 0.0, 0.0, 1.0), (0.5, 30.0, 0.25, 1.0), (0.75, 75.0, 0.5, 0.5), (1.0, 135.0, 0.75, 1.0)] + { + let mut d = Document::new(1000.0, 1000.0); + let mut path = BezPath::new(); + let mut radius = 450.0; + let mut previous = 0.0; + path.move_to((950.0, 500.0)); + let mut arcs = Vec::new(); + let point = |r: f64, a: f64| vectorcraft_geom::Point::new(500.0 + r * a.cos(), 500.0 + r * a.sin()); + for degrees in [17.0_f64, 64.0, 119.0, 147.0, 201.0, 242.0, 313.0, 360.0] { + let a = degrees.to_radians(); + let k = 4.0 / 3.0 * ((a - previous) / 4.0).tan(); + let start = point(radius, previous); + let end = point(radius, a); + path.curve_to( + start + kurbo::Vec2::new(-previous.sin(), previous.cos()) * (k * radius), + end + kurbo::Vec2::new(a.sin(), -a.cos()) * (k * radius), + end, + ); + arcs.push((radius, previous + 0.06, a - 0.06)); + radius = if radius == 450.0 { 438.0 } else { 450.0 }; + path.line_to(point(radius, a)); + previous = a; + } + path.close_path(); + // Match a parser's f32 coordinate round-trip and exact closed endpoint as well as the + // original f64 construction. A near-coincident final anchor must not hide this case. + let q = |p: kurbo::Point| kurbo::Point::new(f64::from(p.x as f32), f64::from(p.y as f32)); + let path = if rounded { + BezPath::from_vec( + path.iter() + .map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(q(p)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(q(p)), + kurbo::PathEl::QuadTo(a, b) => kurbo::PathEl::QuadTo(q(a), q(b)), + kurbo::PathEl::CurveTo(a, b, c) => kurbo::PathEl::CurveTo(q(a), q(b), q(c)), + kurbo::PathEl::ClosePath => kurbo::PathEl::ClosePath, + }) + .collect(), + ) + } else { + path + }; + { + use kurbo::{ParamCurve, ParamCurveDeriv}; + let st = StrokeLayer::new(Paint::solid(Color::BLACK), weight); + let outline = raster_stroke_outline(&path, &st, weight.max(0.5), 0.25); + for segment in path.segments() { + if let kurbo::PathSeg::Cubic(c) = segment { + for step in 1..20 { + let t = step as f64 / 20.0; + let p = c.eval(t); + let v = c.deriv().eval(t).to_vec2().normalize(); + let n = kurbo::Vec2::new(-v.y, v.x); + for side in [-1.0, 1.0] { + assert_ne!(outline.winding(p + n * (side * weight.max(0.5) * 0.4)), 0, "missing geometric band, rounded={rounded}"); + assert_eq!(outline.winding(p + n * (side * weight.max(0.5) * 0.6)), 0, "outside geometric band, rounded={rounded}"); + } + } + } + } + } + let mut node = Node::path( + d.alloc_id(), + vectorcraft_geom::PathData::from_bezpath(&path), + Appearance::basic(Paint::None, Paint::solid(Color::BLACK), weight), + ); + node.opacity = opacity; + d.insert(Some(d.layers[0].id), 0, node).unwrap(); + let view = + Affine::translate((500.0 + phase, 500.0 + phase)) * Affine::rotate(f64::to_radians(rotation)) * Affine::translate((-500.0, -500.0)); + let image = + Renderer::new().render(&d, 1000, 1000, view, &RenderOptions { background: Some([255; 4]), artboards: false, ..Default::default() }); + // Collect only the measured radial bands once, in the original row-major order. + // Each bin then adds the same pixels in the same order without rescanning the image. + let mut ring = Vec::new(); + for y in 0..1000 { + for x in 0..1000 { + let dx = x as f64 + 0.5 - 500.0 - phase; + let dy = y as f64 + 0.5 - 500.0 - phase; + let distance = dx.hypot(dy); + if !arcs.iter().any(|(r, _, _)| (distance - r).abs() <= 3.0) { + continue; + } + let angle = (dy.atan2(dx) - f64::to_radians(rotation)).rem_euclid(std::f64::consts::TAU); + ring.push((distance, angle, f64::from(255 - image.pixel(x, y)[0]) / 255.0)); + } + } + for (r, begin, end) in arcs { + // 3 bins per arc avoid averaging away a washed-out section. The expected ink area + // is independently r * angle * displayed weight, with the existing half-pixel floor. + for bin in 0..3 { + let lo = begin + (end - begin) * bin as f64 / 3.0; + let hi = begin + (end - begin) * (bin + 1) as f64 / 3.0; + let mut ink = 0.0; + for &(distance, angle, value) in &ring { + if (distance - r).abs() > 3.0 { + continue; + } + if angle >= lo && angle < hi { + ink += value; + } + } + let expected = r * (hi - lo) * weight.max(0.5) * f64::from(opacity); + assert!( + (ink / expected - 1.0).abs() < 0.15, + "weight {weight}, rotation {rotation}, phase {phase}, opacity {opacity}, arc {r} {lo}..{hi}: coverage {}", + ink / expected + ); + } + } + } + } +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 44b8c696e4..7c506d2bb3 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -17,6 +17,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } +vectorcraft-pathops = { workspace = true } kurbo = { workspace = true } usvg = { workspace = true } thiserror = { workspace = true } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 7be7483919..adcd3fd259 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeLayer, Writer, Written, - WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, + Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, + Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `` def and the instance transforms that can `` it. @@ -32,6 +32,22 @@ pub(crate) struct Reuse { /// How deep symbols may sit in one another's art (deeper instances are left out). const MAX_SYMBOL_NEST: u32 = 8; +/// Gradient placement and outside-aligned stroke masks need the shape's geometric box. +/// Solid colours and patterns do not, so avoid walking their path geometry for a box. +fn export_shape_bounds(n: &Node) -> Option { + n.appearance + .items + .iter() + .any(|item| match item { + AppearanceItem::Fill(f) => f.visible && matches!(f.paint, Paint::Gradient(_)), + AppearanceItem::Stroke(s) => { + s.visible && s.width > 0.0 && !s.paint.is_none() && (matches!(s.paint, Paint::Gradient(_)) || s.align == StrokeAlign::Outside) + } + }) + .then(|| n.geometric_bounds()) + .flatten() +} + impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; @@ -578,7 +594,7 @@ impl Writer<'_> { let dashed = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.is_dashed()))); let basic = self.basic_shape(path, self.xf, dashed); - self.shape(n, &d, basic, &[path], *rule, n.geometric_bounds()); + self.shape(n, &d, basic, &[path], *rule, export_shape_bounds(n)); } NodeKind::Compound { children, rule } => { let paths: Vec<&PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).filter(|p| !p.is_empty()).collect(); @@ -586,7 +602,7 @@ impl Writer<'_> { return; } let d: Vec = paths.iter().map(|p| self.path_d(p, self.xf)).collect(); - self.shape(n, &d.join(" "), None, &paths, *rule, n.geometric_bounds()); + self.shape(n, &d.join(" "), None, &paths, *rule, export_shape_bounds(n)); } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 92f5234ee6..d8cf3bcd58 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -186,22 +186,85 @@ pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option Some(PathData::single(SubPath::new(anchors, true))) } +const MAX_CLIP_DEPTH: usize = 16; + +/// Most clip paths read for one clip. They are shared, so children that each name the next one +/// multiply the work at every level: without this, a few lines of SVG would never finish. +const MAX_CLIP_READS: usize = 1024; + /// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { - fn collect(g: &usvg::Group, m: Affine, out: &mut Vec<(BezPath, FillRule)>) { + let mut reads = MAX_CLIP_READS; + clip_shapes_depth(cp, ts, 0, &mut reads) +} + +/// Recursively collect shapes for `cp` in document space up to `MAX_CLIP_DEPTH`, and while `reads` +/// are left. +fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize) -> Vec<(BezPath, FillRule)> { + if depth > MAX_CLIP_DEPTH || *reads == 0 { + return Vec::new(); + } + *reads -= 1; + fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, out: &mut Vec<(BezPath, FillRule)>) { for c in g.children() { match c { - usvg::Node::Group(g) => collect(g, m * aff(g.transform()), out), + usvg::Node::Group(g) => { + let m_child = m * aff(g.transform()); + if let Some(child_cp) = g.clip_path() { + let mut child_shapes = Vec::new(); + collect(g, m_child, depth + 1, reads, &mut child_shapes); + if !child_shapes.is_empty() { + let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads); + intersect_shapes(&child_shapes, &clip_paths, out); + } + } else { + collect(g, m_child, depth, reads, out); + } + } usvg::Node::Path(p) => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), _ => {} } } } let mut shapes = Vec::new(); - collect(cp.root(), ts * aff(cp.transform()), &mut shapes); + collect(cp.root(), ts * aff(cp.transform()), depth, reads, &mut shapes); + if !shapes.is_empty() + && depth > 0 + && depth < MAX_CLIP_DEPTH + && *reads > 0 + && let Some(parent_cp) = cp.clip_path() + { + let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads); + let mut intersected = Vec::new(); + intersect_shapes(&shapes, &parent_shapes, &mut intersected); + shapes = intersected; + } shapes } +/// Intersect `shapes` with `clips`: SVG 1.1 §14.3.5 specifies that a clip path clips to the union +/// of its children, each child first clipped by its own clip-path if present. +fn intersect_shapes(shapes: &[(BezPath, FillRule)], clips: &[(BezPath, FillRule)], out: &mut Vec<(BezPath, FillRule)>) { + if shapes.is_empty() || clips.is_empty() { + return; + } + let clip_data = match clips { + [(bp, rule)] => (PathData::from_bezpath(bp), *rule), + _ => { + let paths: Vec<(PathData, FillRule)> = clips.iter().map(|(bp, r)| (PathData::from_bezpath(bp), *r)).collect(); + let refs: Vec<(&PathData, FillRule)> = paths.iter().map(|(p, r)| (p, *r)).collect(); + (vectorcraft_pathops::unite_all(&refs), FillRule::NonZero) + } + }; + for (bp, r) in shapes { + let child_data = PathData::from_bezpath(bp); + let inter = vectorcraft_pathops::boolean(&child_data, *r, &clip_data.0, clip_data.1, vectorcraft_pathops::BoolOp::Intersect); + if !inter.subpaths.is_empty() { + out.push((inter.to_bezpath(), FillRule::NonZero)); + } + } +} + /// Does clip path `cp` (on an element whose user space `ts` maps to the document) leave `art`, /// placed by `xf`, whole? (Only its bounds are checked: the box must be inside a clip shape.) pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> bool { @@ -217,6 +280,7 @@ pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> corners.iter().all(|c| shapes.iter().any(|(s, _)| kurbo::Shape::contains(s, xf * *c))) } +/// Convert a usvg fill rule to the document model fill rule. pub(super) fn rule(r: usvg::FillRule) -> FillRule { match r { usvg::FillRule::NonZero => FillRule::NonZero, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 0a0372e3f4..826fed0994 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -7,6 +7,7 @@ use super::{ StrokeLayer, Vec2, fnv1a, fx, shapes, spread, text, vector_effect, }; use crate::SvgError; +use kurbo::BezPath; /// How many clip paths deep (``) an object's clip is read. const MAX_CLIP_NEST: usize = 16; @@ -446,19 +447,32 @@ impl Importer { } fn clip_node(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { - let shapes = clip_shapes(cp, ts); - if shapes.is_empty() { + let mut shapes = clip_shapes(cp, ts); + let id = cp.id().to_string(); + if shapes.len() == 1 { + let (bp, r) = shapes.pop()?; + let kind = self.clip_shape(&bp, r, true)?; + return self.named(&id, kind); + } + // SVG 1.1 §14.3.5: the clip is the union of the children's silhouettes, each under its own + // clip-rule, so they don't cancel or share one rule: a group of them, which clips to that + // union (`Node::clip_shapes`). + let mut children = Vec::with_capacity(shapes.len()); + for (bp, r) in &shapes { + let kind = self.clip_shape(bp, *r, false)?; + children.push(Arc::new(Node::new(self.alloc_id()?, kind))); + } + if children.is_empty() { return None; } - let r = shapes[0].1; - let mut subs = Vec::new(); - for (bp, _) in &shapes { - subs.extend(PathData::from_bezpath(bp).subpaths); - } - let id = cp.id().to_string(); + self.named(&id, NodeKind::Group { children, clip: false }) + } + + /// One clip path child: a path, or a compound path of its subpaths when it has several. + fn clip_shape(&mut self, bp: &BezPath, r: FillRule, clipping: bool) -> Option { + let subs = PathData::from_bezpath(bp).subpaths; if subs.len() == 1 { - let path = PathData::new(subs); - return self.named(&id, NodeKind::Path { path, rule: r, live: None, clipping: true, guide: false }); + return Some(NodeKind::Path { path: PathData::new(subs), rule: r, live: None, clipping, guide: false }); } let mut children = Vec::with_capacity(subs.len()); for sp in subs { @@ -466,7 +480,7 @@ impl Importer { children .push(Arc::new(Node::new(nid, NodeKind::Path { path: PathData::single(sp), rule: r, live: None, clipping: false, guide: false }))); } - self.named(&id, NodeKind::Compound { children, rule: r }) + Some(NodeKind::Compound { children, rule: r }) } /// A usvg paint mapped by `m`, for art covering `area` (after `m`: where a reflected or diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 57a156b82e..2502bd2bd6 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -503,6 +503,53 @@ impl Ctx { out.spans[slot].1 = start..out.chars.len(); } + /// `textLength` and `lengthAdjust` (SVG 1.1 §10.9.1, + /// https://www.w3.org/TR/SVG11/text.html#TextElementTextLengthAttribute): the characters of + /// each element with a `textLength` are fitted to that advance, by adding the difference evenly + /// between them (`spacing`, the default; it becomes kerning) or by stretching them + /// (`spacingAndGlyphs`; it becomes horizontal scale, kept within 1–10000%). Innermost elements + /// first, so an element's length takes in its children's. Vertical type is spaced out only. + fn fit_lengths(&self, spans: &[(XNode, Range)], cells: &mut [Cell], vertical: bool, label: &str, warnings: &mut Vec) { + let n = cells.len(); + for (el, r) in spans.iter().rev() { + let Some(want) = el.attribute("textLength").and_then(|v| self.length(v, self.font_size(*el), self.viewport.0)).filter(|w| *w >= 0.0) + else { + continue; + }; + // Past the largest coordinate, the characters would only be out of reach. + let want = want.min(vectorcraft_doc::MAX_COORD); + let Some(part) = cells.get_mut(r.start.min(n)..r.end.min(n)) else { continue }; + let Some(gaps) = part.len().checked_sub(1) else { continue }; + let stretch = el.attribute("lengthAdjust").map(str::trim) == Some("spacingAndGlyphs"); + if stretch && vertical { + warnings.push(format!("{label}: lengthAdjust=\"spacingAndGlyphs\" on vertical text spaces the characters out instead")); + } + // Kerning and scale change shaping (manual kerning turns pair kerning off): measure again. + for _ in 0..4 { + let have = advance(&point_text(part)); + if !have.is_finite() || (want - have).abs() < 0.01 { + break; + } + if stretch && !vertical { + let k = want / have; + if !k.is_finite() || k <= 0.0 { + break; + } + for c in part.iter_mut() { + c.style.h_scale = (c.style.h_scale * k).clamp(1.0, 10_000.0); + } + } else if gaps > 0 { + let d = (want - have) / gaps as f64; + for c in part.iter_mut().take(gaps) { + c.kern += d; + } + } else { + break; + } + } + } + } + /// The path a `` follows, in the text's user space. fn text_path(&self, xml: &roxmltree::Document, tp: XNode) -> Option { let mut bp = match tp.attribute("path") { @@ -730,6 +777,7 @@ impl Ctx { } }); let vertical = self.css.prop(t, "writing-mode").is_some_and(|m| m.starts_with("tb") || m.starts_with("vertical")); + self.fit_lengths(&cs.spans, &mut cells, vertical, label, warnings); let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ccc154a383..58cb434ed2 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -624,6 +624,49 @@ pub fn xml_escape(s: &str) -> String { o } +/// [`push_num`] through integer arithmetic, for the values it writes the same as the decimal +/// formatter: `decimals` of at most 9, and `v` scaled by 10^`decimals` below 2^53 and further from +/// halfway between two integers than the scaling's rounding error. Returns false, writing nothing, +/// for any other value. +fn push_num_scaled(out: &mut String, v: f64, decimals: u8) -> bool { + const SCALE: [f64; 10] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + let Some(&scale) = SCALE.get(usize::from(decimals)) else { return false }; + // Each power of ten here is exact, so `x` is within half an ulp (`x * EPSILON / 2`) of |v| × 10^decimals. + let x = v.abs() * scale; + if x.is_nan() || x >= 9.0e15 { + return false; + } + let whole = x.floor(); + let frac = x - whole; + if (frac - 0.5).abs() <= x * f64::EPSILON { + return false; + } + let mut n = whole as u64 + u64::from(frac > 0.5); + let places = usize::from(decimals); + // The digits of `n` from the last one, at least one more than `places` of them. + let mut digits = [0u8; 24]; + let mut len = 0; + for d in digits.iter_mut() { + if n == 0 && len > places { + break; + } + *d = b'0' + (n % 10) as u8; + n /= 10; + len += 1; + } + let Some((fraction, int)) = digits.get(..len).and_then(|d| d.split_at_checked(places)) else { return false }; + let zeros = fraction.iter().take_while(|&&d| d == b'0').count(); + if v < 0.0 && (zeros < places || int.iter().any(|&d| d != b'0')) { + out.push('-'); + } + out.extend(int.iter().rev().map(|&d| char::from(d))); + if zeros < places { + out.push('.'); + out.extend(fraction.iter().skip(zeros).rev().map(|&d| char::from(d))); + } + true +} + /// Format a number with at most `decimals` places, trimming trailing zeros. pub fn fmt_num(v: f64, decimals: u8) -> String { let mut s = String::new(); @@ -635,6 +678,9 @@ pub fn fmt_num(v: f64, decimals: u8) -> String { pub fn push_num(out: &mut String, v: f64, decimals: u8) { use std::fmt::Write as _; let v = if v.is_finite() { v } else { 0.0 }; + if push_num_scaled(out, v, decimals) { + return; + } let start = out.len(); let _ = write!(out, "{:.*}", decimals as usize, v); // writing to a String can't fail let s = out.get(start..).unwrap_or_default(); @@ -674,4 +720,48 @@ mod tests { fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); } + + /// `v` at `decimals` places by the decimal formatter, trailing zeros trimmed. + fn formatted(v: f64, decimals: u8) -> String { + let s = format!("{:.*}", usize::from(decimals), if v.is_finite() { v } else { 0.0 }); + let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; + if matches!(s, "-0" | "") { "0".into() } else { s.into() } + } + + #[test] + fn numbers_match_the_decimal_formatter() { + let mut values = + vec![0.0, -0.0, 0.5, -0.5, 2.5, 0.0005, -0.0005, 1.0005, 0.125, 1e-12, 9.0e15, 4503599627370495.5, 1e20, f64::NAN, f64::INFINITY]; + // Coordinates of every size, and values on and just off the halfway points between written numbers. + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + for _ in 0..20_000 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64; + let v = (unit - 0.5) * 10f64.powi((seed % 13) as i32 - 3); + let tie = ((v * 1000.0).trunc() + 0.5) / 1000.0; + values.extend([v, tie, f64::from_bits(tie.to_bits() + 1), f64::from_bits(tie.to_bits() - 1)]); + } + for v in values { + for d in 0..=12 { + assert_eq!(fmt_num(v, d), formatted(v, d), "{v:e} at {d} decimals"); + } + } + } + + #[test] + fn coordinates_are_written_through_integers() { + for (v, d, want) in [(123.4567, 3, "123.457"), (-0.25, 3, "-0.25"), (-0.0004, 3, "0"), (1600.0, 3, "1600"), (7.0, 0, "7")] { + let mut s = String::new(); + assert!(push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert_eq!(s, want); + } + // Halfway as stored, too large, or too many places: the decimal formatter writes them. + for (v, d) in [(0.5, 0), (0.125, 2), (1e16, 0), (1.0, 10)] { + let mut s = String::new(); + assert!(!push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert!(s.is_empty()); + } + } } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 8b36458609..13518a6fd4 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -213,6 +213,186 @@ fn nested_clips_intersect() { assert_ne!(mine.over_white(90, 60), [255, 255, 255]); } +/// SVG 1.1 §14.3.5: a clip path clips to the union of its children's silhouettes, each under its +/// own `clip-rule` (https://www.w3.org/TR/SVG11/masking.html#EstablishingANewClippingPath). +#[test] +fn clip_path_children_unite_under_their_own_rules() { + // Two squares wound in opposite directions overlap at 60–100: the overlap stays clipped in. + let opposite = r##" + "##; + // A small non-zero square first, then an even-odd ring: the ring's hole stays out. + let ring = r##" + + "##; + let page = |body: &str| format!(r#"{body}"#); + for body in [opposite, ring] { + let (d, w) = import_with_report(&page(body)).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(&page(body), 200, 200), 24.0, 0.003); + // Written back out, the clip is still the union. + let out = vectorcraft_svg::export(&d, &Default::default()); + assert_similar(&render_artboard(&vectorcraft_svg::import(&out).unwrap()), &mine, 24.0, 0.003); + } + let (d, _) = import_with_report(&page(opposite)).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(80, 80), [255, 0, 0], "the overlap is clipped in"); + assert_eq!(mine.over_white(120, 120), [255, 0, 0]); + assert_eq!(mine.over_white(130, 30), [255, 255, 255]); + let (d, _) = import_with_report(&page(ring)).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(100, 80), [255, 255, 255], "the even-odd hole stays out"); + assert_eq!(mine.over_white(50, 80), [255, 0, 0]); + assert_eq!(mine.over_white(5, 5), [255, 0, 0]); + // Each child keeps its own rule in the clipping group, still named after the clip path. + let clip = &art(&d)[1]; + assert_eq!(clip.name.as_deref(), Some("c")); + let NodeKind::Group { children, clip: false } = &clip.kind else { panic!("{clip:?}") }; + assert!(matches!(children[0].kind, NodeKind::Path { rule: vectorcraft_geom::FillRule::NonZero, .. })); + assert!(matches!(children[1].kind, NodeKind::Compound { rule: vectorcraft_geom::FillRule::EvenOdd, .. })); +} + +/// SVG 1.1 §14.3.5: a child of a clipPath element with its own clip-path is clipped by it before +/// contributing to the clip (https://www.w3.org/TR/SVG11/masking.html#EstablishingANewClippingPath). +#[test] +fn clip_path_child_clip_path_clips_child() { + let page = r##" + + + + + + + + "##; + let (d, w) = import_with_report(page).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(page, 200, 200), 24.0, 0.003); + assert_eq!(mine.over_white(25, 25), [255, 0, 0], "the left strip is clipped in"); + assert_eq!(mine.over_white(100, 100), [255, 255, 255], "the right side is cut by inner clip"); + // Written back out, the clip stays identical. + let out = vectorcraft_svg::export(&d, &Default::default()); + assert_similar(&render_artboard(&vectorcraft_svg::import(&out).unwrap()), &mine, 24.0, 0.003); +} + +#[test] +fn clip_path_child_with_chained_clip_path_intersects() { + let page = r##" + + + + + + + + + "##; + let (d, w) = import_with_report(page).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(page, 200, 200), 24.0, 0.003); + assert_eq!(mine.over_white(25, 25), [255, 0, 0], "top left quadrant is inside both clips"); + assert_eq!(mine.over_white(25, 150), [255, 255, 255], "bottom left is cut by base clip"); + assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip"); +} + +/// Clip paths are shared, so children that each name the next one multiply at every level: ten +/// children on seven levels would take 10^7 reads unbounded. The import must still finish. +#[test] +fn clip_paths_whose_children_fan_out_still_import() { + let mut defs = String::from(r#""#); + for n in 1..8 { + let kids = format!(r#""#, n - 1).repeat(10); + defs += &format!(r#"{kids}"#); + } + let svg = format!( + r#"{defs}"# + ); + assert!(import_with_report(&svg).is_ok()); +} + +#[test] +fn clip_path_deep_chain_preserves_art() { + let mut defs = String::from(r#""#); + for n in 1..=20 { + defs += &format!(r#""#, n - 1); + } + let svg = format!( + r##"{defs}"## + ); + let (d, w) = import_with_report(&svg).unwrap(); + assert!(!w.is_empty(), "expected warning about deep clip nesting"); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 0, 0], "red rect should be preserved despite depth limit"); +} + +#[test] +fn clip_path_child_deep_chain_preserves_art() { + let mut defs = String::from(r#""#); + for n in 1..=20 { + defs += &format!(r#""#, n - 1); + } + defs += r#""#; + let svg = format!( + r##"{defs}"## + ); + let (d, _w) = import_with_report(&svg).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 0, 0], "red rect should be preserved despite depth limit in child clip"); +} + +#[test] +fn clip_path_preserves_union_when_read_budget_exhausted() { + let mut defs = String::from(r#""#); + let mut kids = String::new(); + for i in 0..1100 { + let x = (i % 20) * 10; + let y = (i / 20) * 10; + kids += &format!(r##""##); + } + defs += &format!(r#"{kids}"#); + let svg = format!( + r##"{defs}"## + ); + let (d, _w) = import_with_report(&svg).unwrap(); + let mine = render_artboard(&d); + // Early tiles processed within the 1024 read budget must be preserved in the union. + assert_eq!(mine.over_white(5, 5), [255, 0, 0], "early tile inside read budget is preserved"); +} + +#[test] +fn clip_path_empty_clips_everything() { + let page = r##" + + + + + "##; + let (d, _w) = import_with_report(page).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 255, 255], "genuinely empty clip path clips away all art"); +} + +#[test] +fn clip_path_child_with_empty_linked_clip_clips_everything() { + let page = r##" + + + + + + + + + + + "##; + let (d, _w) = import_with_report(page).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 255, 255], "empty linked clip path clips away all art"); +} + #[test] fn undisplayed_objects_import_hidden() { let body = r##" diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 5fa2b5d7f2..7d0e08c0be 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -693,3 +693,40 @@ fn flowed_text_that_cannot_be_read_is_reported() { assert!(w.iter().any(|w| w.contains(id) && w.contains("flowRoot")), "{id}: {w:?}"); } } + +/// Total advance of a single-line text. +fn advance(t: &TextObject) -> f64 { + layout(FontDb::global(), t).glyphs.iter().map(|g| g.advance).sum() +} + +/// SVG 1.1 §10.9.1: `textLength` fits the characters to that advance, by spacing them out +/// (`lengthAdjust="spacing"`, the default) or by stretching them (`spacingAndGlyphs`). +/// https://www.w3.org/TR/SVG11/text.html#TextElementTextLengthAttribute +#[test] +fn text_length_fits_the_advance() { + let natural = advance(only_text(&open(r#"Hello World"#))); + for adjust in ["spacingAndGlyphs", "spacing"] { + for want in [50.0, 150.0, 300.0] { + let (d, w) = import_with_report(&svg(&format!( + r#"Hello World"# + ))) + .unwrap(); + assert!(w.is_empty(), "{w:?}"); + let t = only_text(&d); + assert_eq!(t.plain_text(), "Hello World"); + let got = advance(t); + assert!(close(got, want, 0.05), "{adjust} {want}: {got} (natural {natural})"); + let scaled = t.runs.iter().all(|r| close(r.style.h_scale, 100.0 * want / natural, 0.5)); + assert_eq!(scaled, adjust == "spacingAndGlyphs", "{adjust} {want}: {:?}", t.runs); + } + } + // On a tspan, only its characters are fitted; units and percentages of the viewport resolve. + let t = open(r#"Hi there!"#); + let t = only_text(&t); + let lay = layout(FontDb::global(), t); + let span: f64 = lay.glyphs.iter().filter(|g| (3..8).contains(&g.byte)).map(|g| g.advance).sum(); + assert!(close(span, 100.0, 0.05), "{span}"); + // A negative length is ignored. + let t = open(r#"Hello World"#); + assert!(close(advance(only_text(&t)), natural, 1e-6)); +} diff --git a/crates/svg/tests/it/prop_svg.rs b/crates/svg/tests/it/prop_svg.rs index a25aec175e..2dd7ceec13 100644 --- a/crates/svg/tests/it/prop_svg.rs +++ b/crates/svg/tests/it/prop_svg.rs @@ -82,6 +82,27 @@ proptest! { let _ = import(&format!("{s}")); } + /// Any `textLength` and `lengthAdjust`, on the text or a tspan (vertical too), imports to a + /// valid document without panicking. + #[test] + fn import_random_text_lengths( + len in "-?[0-9]{0,12}(\\.[0-9]{0,4})?(e[+-]?[0-9]{1,3})?(%|px|em|pt)?|[a-z ]{0,6}", + adjust in "spacing|spacingAndGlyphs|[a-zA-Z]{0,8}", + text in "[A-Za-z \u{5d0}-\u{5ea}]{0,12}", + on_span in any::(), + vertical in any::(), + ) { + let attrs = format!("textLength=\"{len}\" lengthAdjust=\"{adjust}\""); + let (outer, inner) = if on_span { ("", attrs.as_str()) } else { (attrs.as_str(), "") }; + let wm = if vertical { " writing-mode=\"tb\"" } else { "" }; + let svg = format!( + "a{text}b" + ); + if let Ok(doc) = import(&svg) { + check_document(&doc).map_err(TestCaseError::fail)?; + } + } + /// Importing random path data never panics and gives a valid document. #[test] fn import_random_path_data(d in "[MLCQZHVAmlcqzhva0-9 .,eE+-]{0,80}") { diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index 69bb4858a4..e88721b04e 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -3,6 +3,7 @@ //! submenu selects them. Tool gestures emit engine commands. pub mod anchor_eraser; +pub mod box3d; pub mod contour; pub mod corner_tool; pub mod enclosing_lasso; @@ -33,13 +34,15 @@ pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour T pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; +pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; + /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). const HEADED: &[(&[ToolInfo], &str)] = - &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour")]; + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour"), (BOX_3D, "3D Box")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -59,6 +62,7 @@ pub fn create(id: &str) -> Option> { smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), contour::ID => Box::new(contour::ContourTool::default()), + box3d::ID => Box::new(box3d::Box3dTool::default()), _ => return None, }) } @@ -80,6 +84,7 @@ mod tests { assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(heading(contour::ID), Some("Contour")); + assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(GROUPS.len(), HEADED.len()); assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); assert!(create("pen").is_none() && heading("pen").is_none()); diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs new file mode 100644 index 0000000000..b0ecdc350e --- /dev/null +++ b/crates/tools/src/addons/box3d.rs @@ -0,0 +1,732 @@ +//! 3D Box tool (`box3d`) and customizable shape state (`vc-shape-tools`), a built-in add-on. +//! +//! Dragging with the 3D Box tool draws a rotatable 3D box (`addon.shapes.box3d`) whose X, Y and Z +//! rotation angles and parallel/perspective projection flags are configurable in the Control bar +//! (`addon.shapes.configure` and `tool.setOption`). Extended parameters for rectangles, ellipses, +//! polygons, stars, spirals and 3D boxes are stored in the object's `vc-shape-tools` attribute +//! entry (left out of SVG export) while keeping standard `LiveShape` variants synced. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeKind}; +use vectorcraft_geom::corners::cut_corners; +use vectorcraft_geom::shapes::{self, CornerKind, EllipseMode}; +use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; + +use crate::guides::{DrawSnap, Leave}; +use crate::shape::{box_params, space_moves, turned_box}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The 3D Box tool's id. +pub const ID: &str = "box3d"; + +/// Object data entry (`Node::extras`) that stores extended customizable shape parameters. +/// The `vc-` prefix marks it as internal so SVG export omits it from `data-*` attributes. +pub const KEY: &str = "vc-shape-tools"; + +/// Maximum stored JSON length read back from a file. +const MAX_STORED: usize = 4096; + +fn whole_mode() -> EllipseMode { + EllipseMode::Whole +} + +fn default_pie() -> (f64, f64) { + (0.0, 360.0) +} + +/// Parse an [`EllipseMode`] from a command or tool option string (`"slice"`/`"pie"`, `"arc"`/`"open"`, +/// `"chord"`, `"whole"`/`"full"`/`"closed"`). +pub fn parse_arc_mode(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "slice" | "pie" => Some(EllipseMode::Slice), + "arc" | "open" => Some(EllipseMode::Arc), + "chord" => Some(EllipseMode::Chord), + "whole" | "full" | "closed" => Some(EllipseMode::Whole), + _ => None, + } +} + +/// Canonical string name for an [`EllipseMode`]. +pub fn arc_mode_str(m: EllipseMode) -> &'static str { + match m { + EllipseMode::Slice => "slice", + EllipseMode::Arc => "arc", + EllipseMode::Chord => "chord", + EllipseMode::Whole => "whole", + } +} + +/// Customizable shape state for rectangles, ellipses, polygons, stars, spirals and 3D boxes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", rename_all = "camelCase")] +pub enum CustomShape { + Rectangle { + w: f64, + h: f64, + radii: [f64; 4], + #[serde(default)] + kinds: [CornerKind; 4], + #[serde(default)] + radii_relative: bool, + xf: Affine, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default = "whole_mode")] + arc_mode: EllipseMode, + }, + Ellipse { + w: f64, + h: f64, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default)] + arc_mode: EllipseMode, + xf: Affine, + }, + Polygon { + radius: f64, + sides: u32, + xf: Affine, + #[serde(default)] + radii: Vec, + #[serde(default)] + kinds: Vec, + #[serde(default)] + radii_relative: bool, + #[serde(default)] + spoke_ratio: Option, + #[serde(default)] + rounded: f64, + #[serde(default)] + randomized: f64, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default = "whole_mode")] + arc_mode: EllipseMode, + }, + Spiral { + center: Point, + radius: f64, + turns: f64, + divergence: f64, + inner_radius: f64, + clockwise: bool, + }, + Box3d { + w: f64, + h: f64, + angle_x: f64, + angle_y: f64, + angle_z: f64, + parallel_x: bool, + parallel_y: bool, + parallel_z: bool, + xf: Affine, + }, +} + +impl CustomShape { + /// Regenerate the path for this customizable shape. + pub fn to_path(&self) -> PathData { + match self { + CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, pie, arc_mode } => { + let base = shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = vectorcraft_doc::corners::resolve_stored_radii(&base, radii, *radii_relative); + let r = std::array::from_fn(|i| resolved.get(i).copied().unwrap_or(0.0)); + let rect_path = shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), r, *kinds); + let cut = shapes::apply_shape_arc(rect_path, Point::new(*w / 2.0, *h / 2.0), pie.0, pie.1, *arc_mode); + cut.transformed(*xf) + } + CustomShape::Ellipse { w, h, pie, arc_mode, xf } => { + shapes::ellipse_arc(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1, *arc_mode).transformed(*xf) + } + CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode } => { + let raw = match spoke_ratio { + Some(ratio) => { + let r2 = (*radius * ratio.clamp(0.01, 1.0)).max(0.01); + shapes::star_configured(Point::ZERO, *radius, r2, *sides, 0.0, *rounded, *randomized) + } + None => shapes::polygon_configured(Point::ZERO, *radius, *sides, 0.0, *rounded, *randomized), + }; + let outline = raw.transformed(*xf); + let cornered = if rounded.abs() < 1e-9 && !radii.is_empty() { + let resolved = vectorcraft_doc::corners::resolve_stored_radii(&outline, radii, *radii_relative); + cut_corners(&outline, &resolved, kinds).0 + } else { + outline + }; + let center = *xf * Point::ZERO; + shapes::apply_shape_arc(cornered, center, pie.0, pie.1, *arc_mode) + } + CustomShape::Spiral { center, radius, turns, divergence, inner_radius, clockwise } => { + shapes::spiral_configured(*center, *radius, *turns, *divergence, *inner_radius, *clockwise) + } + CustomShape::Box3d { w, h, angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, xf } => { + shapes::box3d(Rect::new(0.0, 0.0, *w, *h), *angle_x, *angle_y, *angle_z, *parallel_x, *parallel_y, *parallel_z).transformed(*xf) + } + } + } + + /// Standard [`LiveShape`] representation when the shape is in a state that `LiveShape` natively + /// models (so Live Corners and Pie widgets work on it directly). + pub fn to_live_shape(&self) -> Option { + match self { + CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, arc_mode, .. } if *arc_mode == EllipseMode::Whole => { + Some(LiveShape::Rectangle { w: *w, h: *h, radii: *radii, kinds: *kinds, radii_relative: *radii_relative, xf: *xf }) + } + CustomShape::Ellipse { w, h, pie, arc_mode, xf } if matches!(arc_mode, EllipseMode::Whole | EllipseMode::Slice) => { + let p = if *arc_mode == EllipseMode::Whole { (0.0, 360.0) } else { *pie }; + Some(LiveShape::Ellipse { w: *w, h: *h, pie: p, xf: *xf }) + } + CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, arc_mode, .. } + if spoke_ratio.is_none() && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole => + { + Some(LiveShape::Polygon { + radius: *radius, + sides: *sides, + xf: *xf, + radii: radii.clone(), + kinds: kinds.clone(), + radii_relative: *radii_relative, + }) + } + _ => None, + } + } + + /// Whether this shape uses extended add-on parameters beyond what `LiveShape` stores on its own. + pub fn needs_extra_storage(&self) -> bool { + self.to_live_shape().is_none() + } + + /// Write this shape's regenerated path, `LiveShape` (if standard) and `vc-shape-tools` attribute + /// entry onto path node `n`. + pub fn write_to_node(&self, n: &mut Node) { + let new_path = self.to_path(); + let new_live = self.to_live_shape().map(Box::new); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = new_path; + *live = new_live; + } + if self.needs_extra_storage() { + if let Ok(entry) = serde_json::to_string(self) { + n.edit_attrs(|a| match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = entry, + None => a.data.push((KEY.into(), entry)), + }); + } + } else { + n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY)); + } + } + + /// Read a [`CustomShape`] from `n`: either from its `vc-shape-tools` attribute entry (synced with + /// `LiveShape` if both exist), from its `LiveShape`, or by detecting a star path. + pub fn read(n: &Node) -> Option { + let NodeKind::Path { path, live, guide: false, .. } = &n.kind else { return None }; + let stored = n + .extras() + .attrs + .as_deref() + .and_then(|a| a.data.iter().find(|(k, _)| k == KEY)) + .filter(|(_, text)| text.len() <= MAX_STORED) + .and_then(|(_, text)| serde_json::from_str::(text).ok()); + match (stored, live.as_deref()) { + (Some(s), None) => Some(s), + (stored_opt, Some(l)) => Self::from_live_shape(l, stored_opt), + (None, None) => Self::detect_star_from_path(path), + } + } + + /// Read a [`CustomShape`] from `n`, or upgrade an open spiral path when spiral parameters are + /// being configured. + pub fn read_for_update(n: &Node, spiral_hint: bool) -> Option { + if let Some(cs) = Self::read(n) { + return Some(cs); + } + if spiral_hint + && let NodeKind::Path { path, live: None, guide: false, .. } = &n.kind + && let Some(sp) = path.subpaths.first() + && !sp.closed + && sp.anchors.len() >= 3 + && let Some(last) = sp.anchors.last() + && let Some(first) = sp.anchors.first() + { + let center = last.p; + let radius = first.p.distance(center).max(1.0); + return Some(CustomShape::Spiral { + center, + radius, + turns: ((sp.anchors.len().saturating_sub(1)) as f64 / 4.0).max(0.25), + divergence: 1.0, + inner_radius: 0.0, + clockwise: true, + }); + } + None + } + + fn from_live_shape(l: &LiveShape, stored: Option) -> Option { + match l.folded() { + LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } => { + let (pie, arc_mode) = match stored { + Some(CustomShape::Rectangle { pie, arc_mode, .. }) => (pie, arc_mode), + _ => ((0.0, 360.0), EllipseMode::Whole), + }; + Some(CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, pie, arc_mode }) + } + LiveShape::Ellipse { w, h, pie, xf } => { + let span = (pie.1 - pie.0).rem_euclid(360.0); + let default_mode = if span < 1e-9 || 360.0 - span < 1e-9 { EllipseMode::Whole } else { EllipseMode::Slice }; + let arc_mode = match stored { + Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => arc_mode, + _ => default_mode, + }; + Some(CustomShape::Ellipse { w, h, pie, arc_mode, xf }) + } + LiveShape::Polygon { radius, sides, xf, radii, kinds, radii_relative } => { + let (spoke_ratio, rounded, randomized, pie, arc_mode) = match stored { + Some(CustomShape::Polygon { spoke_ratio, rounded, randomized, pie, arc_mode, .. }) => { + (spoke_ratio, rounded, randomized, pie, arc_mode) + } + _ => (None, 0.0, 0.0, (0.0, 360.0), EllipseMode::Whole), + }; + Some(CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode }) + } + LiveShape::Line { .. } | LiveShape::Path { .. } => stored, + } + } + + /// Detect a regular star path (even vertex count ≥ 6 with alternating outer/inner radii around + /// its centroid) so plain stars created by `shape.star` can be customized live. + pub fn detect_star_from_path(path: &PathData) -> Option { + let sp = path.subpaths.first()?; + let n = sp.anchors.len(); + if path.subpaths.len() != 1 || !sp.closed || n < 6 || !n.is_multiple_of(2) { + return None; + } + let mut cx = 0.0; + let mut cy = 0.0; + for a in &sp.anchors { + cx += a.p.x; + cy += a.p.y; + } + let center = Point::new(cx / (n as f64), cy / (n as f64)); + let r0 = sp.anchors.first()?.p.distance(center); + let r1 = sp.anchors.get(1)?.p.distance(center); + let (r_outer, r_inner) = if r0 >= r1 { (r0, r1) } else { (r1, r0) }; + if r_outer <= 1e-3 || (r_outer - r_inner).abs() <= 1e-3 * r_outer { + return None; + } + for (i, a) in sp.anchors.iter().enumerate() { + let d = a.p.distance(center); + let target = if i % 2 == 0 { r0 } else { r1 }; + if (d - target).abs() > 0.15 * r_outer { + return None; + } + } + let ratio = (r_inner / r_outer).clamp(0.01, 1.0); + let first = sp.anchors.first()?.p - center; + let rot = first.y.atan2(first.x) + std::f64::consts::FRAC_PI_2; + Some(CustomShape::Polygon { + radius: r_outer, + sides: (n / 2) as u32, + xf: Affine::translate((center.x, center.y)) * Affine::rotate(rot), + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: Some(ratio), + rounded: 0.0, + randomized: 0.0, + pie: (0.0, 360.0), + arc_mode: EllipseMode::Whole, + }) + } +} + +/// The customizable shapes & rotatable 3D Box add-on tool (`box3d`). +pub struct Box3dTool { + start: Option, + last: Point, + mods: Mods, + began: bool, + pub shape: &'static str, + pub corner_radius: f64, + pub corner_radii: [f64; 4], + pub corner_symmetry: bool, + pub arc_start: f64, + pub arc_end: f64, + pub arc_mode: &'static str, + pub sides: u32, + pub points: u32, + pub poly_is_star: bool, + pub star_ratio: f64, + pub rounded: f64, + pub randomized: f64, + pub turns: f64, + pub divergence: f64, + pub inner_radius: f64, + pub clockwise: bool, + pub angle_x: f64, + pub angle_y: f64, + pub angle_z: f64, + pub parallel_x: bool, + pub parallel_y: bool, + pub parallel_z: bool, + snap: DrawSnap, +} + +impl Default for Box3dTool { + fn default() -> Self { + Self { + start: None, + last: Point::ZERO, + mods: Mods::default(), + began: false, + shape: "box3d", + corner_radius: 12.0, + corner_radii: [12.0; 4], + corner_symmetry: true, + arc_start: 0.0, + arc_end: 0.0, + arc_mode: "whole", + sides: 6, + points: 5, + poly_is_star: false, + star_ratio: 0.5, + rounded: 0.0, + randomized: 0.0, + turns: 3.0, + divergence: 1.0, + inner_radius: 0.0, + clockwise: true, + angle_x: 30.0, + angle_y: 35.0, + angle_z: 0.0, + parallel_x: true, + parallel_y: true, + parallel_z: true, + snap: DrawSnap::default(), + } + } +} + +impl Box3dTool { + pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { + let mut out = match self.shape { + "rectangle" => { + let mut v = box_params(start, p, m, base); + if self.corner_symmetry { + v["radius"] = json!(self.corner_radius); + } else { + v["radii"] = json!(self.corner_radii); + } + ("addon.shapes.rectangle".into(), v) + } + "ellipse" => { + let v = box_params(start, p, m, base); + ("addon.shapes.ellipse".into(), v) + } + "polygon" | "star" => { + let d = p - start; + let r = d.hypot().max(0.01); + let rot = if m.shift { vectorcraft_geom::constrain_rotation(base).unwrap_or(0.0) } else { (d.atan2().to_degrees() + 90.0) % 360.0 }; + let is_star = self.shape == "star" || self.poly_is_star; + let count = if is_star { self.points } else { self.sides }; + let mut v = if is_star { + json!({ + "cx": start.x, + "cy": start.y, + "radius1": r, + "radius2": r * self.star_ratio, + "points": count, + "rotation": rot, + }) + } else { + json!({ + "cx": start.x, + "cy": start.y, + "radius": r, + "sides": count, + "rotation": rot, + }) + }; + if self.rounded.abs() > 1e-6 { + v["rounded"] = json!(self.rounded); + } + if self.randomized.abs() > 1e-6 { + v["randomized"] = json!(self.randomized); + } + (if is_star { "addon.shapes.star" } else { "addon.shapes.polygon" }.into(), v) + } + "spiral" => { + let r = p.distance(start).max(0.01); + ( + "addon.shapes.spiral".into(), + json!({ + "cx": start.x, + "cy": start.y, + "radius": r, + "turns": self.turns, + "divergence": self.divergence, + "innerRadius": self.inner_radius, + "clockwise": self.clockwise, + }), + ) + } + _ => { + let mut v = box_params(start, p, m, base); + v["angleX"] = json!(self.angle_x); + v["angleY"] = json!(self.angle_y); + v["angleZ"] = json!(self.angle_z); + v["parallelX"] = json!(self.parallel_x); + v["parallelY"] = json!(self.parallel_y); + v["parallelZ"] = json!(self.parallel_z); + return ("addon.shapes.box3d".into(), v); + } + }; + if matches!(self.shape, "rectangle" | "ellipse" | "polygon" | "star") { + let span = (self.arc_end - self.arc_start).rem_euclid(360.0); + if self.arc_mode != "whole" || (span > 1e-4 && (span - 360.0).abs() > 1e-4) { + out.1["startAngle"] = json!(self.arc_start); + out.1["endAngle"] = json!(self.arc_end); + out.1["arcMode"] = json!(self.arc_mode); + } + } + out + } + + fn undo_label(&self) -> &'static str { + match self.shape { + "rectangle" => "Rounded Rectangle", + "ellipse" => "Ellipse", + "polygon" => "Polygon", + "star" => "Star", + "spiral" => "Spiral", + _ => "3D Box", + } + } +} + +impl Tool for Box3dTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.start.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Move => { + self.snap.hover(cx, ev.pos, &[], None); + vec![] + } + PointerKind::Down => { + let p = self.snap.press(cx, ev.pos, &[], None); + self.start = Some(p); + self.last = ev.pos; + self.began = false; + vec![] + } + PointerKind::Drag => { + let Some(mut s) = self.start else { return vec![] }; + let radial = matches!(self.shape, "polygon" | "star" | "spiral"); + let leave = (!radial).then(|| Leave::diagonal(s, ev.mods.shift && vectorcraft_geom::constrain_axes(cx.constrain_angle).is_none())); + let pos = self.snap.drag(cx, ev.pos, leave.as_ref()); + let ev = &PointerEvent { pos, ..*ev }; + space_moves(&mut s, &mut self.last, ev, self.began); + self.start = Some(s); + self.mods = ev.mods; + let mut out = vec![]; + if !self.began { + if ev.pos.distance(s) < cx.tol(2.0) { + return out; + } + self.began = true; + out.push(Action::Begin(self.undo_label().into())); + } + let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); + out.push(Action::Preview(c, v)); + out + } + PointerKind::Up => { + let Some(s) = self.start.take() else { return vec![] }; + self.snap.clear(); + if self.began { + self.began = false; + vec![Action::Commit] + } else { + let (c, v) = self.command_at(s, s + Vec2::new(100.0, 100.0), ev.mods, cx.constrain_angle); + vec![Action::Begin(self.undo_label().into()), Action::Preview(c, v), Action::Commit] + } + } + _ => vec![], + } + } + + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; + let changed = match (self.shape, key) { + ("polygon", ToolKey::Up) => { + self.sides = (self.sides + 1).min(1000); + true + } + ("polygon", ToolKey::Down) => { + self.sides = self.sides.saturating_sub(1).max(3); + true + } + ("star", ToolKey::Up) => { + self.points = (self.points + 1).min(1000); + true + } + ("star", ToolKey::Down) => { + self.points = self.points.saturating_sub(1).max(3); + true + } + (_, ToolKey::Up) => { + self.angle_x = (self.angle_x + 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Down) => { + self.angle_x = (self.angle_x - 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Right) => { + self.angle_y = (self.angle_y + 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Left) => { + self.angle_y = (self.angle_y - 5.0).clamp(-180.0, 180.0); + true + } + _ => false, + }; + if changed { + let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle); + vec![Action::Preview(c, v)] + } else if key == ToolKey::Escape { + self.start = None; + self.began = false; + self.snap.clear(); + vec![Action::Cancel] + } else { + vec![] + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { + let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); + let (r, _) = turned_box(s, self.last, self.mods, cx.constrain_angle); + o.push(Overlay::Measure { p, text: cx.size_label(r.width(), r.height()) }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ + "shape": self.shape, + "cornerRadius": self.corner_radius, + "cornerRadii": self.corner_radii, + "cornerSymmetry": self.corner_symmetry, + "arcStart": self.arc_start, + "arcEnd": self.arc_end, + "arcMode": self.arc_mode, + "sides": self.sides, + "points": self.points, + "polyIsStar": self.poly_is_star, + "starRatio": self.star_ratio, + "rounded": self.rounded, + "randomized": self.randomized, + "turns": self.turns, + "divergence": self.divergence, + "innerRadius": self.inner_radius, + "clockwise": self.clockwise, + "angleX": self.angle_x, + "angleY": self.angle_y, + "angleZ": self.angle_z, + "parallelX": self.parallel_x, + "parallelY": self.parallel_y, + "parallelZ": self.parallel_z, + }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + let finite = v.as_f64().filter(|n| n.is_finite()); + match key { + "shape" => { + if let Some(s) = v.as_str() { + self.shape = match s { + "rectangle" => "rectangle", + "ellipse" => "ellipse", + "polygon" => "polygon", + "star" => "star", + "spiral" => "spiral", + _ => "box3d", + }; + } + } + "cornerRadius" => { + self.corner_radius = finite.unwrap_or(self.corner_radius).clamp(0.0, crate::shape::MAX_CORNER_RADIUS); + if self.corner_symmetry { + self.corner_radii = [self.corner_radius; 4]; + } + } + "cornerSymmetry" => { + self.corner_symmetry = v.as_bool().unwrap_or(self.corner_symmetry); + if self.corner_symmetry { + self.corner_radii = [self.corner_radius; 4]; + } + } + "cornerRadii" => { + if let Some(arr) = v.as_array() + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + if let Some(r) = item.as_f64().filter(|n| n.is_finite()) { + self.corner_radii[i] = r.clamp(0.0, crate::shape::MAX_CORNER_RADIUS); + } + } + self.corner_radius = self.corner_radii[0]; + } + } + "arcStart" => self.arc_start = finite.map_or(self.arc_start, |n| n.rem_euclid(360.0)), + "arcEnd" => self.arc_end = finite.map_or(self.arc_end, |n| n.rem_euclid(360.0)), + "arcMode" => { + if let Some(s) = v.as_str() { + self.arc_mode = match s { + "pie" => "pie", + "chord" => "chord", + "arc" => "arc", + _ => "whole", + }; + } + } + "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, + "polyIsStar" => self.poly_is_star = v.as_bool().unwrap_or(self.poly_is_star), + "starRatio" => self.star_ratio = finite.unwrap_or(self.star_ratio).clamp(0.01, 1.0), + "rounded" => self.rounded = finite.unwrap_or(self.rounded).clamp(-10.0, 10.0), + "randomized" => self.randomized = finite.unwrap_or(self.randomized).clamp(-10.0, 10.0), + "turns" => self.turns = finite.unwrap_or(self.turns).clamp(0.01, 1024.0), + "divergence" => self.divergence = finite.unwrap_or(self.divergence).clamp(0.0, 1000.0), + "innerRadius" => self.inner_radius = finite.unwrap_or(self.inner_radius).clamp(0.0, 0.999), + "clockwise" => self.clockwise = v.as_bool().unwrap_or(self.clockwise), + "angleX" => self.angle_x = finite.unwrap_or(self.angle_x).clamp(-180.0, 180.0), + "angleY" => self.angle_y = finite.unwrap_or(self.angle_y).clamp(-180.0, 180.0), + "angleZ" => self.angle_z = finite.unwrap_or(self.angle_z).clamp(-180.0, 180.0), + "parallelX" => self.parallel_x = v.as_bool().unwrap_or(self.parallel_x), + "parallelY" => self.parallel_y = v.as_bool().unwrap_or(self.parallel_y), + "parallelZ" => self.parallel_z = v.as_bool().unwrap_or(self.parallel_z), + _ => {} + } + } +} diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index ddcbcb310e..b1ccfa949d 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -81,8 +81,9 @@ impl BuilderMap { }) .collect() }; - // A line keeps its pieces under the outline of a closed path in front of it, so a merge - // or an erase removes them as it does the rest of the line. + // A line keeps its pieces under the outline of a closed path or along a line in front of + // it, so a merge or an erase removes them as it does the rest of the line. The pieces in + // front come first, so a hit where pieces lie on each other takes the one in front. let lines = arr.lines.into_iter().chain(arr.lines_under).collect(); Self { shapes, regions: faces_of(arr.regions), lines: bounded(lines), edges: bounded(arr.edges) } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 2104609cf7..fc3ed294c3 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -363,6 +363,30 @@ fn shape_builder_keeps_a_line_under_an_edge_in_front_and_alt_click_there_takes_t assert!(matches!(map.hit(Point::new(150.0, 51.0), Some(4.0)), Some(Hit::Line(_)))); } +#[test] +fn shape_builder_alt_click_on_coincident_lines_takes_the_front_one() { + // Two lines from (0, 50) to (200, 50), crossed by a line at x = 100: each keeps its own + // pieces, and a hit where they lie on each other takes the piece of the line in front. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut s = Selection::default(); + let line = |a: (f64, f64), b: (f64, f64)| PathData::new(vec![SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)]); + let paths = [line((0.0, 50.0), (200.0, 50.0)), line((0.0, 50.0), (200.0, 50.0)), line((100.0, 0.0), (100.0, 100.0))]; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, Node::path(id, path, Appearance::default_art())).unwrap(); + s.add(id); + } + let map = map_of(&d, &s); + for key in [0, 1] { + assert_eq!(map.lines.iter().filter(|(piece, _)| piece.key == key).count(), 2, "line {key}: {:?}", map.lines); + } + for x in [50.0, 150.0] { + let Some(Hit::Line(i)) = map.hit(Point::new(x, 51.0), Some(4.0)) else { panic!("no line hit at {x}") }; + assert_eq!(map.lines.get(i).map(|(piece, _)| piece.key), Some(1), "at {x}"); + } +} + #[test] fn shape_builder_erase_drag_across_an_overlap_narrower_than_twice_the_tolerance_touches_it() { let (d, s) = sliver_rects(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index ffb3a6560b..42cb495c8f 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -25,8 +25,9 @@ //! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]). //! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the //! pointer ([`release_guide_at`]). -//! Direct Selection also edits a blend's spine: drag its points (a key object on a point moves -//! with it) and, once a point is clicked, its handles; and the points of selected gradient meshes +//! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which +//! drag together; a key object on a point moves with it) and, once a point is clicked, its +//! handles; and the points of selected gradient meshes //! and mesh envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, //! a click on a gradient mesh's line picks its two ends and one inside a patch the four points //! around it, a drag of picked points moves them all, the arrow keys nudge them, and a solid fill @@ -182,6 +183,9 @@ pub struct DirectSelectionTool { state: State, /// The spine point last clicked (blend, anchor): its handles show and can be dragged. spine: Option<(NodeId, usize)>, + /// Other points of that spine picked with it (Shift-click adds or takes one away); dragging + /// a picked point moves them all (#5285). + spine_more: Vec, mesh: MeshEdit, /// Smart guides of the handle, anchors or objects being dragged. guides: Vec, @@ -215,8 +219,8 @@ pub struct DirectSelectionTool { click: Option<(NodeId, usize, usize)>, /// A click on a whole path picks the segment on release; a drag still moves the whole path. click_segment: Option<(NodeId, usize, usize)>, - /// An Alt-click on a path selected whole adds this enclosing group on release, as a Group - /// Selection click does; an Alt-drag still copies the selection. + /// A Group Selection click, or an Alt-click on a path selected whole, adds this enclosing + /// group on release. A drag keeps the selection; an Alt-drag still copies it. click_group: Option, /// The selected anchors of area type's frames, picked by a click or a marquee: they show /// filled, a drag of one moves them all, and the arrow keys nudge them. They stay selected @@ -237,6 +241,7 @@ impl DirectSelectionTool { group, state: State::Idle, spine: None, + spine_more: vec![], mesh: MeshEdit::default(), guides: vec![], anchor_snap: None, @@ -773,7 +778,8 @@ impl Tool for DirectSelectionTool { self.state = State::SpineHandle { id: sel.0, anchor: sel.1, out }; return vec![Action::Begin("Reshape Spine".into())]; } - self.spine = None; + let held = self.spine.take().filter(|(id, _)| cx.selection.contains(*id)); + let more = std::mem::take(&mut self.spine_more); self.snapped = false; if let Some(g) = self.mesh.hit(cx, &cx.selection.objects, p) { self.state = State::Mesh; @@ -789,7 +795,24 @@ impl Tool for DirectSelectionTool { return vec![Action::Begin("Reshape".into())]; } if let Some((id, anchor, from)) = hit_spine_point(cx, p, point) { + // The points of this spine picked before: Shift-click adds the point or takes + // it away; a plain click on one of them keeps them all, to drag together. + let mut picked: Vec = + held.filter(|(h, _)| *h == id).map(|(_, a)| more.into_iter().chain([a]).collect()).unwrap_or_default(); + if ev.mods.shift + && let Some(k) = picked.iter().position(|a| *a == anchor) + { + picked.remove(k); + self.spine = picked.pop().map(|a| (id, a)); + self.spine_more = picked; + return vec![]; + } + if !ev.mods.shift && !picked.contains(&anchor) { + picked.clear(); + } + picked.retain(|a| *a != anchor); self.spine = Some((id, anchor)); + self.spine_more = picked; self.state = State::SpinePoint { id, anchor, from, start: p, began: false }; return if cx.selection.contains(id) { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } @@ -873,7 +896,12 @@ impl Tool for DirectSelectionTool { self.state = State::SpinePoint { id, anchor, from, start, began: true }; } let q = from + move_delta(start, p, ev.mods.shift, cx.constrain_angle); - out.push(Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": id.0, "anchor": anchor, "x": q.x, "y": q.y}))); + let mut params = json!({"id": id.0, "anchor": anchor, "x": q.x, "y": q.y}); + let with: Vec = self.spine_more.iter().copied().filter(|a| spine_anchor(cx, (id, *a)).is_some()).collect(); + if !with.is_empty() { + params["with"] = json!(with); + } + out.push(Action::Preview("object.blend.spine.moveAnchor".into(), params)); out } (PointerKind::Drag, State::SpineSegment { id, seg, t, start, began }) => { @@ -1139,6 +1167,12 @@ impl DirectSelectionTool { out.push(Overlay::Handle { p: h, color }); } out.push(Overlay::Anchor { p: a.p, color, filled: true, size: 5.0 }); + out.extend(self.spine_more.iter().filter_map(|i| spine_anchor(cx, (sel.0, *i))).map(|m| Overlay::Anchor { + p: m.p, + color, + filled: true, + size: 5.0, + })); out } } @@ -1159,6 +1193,7 @@ impl DirectSelectionTool { Some(vec![]) } fn press_group(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64) -> Vec { + self.click_group = None; if let Some(out) = self.guide.press(cx, ev) { self.state = State::Idle; return out; @@ -1188,7 +1223,8 @@ impl DirectSelectionTool { } } else if !cx.selection.contains(target) { if cx.selection.contains(h.leaf) { - out.push(Action::Exec("select.add".into(), json!({"ids": [target.0]}))); + // A completed click climbs the group; a drag moves only the selected art. + self.click_group = Some(target); } else { out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index ef60102200..c1748cac9f 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -182,6 +182,45 @@ fn dragging_a_spine_point_moves_it() { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Anchor { filled: true, .. })), "the clicked point shows"); } +/// #5285: Shift-click picks several points of a blend's spine, as of a path; dragging one of them +/// moves them all (`with`), and Shift-click on a picked point takes it away again. +#[test] +fn shift_click_picks_several_spine_points_which_drag_together() { + let (mut d, g, _) = blend_doc(); + let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(160.0, 310.0), Point::new(210.0, 310.0)], false); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![0, 2]); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let filled = |t: &DirectSelectionTool| t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Anchor { filled: true, .. })).count(); + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0).with_mods(shift)); + assert_eq!(filled(&t), 2, "both picked points show"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 330.0)); + assert_eq!( + a.last(), + Some(&Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": g.0, "anchor": 2, "x": 210.0, "y": 330.0, "with": [1]}))) + ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 330.0)), vec![Action::Commit]); + // A plain press on a picked point keeps both. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 160.0, 300.0)); + assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 1 && v["with"] == json!([2])), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 300.0)); + // Shift-click takes one away; a plain click on another point picks it alone. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 310.0).with_mods(shift)); + assert_eq!(filled(&t), 1); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 110.0, 330.0)); + assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 0 && v.get("with").is_none()), "{a:?}"); +} + /// #1111: the Anchor Point tool bends a selected blend's straight spine; Direct Selection /// reshapes a curved spine segment and leaves a straight one alone, as it does a path's. #[test] @@ -755,11 +794,17 @@ fn group_selection_picks_a_path_of_a_compound_path() { d.insert(Some(l), 0, c).unwrap(); let p = paint(); let none = Selection::default(); - let click = |s: &Selection, x, y| DirectSelectionTool::new(true).pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, x, y)); + let click = |s: &Selection, x, y| { + let mut t = DirectSelectionTool::new(true); + let context = cx(&d, s, &p); + let mut actions = t.pointer(&context, &PointerEvent::new(PointerKind::Down, x, y)); + actions.extend(t.pointer(&context, &PointerEvent::new(PointerKind::Up, x, y))); + actions + }; let set = |id: NodeId| vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]; assert_eq!(click(&none, 25.0, 100.0), set(outer), "the fill between the outline and the hole"); assert_eq!(click(&none, 50.0, 100.0), set(hole), "the hole's outline"); - assert!(click(&none, 100.0, 100.0).is_empty(), "inside the hole nothing is hit"); + assert_eq!(click(&none, 100.0, 100.0), vec![Action::Exec("select.none".into(), json!({}))], "a click inside the hole clears selection"); let mut s = Selection::default(); s.set([outer]); assert_eq!(click(&s, 25.0, 100.0), vec![Action::Exec("select.add".into(), json!({"ids": [compound.0]}))]); @@ -813,6 +858,30 @@ fn nested_group_doc() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId, Nod (d, inside, outside, inner, outer) } +/// A selected component drags independently; only a completed click adds its group. +#[test] +fn group_selection_distinguishes_selected_leaf_drags_from_clicks() { + let (d, inside, _, inner, _) = nested_group_doc(); + let paint = paint(); + let mut selected = Selection::default(); + selected.set([inside]); + let context = cx(&d, &selected, &paint); + let mut t = DirectSelectionTool::new(true); + let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0); + assert!(t.pointer(&context, &down).is_empty()); + let actions = t.pointer(&context, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0)); + assert!(matches!(actions.as_slice(), [Action::Begin(_), Action::Preview(command, _)] if command=="object.transform")); + assert_eq!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]); + assert!(t.pointer(&context, &down).is_empty()); + assert_eq!( + t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), + vec![Action::Exec("select.add".into(), json!({"ids":[inner.0]}))] + ); + assert!(t.pointer(&context, &down).is_empty()); + assert_eq!(t.key(&context, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty()); +} + /// Isolation mode: a marquee and an anchor click take the path inside the isolated group and /// leave the path beside it. Group Selection stops at the isolated group instead of adding /// the group around it. diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index db6eae9581..ece5231bd2 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -104,6 +104,11 @@ impl PointerEvent { pub fn json_hold(e: &Value) -> f64 { e.get("holdMs").and_then(Value::as_f64).filter(|f| f.is_finite()).map_or(0.0, |ms| ms.clamp(0.0, 60_000.0) / 1000.0) } + /// Whether backquote is held, from the `backquote` of a JSON pointer event or request (control + /// channel, MCP): `default` when the key is absent, an error when it is not a boolean. + pub fn json_backquote(v: &Value, default: bool) -> Result { + v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) + } } #[cfg(test)] @@ -119,6 +124,17 @@ mod tests { value["backquote"] = serde_json::json!(true); assert!(serde_json::from_value::(value).unwrap().backquote); } + + #[test] + fn json_backquote_takes_the_default_only_when_absent() { + use serde_json::json; + assert_eq!(PointerEvent::json_backquote(&json!({}), true), Ok(true)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": false}), true), Ok(false)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": true}), false), Ok(true)); + for bad in [json!("true"), json!(1), json!(null)] { + assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}"); + } + } } /// Keys tools care about. diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e5474bbde7..d132763156 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -379,6 +379,8 @@ struct MemoState { entry: Option, /// How many measurements the memo has made. measurements: u64, + /// How many times the memo has checked its key. + checks: u64, } /// The measurements for one key; a slot holds `None` until it is measured. @@ -404,8 +406,15 @@ impl PreviewMemo { self.0.try_borrow().map_or(0, |st| st.measurements) } + /// How many times the memo has checked its key against the document. A check compares the whole + /// selection, so a hover has to make the same few however many objects are selected. + pub fn checks(&self) -> u64 { + self.0.try_borrow().map_or(0, |st| st.checks) + } + /// The measurements for the state `cx` shows, after the ones for any other state are dropped. fn current<'m>(st: &'m mut MemoState, cx: &ToolContext) -> &'m mut Measured { + st.checks += 1; let fresh = || Measured { revision: cx.revision, objects: cx.selection.objects.clone(), @@ -466,7 +475,27 @@ fn shown_box(cx: &ToolContext) -> Option { /// The bounds of object `id`, measured as [`selection_bounds`] measures the selection. fn object_bounds(cx: &ToolContext, id: NodeId) -> Option { - remembered(cx, |m| m.by_object.entry(id).or_insert(None), || vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds)) + with_object_bounds(cx, |bounds| bounds(id)) +} + +/// Runs `walk` with a lookup of [`object_bounds`]. The lookups share one check of the memo's key, +/// which compares the whole selection: a walk of every selected object checking it each time takes +/// time in the square of their number. +fn with_object_bounds(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(NodeId) -> Option) -> R) -> R { + let mut measure = |id: NodeId| vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds); + let Some(mut st) = cx.preview_memo.and_then(|memo| memo.0.try_borrow_mut().ok()) else { + return walk(&mut measure); + }; + let mut measured = 0; + let by_object = &mut PreviewMemo::current(&mut st, cx).by_object; + let out = walk(&mut |id| { + *by_object.entry(id).or_insert(None).get_or_insert_with(|| { + measured += 1; + measure(id) + }) + }); + st.measurements += measured; + out } /// The objects of `ids` that lie entirely inside marquee `r`, edges included, measured by their @@ -560,15 +589,17 @@ impl SelectionTool { }; // A press on an unselected object selects it alone: the selected ones stay behind. let selected = if under.is_none_or(|u| cx.selection.contains(u)) { &cx.selection.objects[..] } else { &[] }; - under.into_iter().chain(selected.iter().copied()).find_map(|id| { - let n = cx.doc.node(id)?; - let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)))); - anchor.map(|q| (q, "anchor")).or_else(|| { - if !cx.smart_guides { - return None; - } - let c = object_bounds(cx, id)?.center(); - (c.distance(p) <= reach).then_some((c, "center")) + with_object_bounds(cx, |bounds| { + under.into_iter().chain(selected.iter().copied()).find_map(|id| { + let n = cx.doc.node(id)?; + let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)))); + anchor.map(|q| (q, "anchor")).or_else(|| { + if !cx.smart_guides { + return None; + } + let c = bounds(id)?.center(); + (c.distance(p) <= reach).then_some((c, "center")) + }) }) }) } diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index f8594226ce..f48625a6ac 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -6,11 +6,19 @@ //! Ctrl/Cmd keeps the inner radius where it is while the outer one follows the pointer, and Alt //! keeps the star's shoulders straight (#812). The start point and //! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. +//! +//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, +//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at +//! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on +//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a press anywhere +//! else draws a new shape (#5477). use serde_json::{Value, json}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use crate::corners::{self, CornerDrag}; use crate::guides::{DrawSnap, Leave, square}; +use crate::pie::{self, PieDrag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The largest corner radius the Rounded Rectangle tool draws, points: the range of General › @@ -18,6 +26,18 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// value stop there too. pub const MAX_CORNER_RADIUS: f64 = 1296.0; +/// Does tool `id` keep the selection's bounding box and Live Shape widgets on show and let its +/// corner and pie widgets be dragged (#5477)? The shape tools that draw a box: not Line Segment. +pub fn shows_shape_widgets(id: &str) -> bool { + matches!(id, "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star") +} + +/// A drag on a Live Shape widget of the selection, taken by a shape tool. +enum WidgetDrag { + Corner(CornerDrag), + Pie(PieDrag), +} + pub struct ShapeTool { id: &'static str, start: Option, @@ -37,6 +57,8 @@ pub struct ShapeTool { pub line_angle: f64, pub fill_line: bool, snap: DrawSnap, + /// A widget of the selection is being dragged instead of a shape drawn. + widget: Option, } /// The inner-to-outer radius ratio that keeps a star of `points` points' shoulders straight (each @@ -72,9 +94,41 @@ impl ShapeTool { line_length: 100.0, line_angle: 0.0, fill_line: false, + widget: None, } } + /// A press on a corner or pie widget of the selection: the drag adjusts it. + fn press_widget(&mut self, cx: &ToolContext, ev: &PointerEvent) -> bool { + if !shows_shape_widgets(self.id) { + return false; + } + self.widget = CornerDrag::hit(cx, ev, false).map(WidgetDrag::Corner).or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)); + self.widget.is_some() + } + + /// Is `p` over a corner or pie widget of the selection that a press would drag? + fn over_widget(&self, cx: &ToolContext, p: Point) -> bool { + shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p)) + } + + /// The pointer and keys while a widget is dragged: `None` when none is. + fn widget_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + let w = self.widget.as_mut()?; + Some(match ev.kind { + PointerKind::Drag => match w { + WidgetDrag::Corner(c) => c.drag(cx, ev.pos), + WidgetDrag::Pie(d) => d.drag(cx, ev.pos), + }, + PointerKind::Up => match self.widget.take() { + Some(WidgetDrag::Corner(c)) => c.finish(), + Some(WidgetDrag::Pie(d)) => d.finish(), + None => vec![], + }, + _ => vec![], + }) + } + /// Ctrl/Cmd in a star drag from `start` to `p`, where the last drag showed a star with the inner /// radius `shown`: once the star has begun, the inner radius stays as the star showed it when /// the key went down, so the ratio follows the outer radius (and stays so once the key is let @@ -214,15 +268,27 @@ impl Tool for ShapeTool { self.id } fn busy(&self) -> bool { - self.start.is_some() + self.start.is_some() || self.widget.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if let Some(out) = self.widget_pointer(cx, ev) { + return out; + } match ev.kind { PointerKind::Move => { - self.snap.hover(cx, ev.pos, &[], None); + // Over a widget a press would drag, no Smart Guide for a new shape's start. + if self.over_widget(cx, ev.pos) { + self.snap.clear(); + } else { + self.snap.hover(cx, ev.pos, &[], None); + } vec![] } PointerKind::Down => { + if self.press_widget(cx, ev) { + self.snap.clear(); + return vec![]; + } let p = self.snap.press(cx, ev.pos, &[], None); self.start = Some(p); self.last = ev.pos; @@ -274,6 +340,19 @@ impl Tool for ShapeTool { } } fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + // A widget drag: Up and Down step a corner's kind; Escape cancels it, as with the + // Selection tool. + if let Some(w) = &mut self.widget { + return match (key, w) { + (ToolKey::Up | ToolKey::Down, WidgetDrag::Corner(c)) => c.step_kind(key == ToolKey::Up), + (ToolKey::Escape, _) => match self.widget.take() { + Some(WidgetDrag::Corner(c)) if c.adjusting() => vec![Action::Cancel], + Some(WidgetDrag::Pie(d)) if d.adjusting() => vec![Action::Cancel], + _ => vec![], + }, + _ => vec![], + }; + } let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; let changed = match (self.id, key) { ("polygon", ToolKey::Up) => { @@ -315,7 +394,23 @@ impl Tool for ShapeTool { vec![] } } + /// Adjusting a widget (the canvas hides the bounding box meanwhile, as for the Selection tool). + fn transforming(&self) -> bool { + match &self.widget { + Some(WidgetDrag::Corner(c)) => c.adjusting(), + Some(WidgetDrag::Pie(d)) => d.adjusting(), + None => false, + } + } + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(self.widget, Some(WidgetDrag::Corner(_))) && matches!(key, ToolKey::Up | ToolKey::Down) + } fn overlays(&self, cx: &ToolContext) -> Vec { + match &self.widget { + Some(WidgetDrag::Corner(c)) => return c.overlays(cx), + Some(WidgetDrag::Pie(d)) => return d.overlays(cx), + None => {} + } let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); @@ -347,8 +442,16 @@ impl Tool for ShapeTool { } o } - fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - Cursor::Crosshair + fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { + // Over a widget a press would drag (or dragging one), the Selection tool's pointer for it. + let idle = self.start.is_none(); + match &self.widget { + Some(WidgetDrag::Corner(_)) => Cursor::CornerRadius, + Some(WidgetDrag::Pie(_)) => Cursor::ArrowHollow, + None if idle && shows_shape_widgets(self.id) && corners::over_widget(cx, p, false) => Cursor::CornerRadius, + None if idle && self.over_widget(cx, p) => Cursor::ArrowHollow, + None => Cursor::Crosshair, + } } fn options(&self) -> Value { json!({ diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index da4916576e..f51cf117f9 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -353,3 +353,73 @@ fn line_segment_options_and_fill_line() { ); assert_eq!(t.command(a, b, Mods::default()).1["fill"], json!(true)); } + +/// #5477: with a shape tool, a drag on a selected live rectangle's corner widget rounds its +/// corners (one undo step) and a drag on a live ellipse's pie widget sets its pie angle, as with +/// the Selection tool; the pointer over a widget is the Selection tool's. A press anywhere else, or +/// with Line Segment, draws. +#[test] +fn a_shape_tool_drags_the_selected_shapes_widgets() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let (d, s) = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(110.0, 110.0); + for id in ["rectangle", "roundedRectangle", "polygon", "star", "ellipse"] { + let mut t = ShapeTool::new(id); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::CornerRadius, "{id}"); + // Hovering a widget shows no Smart Guide for a new shape. + t.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert!(t.overlays(&c).is_empty(), "{id}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id}"); + assert!(t.busy(), "{id}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert_eq!(a.first(), Some(&Action::Begin("Corner Radius".into())), "{id}: {a:?}"); + assert!( + matches!(a.last(), Some(Action::Preview(cmd, v)) if cmd == "object.setLiveShape" && v["radius"].as_f64().is_some_and(|r| r > 0.0)), + "{id}: {a:?}" + ); + assert!(t.transforming(), "{id}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 130.0)), vec![Action::Commit], "{id}"); + assert!(!t.busy() && !t.transforming(), "{id}"); + // Escape cancels a widget drag. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{id}"); + assert!(!t.busy(), "{id}"); + // Away from the widgets the tool draws. + assert_eq!(t.cursor(&c, Point::new(300.0, 300.0), Mods::default()), Cursor::Crosshair, "{id}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 350.0, 340.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd.starts_with("shape.")), "{id}: {a:?}"); + } + // Line Segment draws from a widget, as it always did. + let mut t = ShapeTool::new("lineSegment"); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::Crosshair); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}"); + // A whole live ellipse's pie widgets sit 12 px right of (300, 150). + let (d, s) = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("ellipse"); + assert_eq!(t.cursor(&c, Point::new(312.0, 150.0), Mods::default()), Cursor::ArrowHollow); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 312.0, 150.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 200.0, 20.0)); + assert_eq!(a.first(), Some(&Action::Begin("Live Shape".into())), "{a:?}"); + assert!(matches!(a.last(), Some(Action::Preview(cmd, v)) if cmd == "object.setLiveShape" && v.get("pieEnd").is_some()), "{a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); +} diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 04755740a6..d4f553039c 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -276,7 +276,12 @@ fn paint_sample(s: &mut Sampler, levels: &mut [Option], n: &Node, on_s // path's strokes, only the ones that reach `p` count, when any does (a click within the hit // tolerance of a stroke may reach none). let mut visible: Vec = items.into_iter().filter(|&i| n.appearance.items.get(i).is_some_and(|it| it.visible())).collect(); - if stroke && let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }, Some(bp)) = (&n.kind, n.stroke_path()) { + // With at most one visible stroke, reach testing cannot change which paint is sampled. + // Avoid rebuilding a long path just to keep that same stroke in the list. + if stroke + && visible.len() > 1 + && let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }, Some(bp)) = (&n.kind, n.stroke_path()) + { let reach = |i: &usize| matches!(n.appearance.items.get(*i), Some(vectorcraft_doc::AppearanceItem::Stroke(st)) if st.hits(&bp, *rule, p, 0.0)); if visible.iter().any(&reach) { diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 3f09098422..6cacf1c0d6 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -10,6 +10,7 @@ pub mod enclosing_lasso; pub mod pathtools; pub mod pen; pub mod select; +pub mod shapes; pub mod typetools; use crate::menus::Item; @@ -17,6 +18,7 @@ use crate::menus::Item; /// The add-ons' submenus, then a separator: the head of Object › Plug-ins. pub fn plugin_menu() -> Vec { vec![ + Item::Sub("3D Box", shapes::menu()), Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 9ea6530474..39c73e8c64 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -104,6 +104,10 @@ pub fn menu() -> Vec { Item::Cmd("Find Nearest Swatch…", nearest::COMMAND, Value::Null), Item::Cmd("Create Swatch Legend…", legend::COMMAND, Value::Null), Item::Sep, + // Each selected object's stroke takes its own fill, or the other way (#5530). + Item::Cmd("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})), + Item::Cmd("Apply Stroke to Fill", "addon.color.strokeToFill", json!({})), + Item::Sep, Item::Sub( "Select by Color Kind", [ diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 8f6b258269..c61eb0537d 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,7 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen. +//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status +//! ([`link_status`], #5526). use egui::{Sense, Ui, vec2}; use serde_json::{Value, json}; @@ -13,6 +14,8 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; +pub mod link_status; + /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; pub const KIND: &str = "selectByArtboards"; @@ -25,7 +28,9 @@ const LIST_H: f32 = 220.0; /// Object › Plug-ins › Selection Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null)] + let mut v = vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null), Item::Sep]; + v.extend(link_status::menu()); + v } /// The dialog's fields to start with: the active artboard chosen, Overlapping. diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs new file mode 100644 index 0000000000..0b367a7ba0 --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -0,0 +1,289 @@ +//! Select by Link Status in the interface (#5526): Select Linked, Embedded, Missing and Modified +//! (in Object › Plug-ins › Selection Tools and the Links panel's menu; Shift adds to the +//! selection), the Select by Link Status dialog, and the status bar's line saying what was +//! selected and what was left out. Everything goes through `addon.select.byLinkStatus`; the dialog +//! lists what `links.list` reports. + +use egui::{Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// Select by Link Status, and its dialog's kind. +pub const COMMAND: &str = "addon.select.byLinkStatus"; +pub const KIND: &str = "selectByLinkStatus"; +/// The statuses, as the command names them, with their menu items' and the dialog's labels. +pub const STATUSES: [(&str, &str, &str); 4] = [ + ("linked", "Select Linked", "Linked"), + ("embedded", "Select Embedded", "Embedded"), + ("missing", "Select Missing", "Missing"), + ("modified", "Select Modified", "Modified"), +]; +/// The dialog's Show choices: (value, label). +const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")]; +/// How often the statuses are looked at again while the document stays as it is (s): files +/// change on disk without the document knowing. +const RECHECK: f64 = 2.0; +/// The least time between two looks while the document keeps changing (s). +const SETTLE: f64 = 0.5; +const ROW_H: f32 = 22.0; +const LIST_H: f32 = 240.0; +const STATUS_W: f32 = 80.0; +const FORMAT_W: f32 = 70.0; + +/// The menu items: one per status, then the dialog. +pub fn menu() -> Vec { + let mut v: Vec = STATUSES.iter().map(|&(status, label, _)| Item::Cmd(label, COMMAND, json!({ "status": status }))).collect(); + v.push(Item::Cmd("Select by Link Status…", COMMAND, Value::Null)); + v +} + +/// Which statuses ([`STATUSES`] order) the active document's images and placed documents have, +/// for the document and revision it was read for and when. +#[derive(Clone, Debug, Default)] +pub struct Present { + key: Option<(u64, u64)>, + at: f64, + pub has: [bool; 4], +} + +/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order. +pub(crate) fn statuses_in(list: &Value) -> [bool; 4] { + let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice); + STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status)) +} + +/// The status of a `links.list` row as the command names it (`ok` is `linked`). +fn command_status(row: &Value) -> &str { + match row["status"].as_str().unwrap_or_default() { + "ok" => "linked", + s => s, + } +} + +/// Keep [`Present`] up to date: at once when another document comes to the front, at most every +/// [`SETTLE`] seconds while its revision changes (a drag changes it every frame, and each look +/// asks the file system about every linked file), and every [`RECHECK`] seconds while it has +/// linked files. +pub fn refresh(app: &mut VectorcraftApp, now: f64) { + let key = app.session.active().map(|st| (st.uid, st.revision)); + let p = &app.ui.link_statuses; + let linked = p.has.iter().zip(STATUSES).any(|(on, (status, ..))| *on && status != "embedded"); + let other_document = p.key.map(|k| k.0) != key.map(|k| k.0); + let due = if p.key == key { linked && now - p.at >= RECHECK } else { other_document || now - p.at >= SETTLE }; + if !due { + return; + } + let has = if key.is_some() { app.session.execute("links.list", &json!({})).map(|l| statuses_in(&l)).unwrap_or_default() } else { [false; 4] }; + app.ui.link_statuses = Present { key, at: now, has }; +} + +/// Is menu item `status` (a [`STATUSES`] value) on: does an image or placed document have it? +pub(crate) fn enabled(app: &VectorcraftApp, p: &Value) -> bool { + let Some(status) = p.get("status").and_then(Value::as_str) else { return true }; + STATUSES.iter().position(|(s, ..)| *s == status).and_then(|i| app.ui.link_statuses.has.get(i).copied()).unwrap_or(false) +} + +/// A menu item's params with Shift held: add to the selection. +pub(crate) fn with_shift(mut p: Value) -> Value { + if let Some(o) = p.as_object_mut() + && o.contains_key("status") + { + o.insert("add".into(), json!(true)); + } + p +} + +/// Run the command; with `zoom` and something selected, Zoom to Selection; the status bar says +/// what was selected and what was left out. Without params (the menu's "Select by Link Status…") +/// it opens the dialog instead. +pub(crate) fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.as_object().is_none_or(serde_json::Map::is_empty) { + if app.session.active().is_none() { + return Err("no document".into()); + } + let fields = fields(app); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + return Ok(json!({ "dialog": KIND })); + } + let r = app.session.execute(COMMAND, p).map_err(|e| e.to_string())?; + let count = r["count"].as_u64().unwrap_or(0); + if r["zoom"] == true && count > 0 { + crate::addons::arrange::zoom(app)?; + } + let statuses: Vec<&str> = match &p["status"] { + Value::Array(v) => v.iter().filter_map(Value::as_str).collect(), + v => v.as_str().into_iter().collect(), + }; + let reasons: Vec<&str> = r["skipped"].as_array().map_or(vec![], |v| v.iter().filter_map(|k| k["reason"].as_str()).collect()); + app.status(message(&statuses, count, &reasons)); + Ok(r) +} + +/// The status bar's line: `count` objects of `statuses` selected, and the `reasons` the others +/// were left out for (e.g. "Selected 9 missing images; 3 more are hidden or locked"). +pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String { + let n = count; + let selected = match statuses { + ["linked"] => crate::i18n::msg_n(n, "Selected {n} linked image", "Selected {n} linked images", &[]), + ["embedded"] => crate::i18n::msg_n(n, "Selected {n} embedded image", "Selected {n} embedded images", &[]), + ["missing"] => crate::i18n::msg_n(n, "Selected {n} missing image", "Selected {n} missing images", &[]), + ["modified"] => crate::i18n::msg_n(n, "Selected {n} modified image", "Selected {n} modified images", &[]), + _ => crate::i18n::msg_n(n, "Selected {n} image", "Selected {n} images", &[]), + }; + let Some(first) = reasons.first() else { return selected }; + // Hidden and locked go together; a template layer, or the isolated group, alone. + /// The group reason `r` is told in: hidden and locked are one. + fn kind(r: &str) -> &str { + match r { + "hidden" | "locked" => "locked", + r => r, + } + } + let (one, other) = match kind(first) { + k if reasons.iter().any(|r| kind(r) != k) => ("{selected}; {n} more can't be selected now", "{selected}; {n} more can't be selected now"), + "template" => ("{selected}; {n} more is on a template layer", "{selected}; {n} more are on template layers"), + "isolation" => ("{selected}; {n} more is outside the isolated group", "{selected}; {n} more are outside the isolated group"), + _ => ("{selected}; {n} more is hidden or locked", "{selected}; {n} more are hidden or locked"), + }; + crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)]) +} + +/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list` +/// lists them, read once), those selected chosen, All shown, Zoom to Selection on. +pub(crate) fn fields(app: &mut VectorcraftApp) -> Value { + let list = app.session.execute("links.list", &json!({})).unwrap_or_default(); + let rows: Vec = list["links"].as_array().cloned().unwrap_or_default(); + let selected: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + let chosen: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect(); + json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Select by Link Status").to_string(), + body, + confirm, + ok: Some("Select"), + min_width: 420.0, + max_width: Some(480.0), + ok_enabled: Some(|_, d| !chosen(d).is_empty()), + ..DialogSpec::FORM +}; + +/// The ids chosen in dialog `d`. +pub(crate) fn chosen(d: &Dialog) -> Vec { + d.fields.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect() +} + +/// The rows of `rows` the name search `query` (ignoring case) and the Show choice `show` let through. +pub(crate) fn shown<'a>(rows: &'a [Value], query: &str, show: &str) -> Vec<&'a Value> { + let q = query.trim().to_lowercase(); + rows.iter() + .filter(|r| show == "all" || command_status(r) == show) + .filter(|r| q.is_empty() || r["name"].as_str().unwrap_or_default().to_lowercase().contains(&q)) + .collect() +} + +/// All (`on`) or None: choose every row `shown`, or none of them; rows the search or Show hides +/// keep their state. +pub(crate) fn choose_shown(chosen: &mut Vec, shown: &[u64], on: bool) { + if on { + for id in shown { + if !chosen.contains(id) { + chosen.push(*id); + } + } + } else { + chosen.retain(|id| !shown.contains(id)); + } +} + +/// Tick or untick row `id`. +pub(crate) fn toggle(chosen: &mut Vec, id: u64) { + match chosen.iter().position(|c| *c == id) { + Some(i) => { + chosen.remove(i); + } + None => chosen.push(id), + } +} + +/// A status's label in the list. +fn status_label(status: &str) -> &'static str { + STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) +} + +/// The dialog: the search, the Show filter, a checkbox row per image shown (name, status, format), +/// All / None with the count chosen, and Zoom to Selection. Returns false: nothing to preview. +fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); + let query = widgets::search_field(ui, ui.scope_id().with("select-by-link-status-search"), tl!("Search images")); + d.fields.insert("__search".into(), json!(query)); + ui.add_space(4.0); + form::choice(ui, d, "show", tl!("Show:"), (60.0, 140.0), &SHOW); + let show = d.str("show"); + let visible = shown(&rows, &query, &show); + let mut picked = chosen(d); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(LIST_H).auto_shrink([false, true]).show(ui, |ui| { + if visible.is_empty() { + ui.label(egui::RichText::new(tl!("No images match.")).color(t.text_dim)); + } + for r in &visible { + let Some(id) = r["id"].as_u64() else { continue }; + let name = r["name"].as_str().unwrap_or_default(); + let status = status_label(command_status(r)); + let format = r["format"].as_str().unwrap_or_default(); + ui.horizontal(|ui| { + ui.set_min_height(ROW_H); + let on = picked.contains(&id); + let name_w = (ui.available_width() - STATUS_W - FORMAT_W - 40.0).max(60.0); + let check = ui.scope(|ui| { + ui.set_width(name_w + 24.0); + widgets::check_name(ui, name, on) + }); + if check.inner { + toggle(&mut picked, id); + } + ui.add_sized(vec2(STATUS_W, ROW_H), egui::Label::new(egui::RichText::new(status).color(t.text_dim)).truncate()); + ui.add_sized(vec2(FORMAT_W, ROW_H), egui::Label::new(egui::RichText::new(format).color(t.text_dim)).truncate()); + }); + } + }); + ui.add_space(4.0); + let ids: Vec = visible.iter().filter_map(|r| r["id"].as_u64()).collect(); + ui.horizontal(|ui| { + if widgets::flat_button_fit(ui, "All", 50.0).clicked() { + choose_shown(&mut picked, &ids, true); + } + if widgets::flat_button_fit(ui, "None", 50.0).clicked() { + choose_shown(&mut picked, &ids, false); + } + let count = crate::i18n::fmt(tl!("Chosen: {n} of {total}"), &[("n", &picked.len().to_string()), ("total", &rows.len().to_string())]); + ui.label(egui::RichText::new(count).color(t.text_dim)); + }); + d.fields.insert("ids".into(), json!(picked)); + ui.add_space(6.0); + form::check(ui, d, "zoom", tl!("Zoom to Selection")); + false +} + +/// The command's params for dialog `d`: the rows chosen, whatever their status. +pub(crate) fn params(d: &Dialog) -> Value { + json!({ "status": STATUSES.map(|(s, ..)| s), "ids": chosen(d), "zoom": d.bool("zoom") }) +} + +/// Select: select the rows chosen (and zoom to them) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + app.run(COMMAND, params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs new file mode 100644 index 0000000000..8ad61f6e5a --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -0,0 +1,201 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{COMMAND, KIND, choose_shown, message, refresh, shown, toggle}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// A fresh folder for one test (removed when dropped). +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-select-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + fn file(&self, name: &str, bytes: &[u8]) -> String { + let p = self.0.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `w` × `h` red PNG. +fn png(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + out +} + +/// A document with `river.png` linked, `harbour.png` linked and then deleted (missing), and +/// `stamp.png` embedded → (app, river, harbour, stamp). +fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let place = |app: &mut VectorcraftApp, path: &str, at: [u32; 2], link: bool| { + app.run("file.place", json!({"path": path, "at": at, "link": link})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (a, b, c) = (dir.file("river.png", &png(40, 30)), dir.file("harbour.png", &png(30, 20)), dir.file("stamp.png", &png(20, 20))); + let river = place(&mut app, &a, [100, 100], true); + let harbour = place(&mut app, &b, [300, 100], true); + let stamp = place(&mut app, &c, [200, 220], false); + std::fs::remove_file(&b).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, river, harbour, stamp) +} + +/// The selected objects' ids, sorted. +fn selected(app: &VectorcraftApp) -> Vec { + let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +#[test] +fn the_message_says_what_was_selected_and_what_was_left_out() { + assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); + assert_eq!(message(&["linked"], 1, &[]), "Selected 1 linked image"); + assert_eq!(message(&["embedded", "modified"], 2, &[]), "Selected 2 images"); + assert_eq!(message(&["missing"], 9, &["hidden", "locked", "hidden"]), "Selected 9 missing images; 3 more are hidden or locked"); + assert_eq!(message(&["modified"], 0, &["template"]), "Selected 0 modified images; 1 more is on a template layer"); + assert_eq!(message(&["embedded"], 2, &["isolation", "isolation"]), "Selected 2 embedded images; 2 more are outside the isolated group"); + assert_eq!(message(&["linked"], 1, &["isolation", "locked"]), "Selected 1 linked image; 2 more can't be selected now"); +} + +#[test] +fn the_list_filters_by_name_and_status_and_all_and_none_act_on_the_rows_shown() { + let rows = vec![ + json!({"id": 1, "name": "River.png", "status": "ok"}), + json!({"id": 2, "name": "harbour.png", "status": "missing"}), + json!({"id": 3, "name": "Stamp.png", "status": "embedded"}), + json!({"id": 4, "name": "river-2.tif", "status": "modified"}), + ]; + let ids = |v: Vec<&Value>| v.iter().map(|r| r["id"].as_u64().unwrap()).collect::>(); + assert_eq!(ids(shown(&rows, "", "all")), vec![1, 2, 3, 4]); + assert_eq!(ids(shown(&rows, " RIVER ", "all")), vec![1, 4]); + assert_eq!(ids(shown(&rows, "river", "linked")), vec![1], "ok is Linked"); + assert_eq!(ids(shown(&rows, "", "missing")), vec![2]); + assert_eq!(ids(shown(&rows, "zzz", "all")), Vec::::new()); + // Row 3 is chosen but hidden: neither All nor None touches it. + let mut c = vec![3]; + choose_shown(&mut c, &[1, 4], true); + assert_eq!(c, vec![3, 1, 4]); + choose_shown(&mut c, &[1, 4], false); + assert_eq!(c, vec![3]); + toggle(&mut c, 2); + toggle(&mut c, 3); + assert_eq!(c, vec![2]); +} + +#[test] +fn menu_items_are_on_for_the_statuses_present_and_shift_adds() { + let dir = Folder::new("menu"); + let (mut app, river, harbour, stamp) = app(&dir); + refresh(&mut app, 0.0); + let entries = menus::menu_entries(&app); + let item = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap(); + for (label, on) in + [("Select Linked", true), ("Select Embedded", true), ("Select Missing", true), ("Select Modified", false), ("Select by Link Status…", true)] + { + assert_eq!(item(label).enabled, on, "{label}"); + } + let run = |app: &mut VectorcraftApp, label: &str, shift: bool| { + let e = item(label); + let target = menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let (cmd, p) = menus::with_held_keys(target, held); + menus::invoke(app, &cmd, p); + }; + run(&mut app, "Select Missing", false); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.ui.status, "Selected 1 missing image"); + run(&mut app, "Select Embedded", true); + assert_eq!(selected(&app), vec![harbour, stamp], "Shift adds"); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), vec![river], "without Shift it replaces"); + // A hidden image is left out, and the status bar says so. + app.run("object.setProps", json!({"ids": [river], "visible": false})).unwrap(); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), Vec::::new()); + assert_eq!(app.ui.status, "Selected 0 linked images; 1 more is hidden or locked"); + // The document changes: the items follow on the next refresh. + app.run("select.set", json!({"ids": [harbour]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + refresh(&mut app, 1.0); + let entries = menus::menu_entries(&app); + let on = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap().enabled; + assert!(!on("Select Missing")); + assert!(on("Select Embedded")); +} + +#[test] +fn the_links_panel_menu_lists_the_select_items() { + let dir = Folder::new("flyout"); + let (mut app, ..) = app(&dir); + refresh(&mut app, 0.0); + let shown = painted_text(&mut app, crate::panels::links::menu); + for s in ["Select Linked", "Select Embedded", "Select Missing", "Select Modified"] { + assert!(shown.contains(s), "{s} in {shown}"); + } +} + +#[test] +fn the_dialog_lists_filters_and_selects_with_zoom() { + let dir = Folder::new("dialog"); + let (mut app, river, harbour, stamp) = app(&dir); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0))); + let zoom_before = app.view().unwrap().zoom; + menus::invoke(&mut app, COMMAND, Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["zoom"], &d.fields["show"]), (KIND, &json!(true), &json!("all"))); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [ + "Select by Link Status", + "river.png", + "harbour.png", + "stamp.png", + "Linked", + "Missing", + "Embedded", + "PNG", + "Zoom to Selection", + "Chosen: 0 of 3", + "All", + "None", + "Select", + ] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "Select is off with nothing chosen"); + // Show: Missing lists only the missing image. + app.ui.dialog.as_mut().unwrap().fields.insert("show".into(), json!("missing")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("harbour.png") && !shown.contains("river.png") && !shown.contains("stamp.png"), "{shown}"); + // Choose two and Select: they are selected and the view zooms to them. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([river, stamp])); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(selected(&app), vec![river, stamp]); + assert_eq!(app.ui.status, "Selected 2 images"); + assert_ne!(app.view().unwrap().zoom, zoom_before, "zoomed to the selection"); + // Without Zoom to Selection the view stays. + menus::invoke(&mut app, COMMAND, Value::Null); + let zoom = app.view().unwrap().zoom; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([harbour])); + d.fields.insert("zoom".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.view().unwrap().zoom, zoom); +} diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs new file mode 100644 index 0000000000..e7971bb888 --- /dev/null +++ b/crates/ui-egui/src/addons/shapes.rs @@ -0,0 +1,311 @@ +//! The 3D Box and customizable shapes add-on in the interface: its submenu (Object › Plug-ins › +//! 3D Box), which selects the 3D Box tool, and the context-sensitive Control bar options shown +//! when a shape tool (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `spiral`, +//! `box3d`) is active. + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_geom::shapes::EllipseMode; +use vectorcraft_tools::addons::box3d::{self, CustomShape}; + +use crate::menus::Item; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +pub fn menu() -> Vec { + vec![Item::Cmd("3D Box Tool", "tool.select", json!({"tool": box3d::ID}))] +} + +/// Draw context-sensitive shape customization controls in the top Control bar when a shape tool is +/// active. Returns `true` when controls were drawn. +pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { + let tool = app.session.tool_id().to_string(); + if !matches!(tool.as_str(), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "spiral" | "box3d") { + return false; + } + let opts = app.session.tool_options(); + let active_shape = if tool == "box3d" { opts["shape"].as_str().unwrap_or("box3d").to_string() } else { tool.clone() }; + let selected_custom: Option = app.session.active().and_then(|st| { + st.selection.objects.iter().find_map(|&id| st.doc.node(id).and_then(|n| CustomShape::read_for_update(n, active_shape == "spiral"))) + }); + + if tool == "box3d" { + for (s_id, lbl, icon) in [ + ("box3d", "3D Box", "box"), + ("rectangle", "Rectangle", "square"), + ("ellipse", "Ellipse", "dc-ellipse"), + ("polygon", "Polygon", "dc-polygon"), + ("star", "Star", "star"), + ("spiral", "Spiral", "tornado"), + ] { + if widgets::icon_button(ui, icon, tl!(lbl), active_shape == s_id, 22.0).clicked() { + app.run("tool.setOption", json!({ "key": "shape", "value": s_id })).ok(); + } + } + ui.separator(); + } + + match active_shape.as_str() { + "ellipse" => draw_ellipse_controls(app, ui, &opts, selected_custom), + "rectangle" | "roundedRectangle" => draw_rectangle_controls(app, ui, &opts, selected_custom), + "polygon" | "star" => draw_polygon_controls(app, ui, &opts, &active_shape, selected_custom), + "spiral" => draw_spiral_controls(app, ui, &opts, selected_custom), + "box3d" => draw_box3d_controls(app, ui, &opts, selected_custom), + _ => return false, + } + true +} + +fn apply_shape(app: &mut VectorcraftApp, tool_kvs: &[(&str, Value)], live_patch: Value) { + for (k, v) in tool_kvs { + app.run("tool.setOption", json!({ "key": *k, "value": v.clone() })).ok(); + } + if app.session.active().is_some_and(|st| !st.selection.is_empty()) { + app.run("addon.shapes.configure", live_patch).ok(); + } +} + +fn draw_arc_controls(app: &mut VectorcraftApp, ui: &mut Ui, start_deg: f64, end_deg: f64, mode: &str) { + let t = Tokens::get(ui.ctx()); + widgets::field_label(ui, egui::RichText::new(tl!("Start:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "arc-start"), start_deg, "°", 1, 52.0) { + let next_mode = if mode == "whole" { "pie" } else { mode }; + apply_shape(app, &[("arcStart", json!(v)), ("arcMode", json!(next_mode))], json!({ "startAngle": v, "arcMode": next_mode })); + } + widgets::field_label(ui, egui::RichText::new(tl!("End:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "arc-end"), end_deg, "°", 1, 52.0) { + let next_mode = if mode == "whole" { "pie" } else { mode }; + apply_shape(app, &[("arcEnd", json!(v)), ("arcMode", json!(next_mode))], json!({ "endAngle": v, "arcMode": next_mode })); + } + for (m_id, tip_label, icon) in + [("pie", "Slice", "circle-dot"), ("chord", "Closed", "circle-off"), ("arc", "Arc", "dc-arc"), ("whole", "Open", "dc-ellipse")] + { + if widgets::icon_button(ui, icon, tl!(tip_label), mode == m_id, 22.0).clicked() { + let (s0, e0) = if m_id == "whole" { + (0.0, 0.0) + } else if (end_deg - start_deg).abs() < 1e-4 || ((end_deg - start_deg).abs() - 360.0).abs() < 1e-4 { + (0.0, 270.0) + } else { + (start_deg, end_deg) + }; + apply_shape( + app, + &[("arcMode", json!(m_id)), ("arcStart", json!(s0)), ("arcEnd", json!(e0))], + json!({ "arcMode": m_id, "startAngle": s0, "endAngle": if m_id == "whole" { 360.0 } else { e0 } }), + ); + } + } +} + +fn draw_ellipse_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let (start_deg, end_deg, mode) = match selected_custom { + Some(CustomShape::Ellipse { pie: (a0, a1), arc_mode, .. }) => (a0, a1, mode_str(arc_mode)), + _ => (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")), + }; + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape(app, &[("arcMode", json!("whole")), ("arcStart", json!(0.0)), ("arcEnd", json!(0.0))], json!({ "reset": true })); + } + ui.separator(); +} + +fn draw_rectangle_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let unit = app.session.general_unit(); + let sym = opts["cornerSymmetry"].as_bool().unwrap_or(true); + let mut radii = [opts["cornerRadius"].as_f64().unwrap_or(12.0); 4]; + if let Some(arr) = opts["cornerRadii"].as_array() + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + radii[i] = item.as_f64().unwrap_or(radii[i]); + } + } + let (mut start_deg, mut end_deg, mut mode) = + (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")); + if let Some(CustomShape::Rectangle { radii: nr, pie: (a0, a1), arc_mode, .. }) = selected_custom { + radii = nr; + start_deg = a0; + end_deg = a1; + mode = mode_str(arc_mode); + } + if widgets::icon_button(ui, if sym { "link" } else { "unlink" }, tl!("Link"), sym, 22.0).clicked() { + let next_sym = !sym; + apply_shape(app, &[("cornerSymmetry", json!(next_sym))], if next_sym { json!({ "radius": radii[0] }) } else { json!({ "radii": radii }) }); + } + if sym { + widgets::field_label(ui, egui::RichText::new(tl!("Radius:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::num_field(ui, ("cb-shape", "rect-r"), Some(radii[0]), unit, 54.0) { + let r = v.max(0.0); + apply_shape(app, &[("cornerRadius", json!(r)), ("cornerRadii", json!([r, r, r, r]))], json!({ "radius": r })); + } + } else { + for (i, lbl) in [(0, "TL"), (1, "TR"), (2, "BR"), (3, "BL")] { + widgets::field_label(ui, egui::RichText::new(lbl).size(11.0).color(t.text_dim)); + if let Some(v) = widgets::num_field(ui, ("cb-shape-r", i), Some(radii[i]), unit, 44.0) { + let mut next = radii; + next[i] = v.max(0.0); + apply_shape(app, &[("cornerRadii", json!(next))], json!({ "radii": next })); + } + } + } + ui.separator(); + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[ + ("cornerRadius", json!(0.0)), + ("cornerRadii", json!([0.0, 0.0, 0.0, 0.0])), + ("arcMode", json!("whole")), + ("arcStart", json!(0.0)), + ("arcEnd", json!(0.0)), + ], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn draw_polygon_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, active_shape: &str, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let mut is_star = if active_shape == "star" { true } else { opts["polyIsStar"].as_bool().unwrap_or(false) }; + let mut count = if is_star { opts["points"].as_u64().unwrap_or(5) } else { opts["sides"].as_u64().unwrap_or(6) } as u32; + let mut spoke = opts["starRatio"].as_f64().unwrap_or(0.5); + let mut rounded = opts["rounded"].as_f64().unwrap_or(0.0); + let mut randomized = opts["randomized"].as_f64().unwrap_or(0.0); + let (mut start_deg, mut end_deg, mut mode) = + (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")); + if let Some(CustomShape::Polygon { sides, spoke_ratio, rounded: rnd, randomized: rand, pie: (a0, a1), arc_mode, .. }) = selected_custom { + count = sides; + is_star = spoke_ratio.is_some(); + if let Some(sr) = spoke_ratio { + spoke = sr; + } + rounded = rnd; + randomized = rand; + start_deg = a0; + end_deg = a1; + mode = mode_str(arc_mode); + } + if widgets::icon_button(ui, "dc-polygon", tl!("Polygon"), !is_star, 22.0).clicked() { + apply_shape(app, &[("polyIsStar", json!(false))], json!({ "isStar": false })); + } + if widgets::icon_button(ui, "star", tl!("Star"), is_star, 22.0).clicked() { + apply_shape(app, &[("polyIsStar", json!(true))], json!({ "isStar": true, "spokeRatio": spoke })); + } + widgets::field_label(ui, egui::RichText::new(if is_star { tl!("Points:") } else { tl!("Sides:") }).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-corners"), f64::from(count), "", 0, 44.0) { + let c = (v.round() as i64).clamp(3, 1000) as u32; + apply_shape(app, &[("sides", json!(c)), ("points", json!(c))], json!({ "sides": c })); + } + if is_star { + widgets::field_label(ui, egui::RichText::new(tl!("Ratio")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-spoke"), spoke, "", 2, 46.0) { + let sr = v.clamp(0.01, 1.0); + apply_shape(app, &[("starRatio", json!(sr))], json!({ "spokeRatio": sr })); + } + } + widgets::field_label(ui, egui::RichText::new(tl!("Round")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-round"), rounded, "", 2, 46.0) { + let rnd = v.clamp(-10.0, 10.0); + apply_shape(app, &[("rounded", json!(rnd))], json!({ "rounded": rnd })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Random")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-rand"), randomized, "", 2, 46.0) { + let rand = v.clamp(-10.0, 10.0); + apply_shape(app, &[("randomized", json!(rand))], json!({ "randomized": rand })); + } + ui.separator(); + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[("rounded", json!(0.0)), ("randomized", json!(0.0)), ("arcMode", json!("whole")), ("arcStart", json!(0.0)), ("arcEnd", json!(0.0))], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn draw_spiral_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let (mut turns, mut divergence, mut inner_r) = + (opts["turns"].as_f64().unwrap_or(3.0), opts["divergence"].as_f64().unwrap_or(1.0), opts["innerRadius"].as_f64().unwrap_or(0.0)); + if let Some(CustomShape::Spiral { turns: t_v, divergence: div_v, inner_radius: ir_v, .. }) = selected_custom { + turns = t_v; + divergence = div_v; + inner_r = ir_v; + } + widgets::field_label(ui, egui::RichText::new(tl!("Segments")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-turns"), turns, "", 2, 50.0) { + let tv = v.clamp(0.01, 1024.0); + apply_shape(app, &[("turns", json!(tv))], json!({ "turns": tv })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Ratio")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-div"), divergence, "", 2, 50.0) { + let dv = v.clamp(0.0, 1000.0); + apply_shape(app, &[("divergence", json!(dv))], json!({ "divergence": dv })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Inner Radius:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-inner"), inner_r, "", 2, 50.0) { + let iv = v.clamp(0.0, 0.999); + apply_shape(app, &[("innerRadius", json!(iv))], json!({ "innerRadius": iv })); + } + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape(app, &[("turns", json!(3.0)), ("divergence", json!(1.0)), ("innerRadius", json!(0.0))], json!({ "reset": true })); + } + ui.separator(); +} + +fn draw_box3d_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let (mut ax, mut ay, mut az) = + (opts["angleX"].as_f64().unwrap_or(30.0), opts["angleY"].as_f64().unwrap_or(30.0), opts["angleZ"].as_f64().unwrap_or(0.0)); + let (mut px, mut py, mut pz) = + (opts["parallelX"].as_bool().unwrap_or(false), opts["parallelY"].as_bool().unwrap_or(true), opts["parallelZ"].as_bool().unwrap_or(false)); + if let Some(CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. }) = selected_custom { + ax = angle_x; + ay = angle_y; + az = angle_z; + px = parallel_x; + py = parallel_y; + pz = parallel_z; + } + for (lbl, a_key, p_key, a_val, p_val) in + [("X:", "angleX", "parallelX", ax, px), ("Y:", "angleY", "parallelY", ay, py), ("Angle:", "angleZ", "parallelZ", az, pz)] + { + widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-box3d", a_key), a_val, "°", 1, 52.0) { + apply_shape(app, &[(a_key, json!(v))], json!({ a_key: v })); + } + if widgets::icon_button(ui, "dc-line", tl!("Link"), p_val, 20.0).clicked() { + let next = !p_val; + apply_shape(app, &[(p_key, json!(next))], json!({ p_key: next })); + } + } + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[ + ("angleX", json!(30.0)), + ("angleY", json!(30.0)), + ("angleZ", json!(0.0)), + ("parallelX", json!(false)), + ("parallelY", json!(true)), + ("parallelZ", json!(false)), + ], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn mode_str(m: EllipseMode) -> &'static str { + match m { + EllipseMode::Slice => "pie", + EllipseMode::Chord => "chord", + EllipseMode::Arc => "arc", + EllipseMode::Whole => "whole", + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index eb9c3526e1..4698856dfd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -105,6 +105,7 @@ impl VectorcraftApp { pending_url: None, control_rx: None, deferred_control: None, + synthetic_dropped_before: 0, pending_screenshots: vec![], queued_screenshots: vec![], screenshot_token: 0, @@ -195,6 +196,9 @@ impl VectorcraftApp { if let Some(read) = s.read.take() { s.read = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| read(p)))); } + if let Some(read_head) = s.read_head.take() { + s.read_head = Some(Box::new(move |p: &str, max: usize| file_access::check_read(p).and_then(|()| read_head(p, max)))); + } if let Some(mut write) = s.write.take() { s.write = Some(Box::new(move |p: &str, b: &[u8]| file_access::check_write(p).and_then(|()| write(p, b)))); } @@ -279,6 +283,7 @@ impl VectorcraftApp { let now = now_secs(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A // background thread reads it where the host installs one (an unresponsive owner must never @@ -314,6 +319,7 @@ impl VectorcraftApp { placing::poll(self); #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); + crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.plugin_runs.running.is_empty() diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 775248a611..0652e6d9a6 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,6 +1,7 @@ use super::fonts::MAX_RECENT_FONTS; use super::{Value, VectorcraftApp, dialogs, fileio, io, menus, panels, picks, toolbar}; use crate::placing; +use crate::state::ReplaceFontWarning; /// The last repeatable Pathfinder operation completed by a command or atomic batch. fn completed_pathfinder_operation<'a>(id: &'a str, params: &'a Value) -> Option<&'a str> { @@ -12,6 +13,63 @@ fn completed_pathfinder_operation<'a>(id: &'a str, params: &'a Value) -> Option< } } +fn substitute_style_description(font: &Value) -> Option { + if font["status"] != "substitute" { + return None; + } + let family = font["family"].as_str()?; + let style = font["style"].as_str()?; + let resolved_family = font["resolved"]["family"].as_str()?; + let resolved_style = font["resolved"]["style"].as_str()?; + Some(format!("{family} {style} is drawn in {resolved_family} {resolved_style}")) +} + +fn substitute_warnings(fonts: &[Value], styles: &[(String, String)]) -> (Vec, Vec) { + let mut missing = Vec::new(); + let mut live_styles = Vec::new(); + for font in fonts.iter().filter(|font| { + styles.iter().any(|(family, style)| { + font["family"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(family)) + && font["style"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(style)) + }) + }) { + match font["status"].as_str() { + Some("missing") => { + if let Some(family) = font["family"].as_str() { + missing.push(family.to_string()); + } + } + Some("substitute") => { + if let Some(description) = substitute_style_description(font) { + live_styles.push(description); + } + } + _ => {} + } + } + missing.sort(); + missing.dedup(); + live_styles.sort(); + live_styles.dedup(); + (missing, live_styles) +} + +#[cfg(test)] +#[test] +fn substitute_warnings_follow_current_font_inventory() { + let styles = vec![("Source Sans 3".to_string(), "Black Wide".to_string())]; + let replaced_face = serde_json::json!([{ + "family": "Source Sans 3", "style": "Black Wide", "status": "substitute", + "resolved": {"family": "Inter", "style": "Bold"} + }]); + assert_eq!( + substitute_warnings(replaced_face.as_array().unwrap(), &styles), + (Vec::::new(), vec!["Source Sans 3 Black Wide is drawn in Inter Bold".to_string()]) + ); + let removed_family = serde_json::json!([{"family": "Source Sans 3", "style": "Black Wide", "status": "missing"}]); + assert_eq!(substitute_warnings(removed_family.as_array().unwrap(), &styles), (vec!["Source Sans 3".to_string()], Vec::::new())); +} + impl VectorcraftApp { /// Run a UI or engine command by id. The single entry point for every frontend path. pub fn run(&mut self, id: &str, params: Value) -> Result { @@ -145,6 +203,7 @@ impl VectorcraftApp { self.publish_clipboard(); } self.sync_views(); + self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. self.follow_artboard_tool(artboards); match &r { @@ -188,22 +247,113 @@ impl VectorcraftApp { r.insert(0, font.to_string()); r.truncate(MAX_RECENT_FONTS); } - if id == "text.replaceFont" - && v.get("warning").is_none() - && self.ui.status.starts_with("some text is hidden or locked, so its font wasn't replaced") - { - self.ui.status.clear(); + if id == "text.replaceFont" { + self.update_replace_font_status(¶ms, v); } // A command's warning (Rasterize's when an image couldn't be decoded) shows in the // status bar, as a tool preview's does. if let Some(w) = v.get("warning").and_then(Value::as_str) { - self.ui.status = w.to_string(); + self.set_command_warning(id, w); } } } r } + fn set_command_warning(&mut self, id: &str, warning: &str) { + self.ui.status = warning.to_string(); + if id != "text.replaceFont" { + self.ui.replace_font_warning = None; + } + } + + fn update_replace_font_status(&mut self, params: &Value, result: &Value) { + if let Some(warning) = result.get("warning").and_then(Value::as_str) { + let Some((document_uid, revision)) = self.session.active().map(|doc| (doc.uid, doc.revision)) else { + return; + }; + let styles = self + .session + .execute("text.fonts", &serde_json::json!({})) + .ok() + .and_then(|value| value.as_array().cloned()) + .map(|fonts| { + fonts + .iter() + .filter_map(|font| { + let description = substitute_style_description(font)?; + if !warning.contains(&description) { + return None; + } + Some((font["family"].as_str()?.to_string(), font["style"].as_str()?.to_string())) + }) + .collect::>() + }) + .unwrap_or_default(); + let selection: Option> = (params["selectionOnly"] == true) + .then(|| self.session.active().map(|doc| doc.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default()); + self.ui.replace_font_warning = + Some(ReplaceFontWarning { document_uid, revision, request: params.clone(), selection, text: warning.to_string(), styles }); + return; + } + self.refresh_replace_font_warning(true); + } + + pub(super) fn refresh_replace_font_warning(&mut self, force: bool) { + const SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced"; + const STYLE_PREFIX: &str = "font styles that aren't available are drawn in the closest style: "; + const STYLE_SUFFIX: &str = " (pick a style the family has)"; + let Some(previous) = self.ui.replace_font_warning.as_ref() else { + return; + }; + let Some(revision) = self.session.active().filter(|doc| doc.uid == previous.document_uid).map(|doc| doc.revision) else { + return; + }; + if (!force && revision == previous.revision) || previous.text != self.ui.status { + return; + } + let had_skipped = self.ui.status.starts_with(SKIPPED); + let had_style = !previous.styles.is_empty(); + if !had_skipped && !had_style { + return; + } + let scoped_selection = previous.selection.as_ref().map(|selected| selected.iter().copied().map(vectorcraft_doc::NodeId).collect::>()); + let skipped_remains = if had_skipped { + self.session.skipped_font_ids(&previous.request, scoped_selection.as_deref()).is_ok_and(|ids| !ids.is_empty()) + } else { + false + }; + let (missing, live_styles) = if had_style { + let Some(fonts) = self.session.font_inventory(scoped_selection.as_deref()).ok().and_then(|value| value.as_array().cloned()) else { + return; + }; + substitute_warnings(&fonts, &previous.styles) + } else { + (Vec::new(), Vec::new()) + }; + let mut parts = Vec::new(); + if skipped_remains { + parts.push(SKIPPED.to_string()); + } + if !missing.is_empty() { + parts.push(format!( + "fonts that aren't available are drawn in the fallback font, {}: {} (install them, or replace them with Find Font)", + vectorcraft_text::FALLBACK_FAMILY, + missing.join(", ") + )); + } + if !live_styles.is_empty() { + parts.push(format!("{STYLE_PREFIX}{}{STYLE_SUFFIX}", live_styles.join(", "))); + } + self.ui.status = parts.join("; "); + if self.ui.status.is_empty() { + self.ui.replace_font_warning = None; + } else if let Some(warning) = &mut self.ui.replace_font_warning { + warning.revision = revision; + warning.text.clone_from(&self.ui.status); + } + } + /// Select a tool (also used by the toolbar and shortcuts). pub fn select_tool(&mut self, id: &str) { // The tip of a pen whose eraser end selected the Eraser doesn't undo this choice. diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index cde629466c..2f64432821 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -10,10 +10,25 @@ impl VectorcraftApp { let mut handled = 0; while handled < control::MAX_CONTROL_REQUESTS_PER_FRAME { let Some(req) = self.deferred_control.take().or_else(|| rx.try_recv().ok()) else { break }; - // `ui.pointer` drives the tool at once, while `ui.key` and the other synthetic input - // reach it in a later UI pass: a pointer request waits until the input sent before it - // was applied, so a key pressed during a drag changes the drag before its release. - if req.method == "ui.pointer" && (!self.synthetic.is_empty() || self.synthetic_injected) { + // Synthetic input sent before this tool action was dropped (see + // `discard_stale_injected_batch`): it would reach the tool without that input. + let tool_action = matches!(req.method.as_str(), "ui.pointer" | "ui.tool.select"); + if tool_action && req.made_before(self.synthetic_dropped_before) { + // One its caller gave up is skipped without counting toward this frame's limit. + if req.claim() { + handled += 1; + let _ = req.reply.send(json!({ + "ok": false, + "error": "input sent before this tool action was dropped because the document, dialog or focus changed" + })); + } + continue; + } + // `ui.pointer` and `ui.tool.select` act at once, while `ui.key` and other synthetic + // input reach the tool in a later UI pass. Wait for that earlier input, so a key + // pressed during a drag reaches its tool before a pointer event or tool switch. + // One its caller gave up meanwhile is dropped below instead of holding back the rest. + if tool_action && !req.given_up() && (!self.synthetic.is_empty() || self.synthetic_injected) { self.deferred_control = Some(req); ctx.request_repaint(); break; diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2854e11d6a..29baa37d23 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -123,6 +123,9 @@ impl VectorcraftApp { self.synthetic_modifiers = false; self.synthetic_injected = false; self.synthetic_frame = false; + // The `ui.pointer` requests made after this input, waiting or still on the channel, would + // run without it: `drain_control` answers the ones made before now with an error. + self.synthetic_dropped_before = crate::control::ControlRequest::next_seq(); } /// Release the pointer buttons egui still holds down when the system reports that no mouse diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index a1c898b719..9895149917 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -5,17 +5,13 @@ impl VectorcraftApp { /// opens in a floating window while Open Documents As Tabs is cleared). The views Window › New /// Window opened go with their documents. /// - /// A view stays with its document when the documents change order (`document.move`, also in a - /// recording or a batch, #5663): while every view still has the document it was synced with, - /// they are put in the documents' order by uid. Code that removed a view by hand (closing a - /// document) leaves them aligned by index, as before. + /// A view stays with its document when documents change order or close (`document.move`, + /// `file.close`, also several of them in one recording or batch, #5663): the views are matched + /// to the documents by the uid each was synced with, a closed document's view is dropped and a + /// new document gets its saved view. pub fn sync_views(&mut self) { let docs = self.session.documents(); - if self.view_uids.len() == self.views.len() - && docs.len() == self.views.len() - && docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()) - && docs.iter().all(|d| self.view_uids.contains(&d.uid)) - { + if self.view_uids.len() == self.views.len() && docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()) { let mut old: Vec> = std::mem::take(&mut self.views).into_iter().map(Some).collect(); self.views = docs .iter() @@ -30,6 +26,7 @@ impl VectorcraftApp { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } self.view_uids = docs.iter().map(|d| d.uid).collect(); + panels::layers::retain_open_thumbs(&self.view_uids); crate::doc_windows::retain_views(self); crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f99c524f12..8e3315e357 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -550,25 +550,28 @@ fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); } } - // Upload finished background renders whenever they are not older than what is currently - // displayed on screen. This prevents canvas freezes during continuous edits (drags, arrow - // nudges, MCP command bursts) while ensuring obsolete out-of-order frames are dropped. - if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll()) - && done.key.doc == key_doc - { - let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision); - if not_older { - upload(app, ui.ctx(), done.img, done.key.pixel.is_some()); - app.canvas.key = Some(done.key); - app.canvas.shown = Some((done.doc, done.opts)); - app.perf.render_ms = done.ms; - app.canvas.last_ms = done.ms; - app.canvas.moved = done.moved > 0; - app.canvas.from_worker = true; - } + if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll()) { + show_worker_frame(app, ui.ctx(), done, key_doc); } } +/// Upload frame `done` from the render worker when it is of document `key_doc` and not older than +/// the frame shown. This prevents canvas freezes during continuous edits (drags, arrow nudges, MCP +/// command bursts) while ensuring obsolete out-of-order frames are dropped. +fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate::render_worker::Done, key_doc: usize) { + let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision); + if done.key.doc != key_doc || !not_older { + return; + } + upload(app, ctx, done.img, done.key.pixel.is_some()); + app.canvas.key = Some(done.key); + app.canvas.shown = Some((done.doc, done.opts)); + app.perf.render_ms = done.ms; + app.canvas.last_ms = done.ms; + app.canvas.moved = done.moved > 0; + app.canvas.from_worker = true; +} + /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. fn frame_view(pixel: Option<[i64; 4]>, (w, h): (u32, u32), v: &View, ppp: f32) -> (u32, u32, Affine) { match pixel { @@ -645,16 +648,26 @@ struct Frame<'a> { pixel: Option<[i64; 4]>, } +/// How long the UI thread waits for a document's first frame from the render worker before it +/// shows the document's paper without the art: about a frame at 60 Hz. +pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); + fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let Frame { key, doc, size: (w, h), view, opts, pixel } = frame; + // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this // thread's renderer has none, so a frame fast on the worker would be slow here. let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; - let heavy = (app.canvas.last_ms > 8.0 || settling || staying) && app.canvas.texture.is_some() && same_doc; + // A document's first frame (opened, or its tab chosen) renders on the worker too: how long it + // takes is not known yet, and a heavy one froze the window for seconds (#4155). Its paper and + // artboards show meanwhile. + let first = app.canvas.texture.is_none() || !same_doc; + let heavy = first || app.canvas.last_ms > 8.0 || settling || staying; let changed = changed_pixels(app, key, doc, &opts, view, w, h); + let mut landed = None; match (&mut app.canvas.worker, heavy, changed) { // Only the document changed since the frame shown, in a part of it: that part is // rendered again, here, into the texture. `last_ms` stays the whole frame's. @@ -671,15 +684,22 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.shown = Some((doc.clone(), opts.clone())); app.perf.render_ms = now_ms() - t0; } - (Some(worker), true, None) => worker.submit(crate::render_worker::Job { - key: key.clone(), - doc: doc.clone(), - w, - h, - view, - opts, - scope: vectorcraft_engine::file_access::ScopeHandle::capture(), - }), + (Some(worker), true, None) => { + let queued = worker.submit(crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w, + h, + view, + opts, + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + }); + // A light document's first frame is ready within the grace and shows in this frame, + // with no frame of bare paper. Waited for once, when the frame is queued. + if first && queued { + landed = worker.wait(FIRST_FRAME_GRACE); + } + } _ => { let t0 = now_ms(); let img = app.canvas.renderer.render(doc, w, h, view, &opts); @@ -692,6 +712,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.from_worker = false; } } + if let Some(done) = landed { + show_worker_frame(app, ui.ctx(), done, key.doc); + } } /// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b98e186481..206b095cab 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -90,12 +90,21 @@ fn curve_point(p: &egui::Painter, c: Pos2, color: Color32, filled: bool, size: f } pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { - // The Selection tool's bounding box (rotated with the objects after a rotation). It hides while - // a drag moves or resizes the selection, so only the art is seen going with the pointer (#712). + // The Selection tool's bounding box (rotated with the objects after a rotation), also shown by + // the shape tools that keep a shape just drawn ready to adjust while they draw none (#5477). It + // hides while a drag moves or resizes the selection, so only the art is seen going with the + // pointer (#712). // With Real-time Drawing off the art waits for the release of a move drag, and the box moves // with the pointer instead. let moved = app.session.deferred_move(); - let show_box = app.session.tool_id() == "selection" + let shape_tool = vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()); + // A shape tool drawing a shape shows none of this; adjusting a widget, it shows the widgets. + let drawing = shape_tool && app.session.tool_busy() && !app.session.tool_transforming(); + // Cmd held lends the Selection tool to a press (Direct Selection's included, #3901): its box + // shows while the key is down, where its handles take that press. + let held = super::drag::mods(p.ctx().input(|i| i.modifiers), false); + let lends_selection = !app.session.tool_busy() && app.session.lent_tool_id(&held) == Some("selection"); + let show_box = (app.session.tool_id() == "selection" || lends_selection || (shape_tool && !app.session.tool_busy())) && (!app.session.tool_transforming() || moved.is_some()) && app.ui.view.bounding_box && app.session.active().is_some_and(|st| !st.selection.is_empty() && st.selection.anchors.is_empty()); @@ -250,8 +259,9 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: anchor_square(p, xf.to_screen(a.p), color, false, anchor(direct)); } } - // Live Corners widgets (Selection on a live rectangle or polygon, Direct Selection on any path). - if matches!(tool, "selection" | "directSelection") + // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon, Direct + // Selection on any path). + if (matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing)) && let Some(w) = vectorcraft_tools::corners::CornerWidgets::showing( &st.doc, &st.selection, @@ -287,7 +297,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: } // Pie widgets (Selection tool, with View › Show Bounding Box, on live ellipses): each joined // by a line to the outline's point at its angle. They stay while one is dragged. - if tool == "selection" && app.ui.view.bounding_box { + if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f6f9f0ff6..dcb9b5312f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1466,9 +1466,10 @@ fn a_huge_selection_of_type_images_symbols_or_meshes_shows_its_bounds() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.ui.task_bar = false; - // The Rectangle tool draws nothing of its own (no bounding box, no type on a path - // brackets): only the selection's overlay changes the frame. - app.select_tool("rectangle"); + // The Line Segment tool draws nothing of its own (no bounding box, no type on a path + // brackets; the box-drawing shape tools show the bounding box, #5477): only the + // selection's overlay changes the frame. + app.select_tool("lineSegment"); match kind { "point type" => { app.session.execute("text.create", &json!({"x": 20, "y": 40, "text": "Type"})).unwrap(); @@ -6233,6 +6234,141 @@ fn ime_edge_orders_never_eat_committed_text_or_lose_the_composition() { assert_eq!(plain(&app, id), "雅がくらくか"); } +/// Starts editing new point type with the Type tool; returns its id. +fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + typing_frame(app, ctx, vec![]); + app.select_tool("type"); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = xf.to_screen(Point::new(100.0, 100.0)); + let click = + |p: Pos2, pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + typing_frame(app, ctx, vec![egui::Event::PointerMoved(at), click(at, true)]); + typing_frame(app, ctx, vec![click(at, false)]); + assert!(app.session.tool_wants_text()); + app.session.active().unwrap().selection.objects[0].0 +} + +/// Returns a key press and its release. +fn tap(key: egui::Key) -> [egui::Event; 2] { + [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) +} + +/// Arrows, Home, End, Tab, Enter and clipboard events go to the Type tool in order with the text +/// of the same frame, and each Enter types a line break. +#[test] +fn the_type_tool_takes_text_and_editing_keys_in_the_order_they_came() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + typing_frame(&mut app, &ctx, vec![text("ax")]); + // ← moves the caret before the text that follows it goes in. + typing_frame(&mut app, &ctx, [tap(egui::Key::ArrowLeft).to_vec(), vec![text("b")]].concat()); + assert_eq!(plain(&app, id), "abx"); + // Home and End move the caret before the text that follows each goes in. + typing_frame(&mut app, &ctx, [tap(egui::Key::Home).to_vec(), vec![text("0")], tap(egui::Key::End).to_vec(), vec![text("9")]].concat()); + assert_eq!(plain(&app, id), "0abx9"); + // Tab and a paste go in between the texts around them. + let paste = egui::Event::Paste("p".into()); + typing_frame(&mut app, &ctx, [vec![text("t")], tap(egui::Key::Tab).to_vec(), vec![text("u"), paste, text("q")]].concat()); + assert_eq!(plain(&app, id), "0abx9t\tupq"); + // Enter types its line break between the texts around it, once for each press. + typing_frame(&mut app, &ctx, [vec![text("1")], tap(egui::Key::Enter).to_vec(), tap(egui::Key::Enter).to_vec(), vec![text("2")]].concat()); + assert_eq!(plain(&app, id), "0abx9t\tupq1\n\n2"); + // A key that comes before a composition starts in the same frame still moves the caret. + typing_frame(&mut app, &ctx, [tap(egui::Key::Home).to_vec(), vec![preedit("k", 1)]].concat()); + typing_frame(&mut app, &ctx, vec![preedit("", 0), egui::Event::Ime(egui::ImeEvent::Commit("k".into()))]); + assert_eq!(plain(&app, id), "0abx9t\tupq1\n\nk2"); +} + +/// Enter keeps each key event's modifiers while sharing a frame with typed text. +#[test] +fn shift_enter_types_a_soft_return_in_order_with_plain_enter() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + let enter = + |modifiers| [true, false].map(|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers }); + typing_frame( + &mut app, + &ctx, + [vec![text("a")], enter(egui::Modifiers::SHIFT).to_vec(), vec![text("b")], enter(egui::Modifiers::NONE).to_vec(), vec![text("c")]].concat(), + ); + assert_eq!(plain(&app, id), "a\u{2028}b\nc"); +} + +/// Within one frame, Home between two texts, Tab inside a line, and Backspace after a paste each +/// act on the text as the events before them left it. +#[test] +fn home_tab_and_backspace_act_on_the_text_before_them_in_the_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + typing_frame(&mut app, &ctx, vec![text("abc")]); + typing_frame(&mut app, &ctx, [vec![text("d")], tap(egui::Key::Home).to_vec(), vec![text("0")]].concat()); + assert_eq!(plain(&app, id), "0abcd"); + typing_frame(&mut app, &ctx, [tap(egui::Key::ArrowRight).to_vec(), tap(egui::Key::Tab).to_vec(), vec![text("t")]].concat()); + assert_eq!(plain(&app, id), "0a\ttbcd"); + typing_frame(&mut app, &ctx, [tap(egui::Key::End).to_vec(), vec![egui::Event::Paste("pq".into())], tap(egui::Key::Backspace).to_vec()].concat()); + assert_eq!(plain(&app, id), "0a\ttbcdp"); +} + +/// In a frame that began composing, an editing key after the IME's commit applies before the text +/// that follows it; a key before the commit and an Enter after it stay the IME's. +#[test] +fn editing_keys_after_an_ime_commit_apply_in_the_same_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + let commit = |t: &str| egui::Event::Ime(egui::ImeEvent::Commit(t.into())); + typing_frame(&mut app, &ctx, vec![text("ab")]); + typing_frame(&mut app, &ctx, vec![preedit("漢", 1)]); + typing_frame(&mut app, &ctx, [vec![preedit("", 0), commit("漢")], tap(egui::Key::ArrowLeft).to_vec(), vec![text("x")]].concat()); + assert_eq!(plain(&app, id), "abx漢"); + typing_frame(&mut app, &ctx, vec![preedit("字", 1)]); + let keys = [tap(egui::Key::ArrowLeft).to_vec(), vec![preedit("", 0), commit("字")], tap(egui::Key::Enter).to_vec()]; + typing_frame(&mut app, &ctx, keys.concat()); + assert_eq!(plain(&app, id), "abx字漢"); +} + +/// Cmd/Ctrl+Enter bound to a command runs the command and types no line break, also when a plain +/// Enter comes in the same frame. Unbound, it types a line break as Enter does. +#[test] +fn a_command_on_cmd_enter_runs_without_typing_a_line_break() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let cmd_enter = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::COMMAND, + }); + typing_frame(&mut app, &ctx, vec![egui::Event::Text("a".into())]); + typing_frame(&mut app, &ctx, cmd_enter.to_vec()); + assert_eq!(plain(&app, id), "a\n", "nothing is bound to Cmd+Enter"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.grid", "Cmd+Enter"); + crate::shortcut_editor::sync(&app.ui); + let grid = app.ui.view.grid; + typing_frame(&mut app, &ctx, cmd_enter.to_vec()); + let ran = (plain(&app, id), app.ui.view.grid); + typing_frame(&mut app, &ctx, [tap(egui::Key::Enter).to_vec(), cmd_enter.to_vec()].concat()); + app.ui.shortcut_overrides.clear(); + crate::shortcut_editor::sync(&app.ui); + assert_eq!((ran.0.as_str(), ran.1), ("a\n", !grid), "Cmd+Enter runs Show Grid only"); + assert_eq!((plain(&app, id).as_str(), app.ui.view.grid), ("a\n\n", grid), "Enter types a line break and Cmd+Enter runs Show Grid"); +} + /// Reset to a blank document, select the Type tool and click document point (100, 100), returning /// the screen position used by IME fixtures. fn type_at(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::Pos2 { @@ -9062,3 +9198,107 @@ fn the_contour_bar_sets_corners_and_bakes() { click_contour_bar(&mut app, &ctx, "Bake"); assert!(offsets(&app).is_empty(), "baked"); } + +/// A frame the render worker finished for `job`: white pixels of the job's size. +fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { + let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; + crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0 } +} + +/// #4155: a document's first frame renders on the render worker, not on the UI thread, where a +/// heavy one froze the window for seconds while it opened. The canvas shows the document's paper +/// meanwhile, does not queue the frame again while it renders, and shows it once it lands. +#[test] +fn a_documents_first_frame_renders_on_the_worker() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let frame = |app: &mut VectorcraftApp| ctx.run_ui(raw.clone(), |ui| show(app, ui)).textures_delta.clear(); + + frame(&mut app); + let job = jobs.try_recv().expect("the first frame is queued on the worker"); + assert!(app.canvas.texture.is_none(), "not rendered on the UI thread"); + frame(&mut app); + // A placed document of a test running beside this one moves the process-wide generation in + // the key: that makes a new frame, not this one again. + assert!(jobs.try_iter().all(|j| j.key.placed != job.key.placed), "not queued again while it renders"); + assert!(app.canvas.texture.is_none()); + + done_tx.send(finished(&job)).unwrap(); + frame(&mut app); + assert!(app.canvas.texture.is_some(), "shown once it lands"); + assert_eq!(app.canvas.key.as_ref(), Some(&job.key)); + assert!(app.canvas.from_worker); +} + +/// The canvas waits for a document's first frame only briefly (`FIRST_FRAME_GRACE`): `wait` +/// returns a frame finished before or during the wait, clearing the pending job, and nothing once +/// the time is up. +#[test] +fn the_render_worker_waits_for_a_frame_only_as_long_as_asked() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, _) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0))), ..Default::default() }; + ctx.run_ui(raw, |ui| show(&mut app, ui)).textures_delta.clear(); + let job = jobs.try_recv().expect("a job to finish"); + + let (mut w, _, done_tx) = crate::render_worker::Worker::test_channel(); + let t0 = std::time::Instant::now(); + assert!(w.wait(std::time::Duration::from_millis(20)).is_none()); + assert!(t0.elapsed() >= std::time::Duration::from_millis(20), "waited the time asked"); + + w.pending = Some(job.key.clone()); + done_tx.send(finished(&job)).unwrap(); + assert_eq!(w.wait(std::time::Duration::from_secs(5)).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); + assert!(w.pending.is_none()); + + let late = finished(&job); + let sender = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + done_tx.send(late).unwrap(); + }); + assert!(w.wait(std::time::Duration::from_secs(5)).is_some(), "finished during the wait"); + sender.join().unwrap(); +} + +/// #3901: with Direct Selection, the Selection tool's bounding box shows while Cmd/Ctrl is held +/// (a press then takes its handles), and not otherwise. +#[test] +fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("directSelection"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let corner = xf.to_screen(Point::new(200.0, 150.0)); + // A frame with `modifiers` held → is a white box handle drawn at the bottom-right corner? + let handle_drawn = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + let screen = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect: screen, events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() }; + let out = ctx.run_ui(raw, |ui| show(app, ui)); + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + let mut v = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut v)); + v.iter().any(|s| matches!(s, Shape::Rect(r) if r.fill == Color32::WHITE && (r.rect.width() - 6.0).abs() < 1.0 && r.rect.center().distance(corner) < 0.5)) + }; + assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "Direct Selection alone shows no box"); + assert!(handle_drawn(&mut app, egui::Modifiers::COMMAND), "Cmd held shows the Selection tool's box"); + assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "gone once Cmd is released"); + assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); +} diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 018a4e2d94..88cc6dde0b 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -172,13 +172,95 @@ fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { /// language, the four fields, the W/H link and the item spacing ahead of each of them. With less, /// only the Transform link shows. fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { - let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; - let labels: f32 = INLINE_FIELDS.iter().map(|(_, lbl)| measure(inline_label(t, lbl).into())).sum(); + let labels: f32 = INLINE_FIELDS.iter().map(|(_, lbl)| widgets::text_width(ui, inline_label(t, lbl))).sum(); let fields = INLINE_FIELD_WIDTH * INLINE_FIELDS.len() as f32; let items = 2 * INLINE_FIELDS.len() + 1; labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The size of the Control bar's Align, Distribute and area type vertical alignment buttons. +const BUTTON: f32 = 24.0; + +/// The space ahead of the separator that ends a group of the Control bar's controls. +const GROUP_GAP: f32 = 4.0; + +/// The width of the separators of the Control bar's [`group_end`] and ahead of the Transform link. +const SEPARATOR: f32 = 6.0; + +/// The widths of the Document Setup and Preferences buttons, shown with nothing selected. +const DOCUMENT_SETUP_WIDTH: f32 = 112.0; +const PREFERENCES_WIDTH: f32 = 90.0; + +/// The room `n` of the bar's buttons take, with the spacing after each. +fn buttons_width(ui: &Ui, n: usize) -> f32 { + (BUTTON + ui.spacing().item_spacing.x) * n as f32 +} + +/// The separator that ends a group of the Control bar's controls, as [`group_end_width`] measures it. +fn group_end(ui: &mut Ui) { + ui.add_space(GROUP_GAP); + separator(ui); +} + +fn group_end_width(ui: &Ui) -> f32 { + GROUP_GAP + separator_width(ui) +} + +/// A separator [`SEPARATOR`] wide. +fn separator(ui: &mut Ui) { + ui.add(egui::Separator::default().spacing(SEPARATOR)); +} + +fn separator_width(ui: &Ui) -> f32 { + SEPARATOR + ui.spacing().item_spacing.x +} + +/// The room the controls at the end of the Control bar need: the Transform link, or Document Setup +/// and Preferences with nothing selected. The groups ahead of them (the Paragraph section, area +/// type's vertical alignment, the Align and Distribute buttons) show only while it is left, so +/// the bar trims them from its right end (#5372), after the inline X/Y/W/H fields. +fn end_width(ui: &Ui, nothing_selected: bool) -> f32 { + if nothing_selected { DOCUMENT_SETUP_WIDTH + ui.spacing().item_spacing.x + PREFERENCES_WIDTH } else { crate::panels::transform::link_width(ui) } +} + +/// Draws the Control bar's groups between its Character controls and the Transform link, and +/// returns whether the Transform link and X/Y/W/H follow (false: nothing is selected, and Document +/// Setup and Preferences, drawn here, end the bar). The groups are the Paragraph section and area +/// type's vertical alignment (#3759), then the Align buttons and, for two or more objects, the +/// Distribute buttons (a single object keeps the bar as it was); each shows only while the end of +/// the bar keeps its room. +fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize) -> bool { + let nothing = objects == 0; + if crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end_width(ui, nothing)) { + group_end(ui); + } + if crate::panels::properties::vertical_align::shown(app).is_some() + && ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end_width(ui, nothing) + && crate::panels::properties::vertical_align::buttons(app, ui, BUTTON) + { + group_end(ui); + } + if nothing { + if widgets::flat_button(ui, tl!("Document Setup"), DOCUMENT_SETUP_WIDTH).clicked() { + app.run("file.documentSetup", json!({})).ok(); + } + if widgets::flat_button(ui, tl!("Preferences"), PREFERENCES_WIDTH).clicked() { + app.run("edit.preferences", json!({})).ok(); + } + return false; + } + let end = separator_width(ui) + end_width(ui, false); + if ui.available_width() >= buttons_width(ui, 7) + end { + crate::panels::align::align_buttons(app, ui, BUTTON); + if objects > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end { + ui.add_space(GROUP_GAP); + crate::panels::align::distribute_buttons(app, ui, BUTTON); + } + separator(ui); + } + true +} + /// The Control bar (Window → Control), context-sensitive like Illustrator's. pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); @@ -283,28 +365,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); crate::panels::character::control_bar(app, ui); - // Area type: its vertical alignment in the frame (#3759). - if crate::panels::properties::vertical_align::buttons(app, ui, 24.0) { - ui.add_space(4.0); - ui.separator(); - } - if sel.is_empty() { - if widgets::flat_button(ui, tl!("Document Setup"), 112.0).clicked() { - app.run("file.documentSetup", json!({})).ok(); - } - if widgets::flat_button(ui, tl!("Preferences"), 90.0).clicked() { - app.run("edit.preferences", json!({})).ok(); - } + if !groups_before_transform(app, ui, sel.len()) { return; } - crate::panels::align::align_buttons(app, ui, 24.0); - // Two or more objects get the six Distribute Objects buttons too; a single - // object keeps the bar as it was. - if sel.len() > 1 { - ui.add_space(4.0); - crate::panels::align::distribute_buttons(app, ui, 24.0); - } - ui.separator(); // The Transform link opens the whole Transform panel (reference point, rotate, // shear, options) in a popover; X/Y/W/H follow inline while the bar has room. crate::panels::transform::link(app, ui); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 710f3ba0c0..86a85699d9 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1939,7 +1939,8 @@ fn the_control_bar_shows_the_global_edit_options() { /// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin, /// or leaves all four out and keeps the Transform link; a wider bar never leaves them out once a -/// narrower one showed them. +/// narrower one showed them. The Align buttons, and for two objects the Distribute buttons, are +/// trimmed the same way ahead of the Transform link (#5372). #[test] fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { crate::i18n::set_current(crate::i18n::Lang::EN); @@ -1954,6 +1955,33 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); let mut seen = false; + // The Align group, then for two objects the Distribute group (#5372): each by its controls. + let mut groups: Vec<(&str, Vec<&str>)> = vec![( + "Align", + vec![ + "Horizontal Align Left", + "Horizontal Align Center", + "Horizontal Align Right", + "Horizontal & Vertical Align Center", + "Vertical Align Top", + "Vertical Align Center", + "Vertical Align Bottom", + ], + )]; + if count == 2 { + groups.push(( + "Distribute", + vec![ + "Vertical Distribute Top", + "Vertical Distribute Center", + "Vertical Distribute Bottom", + "Horizontal Distribute Left", + "Horizontal Distribute Center", + "Horizontal Distribute Right", + ], + )); + } + let mut groups_seen = vec![false; groups.len()]; for width in (600..=2400).step_by(10) { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); let mut nodes = Vec::new(); @@ -1980,7 +2008,24 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { } assert!(!seen || fields[3].is_some(), "{count} objects, {width}: left out after a narrower bar showed them"); seen |= fields[3].is_some(); + // The Align and Distribute buttons show whole inside the margin, with the Transform + // link after them, or are left out; once shown, a wider bar keeps them. + let end = |name: &str| nodes.iter().find(|(_, n)| n.label() == Some(name)).and_then(|(_, n)| n.bounds()).map(|b| b.x1); + let inside = |x: f64| x <= f64::from(width) - 10.0; + for ((group, names), was) in groups.iter().zip(groups_seen.iter_mut()) { + let ends: Vec> = names.iter().map(|n| end(n)).collect(); + let shown = ends.iter().all(Option::is_some); + assert!(shown || ends.iter().all(Option::is_none), "{count} objects, {width}: {group} {ends:?}"); + if let Some(Some(last)) = ends.last() { + assert!(inside(*last), "{count} objects, {width}: {group} ends at {last}"); + let transform = end("Transform"); + assert!(transform.is_some_and(inside), "{count} objects, {width}: Transform after {group} ends at {transform:?}"); + } + assert!(!*was || shown, "{count} objects, {width}: {group} left out after a narrower bar showed it"); + *was |= shown; + } } assert!(seen, "{count} objects: a wide bar has room for the fields"); + assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 045ad97328..fccfbedab5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -34,7 +34,7 @@ //! Background Save or Background Export on. A `wait` other than true, false or null is refused use std::sync::Arc; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::mpsc::Sender; use serde_json::{Value, json}; @@ -101,8 +101,13 @@ pub struct ControlRequest { pub params: Value, pub reply: Sender, state: Arc, + /// Its place in the order requests were made ([`ControlRequest::next_seq`]). + seq: u64, } +/// The sequence number of the next request made. +static NEXT_SEQ: AtomicU64 = AtomicU64::new(0); + /// A request's state: waiting to run, taken by the app ([`ControlRequest::claim`]), or given up /// by its caller before that ([`Ticket::give_up`]). It leaves `QUEUED` once, one way or the other. const QUEUED: u8 = 0; @@ -124,7 +129,18 @@ impl Ticket { impl ControlRequest { pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { let (tx, rx) = std::sync::mpsc::channel(); - (Self { method: method.into(), params, reply: tx, state: Arc::new(AtomicU8::new(QUEUED)) }, rx) + let seq = NEXT_SEQ.fetch_add(1, Ordering::SeqCst); + (Self { method: method.into(), params, reply: tx, state: Arc::new(AtomicU8::new(QUEUED)), seq }, rx) + } + + /// The sequence number the next request made gets: every request made so far is before it. + pub fn next_seq() -> u64 { + NEXT_SEQ.load(Ordering::SeqCst) + } + + /// Whether this request was made before the one numbered `seq`. + pub fn made_before(&self, seq: u64) -> bool { + self.seq < seq } /// The caller's handle on this request, to give it up with. @@ -132,6 +148,11 @@ impl ControlRequest { Ticket(self.state.clone()) } + /// Whether its caller gave it up (it never runs), without taking it. + pub fn given_up(&self) -> bool { + self.state.load(Ordering::SeqCst) == GIVEN_UP + } + /// Take the request to run it → `false` when its caller gave it up meanwhile (don't run it). pub fn claim(&self) -> bool { self.state.compare_exchange(QUEUED, STARTED, Ordering::SeqCst, Ordering::SeqCst).is_ok() @@ -540,7 +561,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); - for e in events { + let held = + PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::, _>>()); + let held = match held { + Ok(held) => held, + Err(e) => return err(e), + }; + for (e, backquote) in events.iter().zip(held) { let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") { "down" => PointerKind::Down, "drag" => PointerKind::Drag, @@ -566,7 +593,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), _ => q, }); - let backquote = e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); crate::canvas::dispatch(app, &PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen }, view); let hold = PointerEvent::json_hold(e); if hold > 0.0 { diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d084d7ee04..e587c0489f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -293,6 +293,29 @@ fn synthetic_pointer_backquote_keeps_solid_object_in_place() { assert_eq!(xf.as_coeffs()[4], 20.0, "synthetic backquote drag changes pattern paint"); } +/// `ui.pointer` rejects a `backquote` that is not a boolean, given for the request or for any +/// event, before any of the events runs. +#[test] +fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true); + let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let down = json!({"kind": "down", "x": 125, "y": 125}); + let drag = json!({"kind": "drag", "x": 145, "y": 125}); + for params in [ + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125}], "backquote": "true"}), + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125, "backquote": 1}]}), + ] { + let r = input_request(&mut app, "ui.pointer", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`backquote` must be a boolean")), "{r}"); + assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{params}"); + } +} + /// `ui.pointer` replies with the key object: a click on one of two selected objects makes it /// the key, and a click on the key again lets it go. #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 2a90425c1f..c0f900f67c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, + SelectByLinkStatus: [crate::addons::select::link_status::KIND] => crate::addons::select::link_status::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 8d58f21b41..fdbf335cb6 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -249,6 +249,23 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The field of a Color Picker opened over a command dialog ([`over_effect`]): the dialog's colour +/// field its OK fills. +const COLOUR_FIELD: &str = "__colourField"; + +/// The Color Picker over the command dialog `parent`, on `colour`, that fills the dialog's `field` +/// with its OK and goes back to it, as Cancel does. It previews nothing itself: the dialog's own +/// preview shows the colour once it is back. +pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog { + let mut d = Dialog::new( + KIND, + json!({"original": color_json(&colour), "channel": Channel::default().id(), "webOnly": false, "swatches": false, COLOUR_FIELD: field}), + ); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + store(&mut d, &Picked::of(colour)); + d +} + /// The field of a Color Picker opened over Recolor Artwork ([`over_recolor`]): the row whose new /// color it picks. const RECOLOR_ROW: &str = "__recolorRow"; @@ -433,8 +450,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { /// Opened for an artboard, the picker shows the color on that artboard's paper, with or without a /// selection. fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { - // Over Recolor Artwork the art shows that dialog's preview, which this one must not replace. - if d.fields.contains_key(RECOLOR_ROW) { + // Over Recolor Artwork the art shows that dialog's preview, which this one must not replace; + // over a command dialog this picker only fills a field, and the dialog previews it. + if d.fields.contains_key(RECOLOR_ROW) || d.fields.contains_key(COLOUR_FIELD) { return; } let (cmd, params) = paint_command(app, d); @@ -632,6 +650,15 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color, side: f32) -> /// OK with the starting color unchanged and nothing previewed closes the picker and leaves the /// artboard as it was: without a background color, or with its color in its own color model. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + // The dialog previews the new colour when it comes back: end this picker's interaction, as + // Cancel does, so the dialog starts its preview afresh. + let _ = app.session.cancel_interaction(); + app.ui.dialog = Some(parent); + return Ok(Value::Null); + } if let Some(row) = d.fields.get(RECOLOR_ROW).and_then(Value::as_u64) { let parent = super::parent(d).ok_or("Recolor Artwork is no longer open")?; let c = in_document_model(app, picked(d).color); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 273c0291ef..d305be1ffc 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -985,4 +985,60 @@ mod tests { assert_eq!((¶ms["texture"], ¶ms["textureImage"]), (&json!("loaded"), &json!(stored))); let _ = std::fs::remove_dir_all(&dir); } + /// Effect > Stylize > Outer Glow: a swatch beside Color shows the effect's colour, typing a + /// hex recolours it, and a double-click opens the Color Picker over the dialog; its OK fills + /// Color, and the effect applies that colour. + #[test] + fn outer_glow_colour_swatch_opens_the_color_picker() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "stylize.outerGlow"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + for n in 0..6 { + frame(&mut app, f64::from(n) * 0.01, vec![]); + } + let rect = ctx.read_response(form::colour_swatch_id("color")).expect("the colour swatch is drawn").rect; + // The colour of the swatch drawn at `rect`. + let swatch = |out: &egui::FullOutput| { + out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.rect == rect => Some(r.fill), + _ => None, + }) + }; + let yellow = egui::Color32::from_rgb(255, 255, 0); + assert_eq!(swatch(&frame(&mut app, 0.2, vec![])), Some(yellow), "the swatch shows the effect's #ffff00"); + // Typing a colour recolours the swatch. + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert_eq!(swatch(&frame(&mut app, 0.25, vec![])), Some(egui::Color32::from_rgb(255, 0, 0)), "typing a hex recolours the swatch"); + // A double-click opens the Color Picker on the field's colour. + let pos = rect.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, 0.3, vec![egui::Event::PointerMoved(pos), button(true)]); + frame(&mut app, 0.35, vec![button(false)]); + frame(&mut app, 0.4, vec![button(true)]); + frame(&mut app, 0.45, vec![button(false)]); + frame(&mut app, 0.5, vec![]); + let d = app.ui.dialog.as_ref().expect("a dialog"); + assert_eq!(d.kind, "colorPicker", "a double-click opens the Color Picker over the effect dialog"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(Color::rgb(1.0, 0.0, 0.0)), "on the field's colour"); + // Its OK fills the effect's Color, and the effect applies it. + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("the effect dialog is back"); + assert_eq!((d.kind.as_str(), d.fields.get("color")), ("effect", Some(&json!("#00ff00"))), "OK fills Color and comes back"); + frame(&mut app, 0.6, vec![]); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + assert_eq!(fx.params.get("color"), Some(&json!("#00ff00")), "Outer Glow takes the picked colour"); + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 1ac4c78886..7238e191ed 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Unit; +use vectorcraft_doc::color::Color; use vectorcraft_plugins::{Manifest, Param, ParamSpec}; use crate::state::Dialog; @@ -168,6 +169,26 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> { } } +/// The id of the colour swatch beside the field `key` (a test clicks it; [`colour_swatch`] draws it). +pub(super) fn colour_swatch_id(key: &str) -> egui::Id { + egui::Id::unique(("fx-colour-swatch", key)) +} + +/// The colour swatch beside the colour field `key`, showing `colour`: a double-click asks for the +/// Color Picker over this dialog, whose OK fills the field ([`super::color_picker::over_effect`]). +/// Returns whether the picker was asked for. +fn colour_swatch(ui: &mut egui::Ui, key: &str, colour: Color) -> bool { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::hover()); + let resp = ui.interact(rect, colour_swatch_id(key), egui::Sense::click()); + let [r, g, b, _] = colour.to_rgba8(1.0); + ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b)); + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + resp.double_clicked() +} /// A text field `width` wide bound to `d.fields[key]`. Returns true when it changed. pub(super) fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> bool { text_edit(ui, d, key, width).changed() @@ -403,6 +424,7 @@ pub(super) fn param_fields( ) -> bool { let t = Tokens::get(ui.ctx()); let mut changed = false; + let mut pick: Option<(String, Color)> = None; egui::Grid::new("fxgrid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { let mut keys: Vec<(String, Value)> = d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect(); @@ -480,18 +502,42 @@ pub(super) fn param_fields( } } Value::String(mut s) => { - if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(140.0)).changed() { - d.fields.insert(k.clone(), json!(s)); - changed = true; + // A hex colour (#rrggbb or #rgb) shows its swatch beside the field; the swatch's + // double-click opens the Color Picker over this dialog. + let mut colour = None; + let mut ask = false; + ui.horizontal(|ui| { + if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + colour = crate::panels::color::parse_hex(&s); + if let Some(c) = colour { + ask = colour_swatch(ui, &k, c); + } + }); + if ask && let Some(c) = colour { + pick = Some((k.clone(), c)); } } // A color object shows as its hex; typing in the field stores the typed text. other => match color_object(&other) { Some(c) => { let mut s = c.to_hex(); - if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { - d.fields.insert(k.clone(), json!(s)); - changed = true; + let mut colour = None; + let mut ask = false; + ui.horizontal(|ui| { + if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + colour = crate::panels::color::parse_hex(&s); + if let Some(c) = colour { + ask = colour_swatch(ui, &k, c); + } + }); + if ask && let Some(c) = colour { + pick = Some((k.clone(), c)); } } None => { @@ -503,6 +549,9 @@ pub(super) fn param_fields( ui.end_row(); } }); + if let Some((key, colour)) = pick { + *d = super::color_picker::over_effect(d, &key, colour); + } changed } diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 81aeae9b5a..35d216bc77 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -290,7 +290,7 @@ fn the_new_path_is_selected_only_with_keep_selected_on() { super::super::confirm(&mut app).unwrap(); let (selected, id) = stroke(&mut app, tool, 100.0); assert_eq!(selected, vec![id], "{tool}"); - // Off: the next stroke leaves the selection as it was. + // Off: the next stroke leaves nothing selected, the earlier path included (#5752). app.run("tool.options", json!({"tool": tool})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("keepSelected".into(), json!(false)); super::super::confirm(&mut app).unwrap(); @@ -299,7 +299,7 @@ fn the_new_path_is_selected_only_with_keep_selected_on() { assert_eq!(app.session.tool_options_of(tool)["keepSelected"].as_bool(), Some(false), "{tool}"); let (selected, new) = stroke(&mut app, tool, 200.0); assert_ne!(new, id, "{tool} drew a new path"); - assert_eq!(selected, vec![id], "{tool}"); + assert!(selected.is_empty(), "{tool}: the earlier path is no longer selected either"); } } diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 6d9f91df33..f72383068e 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -1,8 +1,9 @@ //! The modal dialog window: a backdrop that keeps the rest of the app from taking clicks, and a //! window with no title bar that opens centred and moves by dragging its heading (the band from its -//! top edge down to the heading), as a title bar would. Where it was moved to stays, per window, for -//! the session, and the window never leaves the screen. Rows too many for the screen's height -//! scroll inside it ([`scrolled_rows`]), so its heading and buttons stay in view. +//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where +//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows +//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons +//! stay in view. use egui::{Id, Rect, Vec2}; @@ -60,10 +61,10 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { let band = Rect::from_x_y_ranges(outer.x_range(), outer.top()..=bottom.max(outer.top())); // Not focusable (`Sense::drag()` is): Tab goes through the dialog's controls, not the band. let r = ui.interact(band, handle(id), egui::Sense::DRAG); + // Hovered, it keeps the arrow, as a title bar does (the grab cursor is Windows' four-way move + // arrows: #5246); only while it is dragged does it show the window being carried. if r.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } else if r.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } } diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 5408b78c24..95ff410cae 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -118,6 +118,31 @@ fn dialogs_move_by_their_heading_stay_on_screen_and_where_they_were_moved() { } } +/// #5246: the band that moves a dialog keeps the arrow when hovered, as a title bar does (the grab +/// cursor is the four-way move arrows on Windows); it shows the window held only while dragged. +#[test] +fn the_band_that_moves_a_dialog_keeps_the_arrow_until_dragged() { + let opens: [(&str, Open, egui::Id); 2] = [ + ("Offset Path", |app| crate::menus::invoke(app, "object.path.offsetPath", json!({})), egui::Id::unique(("dialog", "offsetPath"))), + ("New Document", open_new_document, egui::Id::unique(("dialog", "newDocument"))), + ]; + for (name, open, id) in opens { + let (ctx, mut app) = (ctx(), app_with_selection()); + open(&mut app); + settle(&ctx, &mut app); + let at = rect_of(&ctx, id).left_top() + vec2(40.0, 6.0); + let cursor = |ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), events, ..Default::default() }; + ctx.run_ui(input, |ui| show(app, ui.ctx())).platform_output.cursor_icon + }; + cursor(&ctx, &mut app, vec![Event::PointerMoved(at)]); + assert_eq!(cursor(&ctx, &mut app, vec![]), egui::CursorIcon::Default, "{name}: hovering the band"); + cursor(&ctx, &mut app, vec![button(at, true)]); + assert_eq!(cursor(&ctx, &mut app, vec![Event::PointerMoved(at + vec2(20.0, 10.0))]), egui::CursorIcon::Grabbing, "{name}: dragging it"); + cursor(&ctx, &mut app, vec![button(at + vec2(20.0, 10.0), false)]); + } +} + /// Tab goes through a dialog's controls and does not stop on the band that moves the window. #[test] fn tab_skips_the_band_that_moves_a_dialog() { diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index c474cea581..b467f05552 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -530,6 +530,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let contour = vectorcraft_tools::addons::contour::ID; + let box3d = vectorcraft_tools::addons::box3d::ID; let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); assert_eq!( addon, @@ -543,7 +544,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "sharedEdge", "smartPen", enclosing, - contour + contour, + box3d ] ); for advanced in [false, true] { @@ -559,7 +561,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); - for tool in ["extendPath", "smartPen", enclosing, contour] { + assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); + for tool in ["extendPath", "smartPen", enclosing, contour, box3d] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 7324520e27..e73d787364 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -448,7 +448,7 @@ mod tests { assert_eq!(fonts(&mut app)[0]["family"], "Missing Family"); assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); app.run("object.unlockAll", json!({})).unwrap(); - assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); + assert_eq!(app.ui.status, "", "unlocking the skipped text clears the warning"); let r = change(&mut app, &d, &from, true).unwrap(); assert_eq!(r["runs"], 1, "{r}"); assert!(r.get("warning").is_none(), "{r}"); @@ -459,6 +459,258 @@ mod tests { assert_eq!(app.ui.status, "Saved another document"); } + #[test] + fn replacement_keeps_only_font_warnings_that_still_apply() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Other", "font": "Inter"})).unwrap(); + + let replace = |app: &mut VectorcraftApp, from: &str, from_style: Option<&str>, style: &str| { + app.run("text.replaceFont", json!({"from": {"family": from, "style": from_style}, "to": {"family": "Source Sans 3", "style": style}})) + .unwrap() + }; + let first = replace(&mut app, "Missing Family", Some("Regular"), "Black Wide"); + assert_eq!(first["runs"], 1, "{first}"); + assert_eq!(first["skipped"], 1, "{first}"); + let style_warning = first["warning"].as_str().unwrap().split_once("; ").unwrap().1.to_string(); + assert!(style_warning.contains("Source Sans 3 Black Wide is drawn in Source Sans 3"), "{style_warning}"); + + let unrelated = replace(&mut app, "Inter", None, "Regular"); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, first["warning"].as_str().unwrap()); + + app.run("object.unlockAll", json!({})).unwrap(); + let second = replace(&mut app, "Missing Family", None, "Regular"); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, style_warning); + + let third = replace(&mut app, "Source Sans 3", Some("Black Wide"), "Regular"); + assert_eq!(third["runs"], 1, "{third}"); + assert!(third.get("warning").is_none(), "{third}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_style_specific_retry_clears_a_family_wide_skipped_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Regular"}})) + .unwrap(); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1))); + app.run("object.unlockAll", json!({})).unwrap(); + let second = app + .run( + "text.replaceFont", + json!({"from": {"family": "Missing Family", "style": "Regular"}, "to": {"family": "Source Sans 3", "style": "Regular"}}), + ) + .unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn new_text_in_the_source_font_does_not_keep_an_old_skip_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let replace = |app: &mut VectorcraftApp, from: &str, style: &str| { + app.run("text.replaceFont", json!({"from": {"family": from}, "to": {"family": "Source Sans 3", "style": style}})).unwrap() + }; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Editable", "font": "Missing Family"})).unwrap(); + let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = replace(&mut app, "Missing Family", "Regular"); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1))); + app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "New", "font": "Missing Family"})).unwrap(); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)]; + let second = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(fonts(&mut app).iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn unlocking_skipped_text_clears_its_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Other", "font": "Inter"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1); + app.run("object.unlockAll", json!({})).unwrap(); + assert_eq!(app.ui.status, ""); + let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(unrelated["runs"], 1); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_document_revision_refreshes_the_skip_warning_on_tick() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1); + assert!(!app.ui.status.is_empty()); + + app.session.execute("object.unlockAll", &json!({})).unwrap(); + let ctx = egui::Context::default(); + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_selection_only_retry_ignores_unselected_text_in_the_same_font() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Outside", "font": "Missing Family"})).unwrap(); + let selected = app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Selected", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}); + let first = app.run("text.replaceFont", params.clone()).unwrap(); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(0), Some(1))); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let second = app.run("text.replaceFont", params).unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn a_changed_selection_keeps_the_original_warning_scope() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Outside", "font": "Missing Family"})).unwrap(); + let added = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Added", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)]; + let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}); + let first = app.run("text.replaceFont", params.clone()).unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped), vectorcraft_doc::NodeId(added)]; + let second = app.run("text.replaceFont", params).unwrap(); + assert_eq!(second["runs"], 2, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn changing_selection_does_not_clear_a_skipped_font_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let selected = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + let warning = app.ui.status.clone(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + let unrelated = + app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap(); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, warning); + app.run("object.unlockAll", json!({})).unwrap(); + let retry = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(retry["runs"], 1, "{retry}"); + assert!(retry.get("warning").is_none(), "{retry}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn replacing_a_font_in_another_document_keeps_the_original_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + let warning = app.ui.status.clone(); + let original_uid = app.session.active().unwrap().uid; + + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Other", "font": "Inter"})).unwrap(); + let second = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert_eq!(app.ui.status, warning); + app.session.set_active(0); + assert_eq!(app.session.active().unwrap().uid, original_uid); + assert_eq!(app.ui.status, warning); + } + + #[test] + fn a_comma_in_a_substituted_style_keeps_its_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}})) + .unwrap(); + let warning = first["warning"].as_str().unwrap().to_string(); + assert!(warning.contains("Black, Wide"), "{warning}"); + let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap(); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, warning); + } + + #[test] + fn an_unrelated_substituted_style_does_not_keep_a_resolved_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3", "style": "Narrow"}})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}})) + .unwrap(); + assert!(first["warning"].as_str().is_some_and(|warning| warning.contains("Black, Wide")), "{first}"); + let resolved = app + .run( + "text.replaceFont", + json!({"from": {"family": "Source Sans 3", "style": "Black, Wide"}, "to": {"family": "Inter", "style": "Regular"}}), + ) + .unwrap(); + assert!(resolved.get("warning").is_none(), "{resolved}"); + assert_eq!(app.ui.status, ""); + } + #[test] fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() { let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap(); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 5fbca5a2e9..39dd49bfc6 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -13,7 +13,7 @@ //! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the //! pointer leaves the field or the text selection changes; steps stop at its first and last family. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use egui::{Color32, Sense, Ui, vec2}; @@ -363,12 +363,17 @@ pub fn font_menu( // These turns preceded the opener. The popup cancels back to the newly // applied family, and any preview drawn this pass has not been applied. st.current.clone_from(&own); + st.highlight = st.rows.iter().position(|row| matches!(row, Row::Family(f) if f.eq_ignore_ascii_case(&own))); st.previewed = None; } out = Some(FontPick::Wheel(steps)); } } - if drawn || !field.contains_pointer() { + let queued = ui.data(|d| { + d.get_temp::(wheel_fields_id(ui.ctx().viewport_id())) + .is_some_and(|fields| fields.queued.iter().any(|event| event.field == field.id)) + }); + if drawn || (!field.contains_pointer() && !queued) { st.wheel_order = None; ui.data_mut(|d| d.remove::(field.id.with("wheel"))); } @@ -436,6 +441,26 @@ struct WheelField { layer: egui::LayerId, } +#[derive(Clone)] +struct QueuedWheel { + frame: u64, + field: egui::Id, + menu: egui::Id, + position: egui::Pos2, + rect: egui::Rect, + event: egui::Event, + amount: f32, + reset_after: bool, + positions_after: Vec, +} + +#[derive(Clone)] +struct ReplayWheel { + target: egui::LayerId, + position: egui::Pos2, + event: egui::Event, +} + #[derive(Clone, Default)] struct WheelFields { pass: u64, @@ -445,6 +470,8 @@ struct WheelFields { pointer: Option, fields: Vec, pending: HashMap>, + queued: Vec, + replay: Vec, } #[cfg(not(target_arch = "wasm32"))] @@ -461,6 +488,58 @@ impl egui::Plugin for WheelLayerSnapshot { "font wheel viewport layers" } + fn on_begin_pass(&mut self, ui: &mut Ui) { + let ctx = ui.ctx(); + let viewport = ctx.viewport_id(); + if viewport == egui::ViewportId::ROOT { + return; + } + let key = wheel_fields_id(viewport); + let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; + let frame = ctx.cumulative_frame_nr_for(viewport); + let mut ready = Vec::new(); + fields.queued.retain(|event| { + if event.frame < frame { + ready.push(event.clone()); + false + } else { + true + } + }); + let replayed = fields.replay.len(); + for event in ready { + let current = fields.fields.iter().find(|field| field.id == event.field); + let layer = current.map(|field| field.layer); + let opened_after_wheel = current.is_none() + && ctx.data(|d| d.get_temp::(event.menu)).is_some_and(|menu| menu.opened > 0 && menu.opened == fields.pass); + let active = opened_after_wheel + || current.is_some_and(|field| field.rect.contains(event.position) && ctx.layer_id_at(event.position) == Some(field.layer)); + let left = !active || event.reset_after || event.positions_after.iter().any(|position| ctx.layer_id_at(*position) != layer); + let id = event.field.with("wheel"); + if !active { + ctx.data_mut(|d| d.remove::(id)); + if let Some(target) = ctx.layer_id_at(event.position) { + fields.replay.push(ReplayWheel { target, position: event.position, event: event.event }); + } + } else { + let notches = ctx.data(|d| d.get_temp::(id)).unwrap_or(0.0) + event.amount; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(event.field).or_default().push(WheelInput::Notches(whole as i32)); + } + } + if left { + ctx.data_mut(|d| d.remove::(id)); + fields.pending.entry(event.field).or_default().push(WheelInput::Leave); + } + } + if fields.replay.len() > replayed { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(key, fields)); + } + fn on_end_pass(&mut self, ui: &mut Ui) { let ctx = ui.ctx(); let viewport = ctx.viewport_id(); @@ -502,6 +581,36 @@ fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } +fn mark_queued_wheel_leaves(fields: &mut WheelFields, point: Option) { + let mut marked = HashSet::new(); + for event in fields.queued.iter_mut().rev() { + if marked.insert(event.field) { + match point { + Some(position) if event.rect.contains(position) => event.positions_after.push(position), + _ => event.reset_after = true, + } + } + } +} + +#[cfg(test)] +pub(crate) fn wheel_field_layer_for_test(ctx: &egui::Context, viewport: egui::ViewportId, point: egui::Pos2) -> Option { + ctx.data(|data| data.get_temp::(wheel_fields_id(viewport))) + .and_then(|fields| fields.fields.iter().find(|field| field.rect.contains(point)).map(|field| field.layer)) +} + +#[cfg(test)] +pub(crate) fn offset_wheel_fields_for_test(ctx: &egui::Context, viewport: egui::ViewportId, offset: egui::Vec2) { + let key = wheel_fields_id(viewport); + ctx.data_mut(|data| { + let mut fields = data.get_temp::(key).expect("registered wheel fields"); + for field in &mut fields.fields { + field.rect = field.rect.translate(offset); + } + data.insert_temp(key, fields); + }); +} + #[derive(Clone, PartialEq)] struct WheelTarget { input: crate::state::InputGeneration, @@ -653,8 +762,12 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } match event { egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + mark_queued_wheel_leaves(&mut fields, Some(*p)); for field in &fields.fields { - if over(field, pointer) && !over(field, Some(*p)) { + if pointer.is_some_and(|point| field.rect.contains(point)) + && !field.rect.contains(*p) + && !fields.queued.iter().any(|event| event.field == field.id) + { ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); fields.pending.entry(field.id).or_default().push(WheelInput::Leave); } @@ -663,23 +776,42 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } egui::Event::PointerGone => { pointer = None; + mark_queued_wheel_leaves(&mut fields, None); for field in &fields.fields { - ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); - fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + if !fields.queued.iter().any(|event| event.field == field.id) { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } } } egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() && delta.y != 0.0 => { if let Some(field) = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied() { - let id = field.id.with("wheel"); - let mut notches: f32 = ctx.data(|d| d.get_temp(id)).unwrap_or(0.0); - notches -= match unit { + let amount = -match unit { egui::MouseWheelUnit::Point => delta.y / line, egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, }; - let whole = notches.trunc(); - ctx.data_mut(|d| d.insert_temp(id, notches - whole)); - if whole != 0.0 { - fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + if cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() != raw.viewport_id { + if let Some(position) = pointer { + fields.queued.push(QueuedWheel { + frame, + field: field.id, + menu: field.menu, + position, + rect: field.rect, + event: event.clone(), + amount, + reset_after: false, + positions_after: Vec::new(), + }); + } + } else { + let id = field.id.with("wheel"); + let notches = ctx.data(|d| d.get_temp::(id)).unwrap_or(0.0) + amount; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + } } captured = true; return false; @@ -689,6 +821,23 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } true }); + if !fields.replay.is_empty() { + let mut replay = Vec::new(); + for wheel in std::mem::take(&mut fields.replay) { + #[cfg(not(target_arch = "wasm32"))] + let target_still_visible = native_layers.as_ref().is_some_and(|layers| (layers.0)(wheel.position) == Some(wheel.target)); + #[cfg(target_arch = "wasm32")] + let target_still_visible = false; + if target_still_visible { + replay.push(egui::Event::PointerMoved(wheel.position)); + replay.push(wheel.event); + } + } + if !replay.is_empty() { + replay.push(pointer.map_or(egui::Event::PointerGone, egui::Event::PointerMoved)); + raw.events.splice(0..0, replay); + } + } fields.pointer = pointer; ctx.data_mut(|d| d.insert_temp(key, fields)); if captured { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 07c4f90d9f..e60b76cefa 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3207,7 +3207,9 @@ digits Malayalam Малаялам Patterns Мостри Stroke Options Опции на щриха Character: Знак: + Paragraph: Абзац: Character options Опции на знака + Paragraph options Опции за абзац Stroke options Опции на щриха Transform options Опции за трансформации Stroke Weight Дебелина на щриха @@ -4194,6 +4196,8 @@ axis Both И двете @msg no such saved selection няма такава запазена селекция @msg no such segment няма такъв сегмент @msg no such spine point няма такава точка от оста +@msg `with` must be a list of at most 10000 spine point indexes `with` трябва да е списък с най-много 10000 индекса на точки от оста +@msg `with` moves points, not a handle `with` мести точки, не дръжка @msg no such spine segment няма такъв сегмент от оста @msg no such subpath няма такъв подпът @msg no such user library няма такава потребителска библиотека @@ -4524,6 +4528,9 @@ axis Both И двете @msg an image VectorCraft can't read was left out изображение, което VectorCraft не може да разчете, беше пропуснато @msg an image whose data is cut short was left out изображение с непълни данни беше пропуснато @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel свързаните картини показват записания във файла предварителен преглед с ниска резолюция, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“ +@msg linked type areas past VectorCraft's limits were left out свързаните текстови области извън ограниченията на VectorCraft бяха пропуснати +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, използван като маска в свързани области, обтичащ текст или съставен път, не изрязва +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel свързаните картини без предварителен преглед във файла показват заместител, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“ @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текстовите рамки за област в редове, твърде къси за шрифта, в който се показват, получиха по-високи рамки ({_1}): текстът им иначе нямаше да се види @msg its editing data doesn't say where its art is данните му за редактиране не посочват къде се намира неговата графика @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) този файл е записан без съвместимост с PDF и данните му за редактиране не могат да бъдат прочетени ({why}) @@ -5949,6 +5956,9 @@ anchor Points: Точки: Find Nearest Swatch… Намиране на най-близкия образец… Find Nearest Swatch Намиране на най-близкия образец Apply Nearest Swatch Прилагане на най-близкия образец +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Прилагане на запълването към щриха + Apply Stroke to Fill Прилагане на щриха към запълването Select objects to find the swatches nearest their colors. Изберете обекти, за да намерите най-близките до цветовете им образци. @msg select objects or give `color` изберете обекти или задайте `color` @msg `color` is not a colour `color` не е цвят @@ -6215,6 +6225,29 @@ breakText Glyphs Глифи Minimum angle Минимален ъгъл Maximum angle Максимален ъгъл +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Избиране на свързаните + Select Embedded Избиране на вградените + Select Missing Избиране на липсващите + Select Modified Избиране на модифицираните + Select by Link Status Избиране по състояние на връзката + Select by Link Status… Избиране по състояние на връзката… + Search images Търсене на изображения + No images match. Няма съвпадащи изображения. +@msgplural Selected {n} linked image|Selected {n} linked images Избрано е {n} свързано изображение|Избрани са {n} свързани изображения +@msgplural Selected {n} embedded image|Selected {n} embedded images Избрано е {n} вградено изображение|Избрани са {n} вградени изображения +@msgplural Selected {n} missing image|Selected {n} missing images Избрано е {n} липсващо изображение|Избрани са {n} липсващи изображения +@msgplural Selected {n} modified image|Selected {n} modified images Избрано е {n} модифицирано изображение|Избрани са {n} модифицирани изображения +@msgplural Selected {n} image|Selected {n} images Избрано е {n} изображение|Избрани са {n} изображения +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; още {n} е скрито или заключено|{selected}; още {n} са скрити или заключени +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; още {n} е в шаблонен слой|{selected}; още {n} са в шаблонни слоеве +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; още {n} е извън изолираната група|{selected}; още {n} са извън изолираната група +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; още {n} не може да бъде избрано сега|{selected}; още {n} не могат да бъдат избрани сега + # Compound Shapes add-on Compound Shapes Съставни фигури Shape Mode Buttons Make Compound Shapes Бутоните за режими на фигури създават съставни фигури + +# 3D Box add-on + 3D Box 3D кутия + 3D Box Tool Инструмент за 3D кутия diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d007b68291..0d95e80181 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1469,7 +1469,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Standardno okomito latinično poravnanje Strikethrough Precrtano Character: Znak: + Paragraph: Pasus: Character options Opcije znakova + Paragraph options Opcije pasusa Subscript Indeks Subscript (on the roadmap) Indeks (u planu) Superscript Eksponent @@ -4589,6 +4591,8 @@ imageTrace Outline Obris @msg no such saved selection nema takvog sačuvanog odabira @msg no such segment nema takvog segmenta @msg no such spine point nema takve tačke kičme +@msg `with` must be a list of at most 10000 spine point indexes `with` mora biti lista od najviše 10000 indeksa tačaka kičme +@msg `with` moves points, not a handle `with` pomjera tačke, ne ručicu @msg no such spine segment nema takvog segmenta kičme @msg no such subpath nema takve podputanje @msg no such user library nema takve korisničke biblioteke @@ -4923,6 +4927,9 @@ imageTrace Outline Obris @msg an image VectorCraft can't read was left out izostavljena je slika koju VectorCraft ne može pročitati @msg an image whose data is cut short was left out izostavljena je slika čiji su podaci skraćeni @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel povezane slike prikazuju pregled niske rezolucije sačuvan u datoteci dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze +@msg linked type areas past VectorCraft's limits were left out povezana područja teksta izvan ograničenja programa VectorCraft su izostavljena +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst korišten kao maska u povezanim područjima, omotanom tekstu ili složenoj putanji ne odsijeca +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel povezane slike bez pregleda u datoteci prikazuju čuvar mjesta dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise tekst u području u okvirima prekratkim za red fonta u kojem se prikazuje dobio je više okvire ({_1}): inače se tekst ne bi prikazao @msg its editing data doesn't say where its art is njeni podaci za uređivanje ne govore gdje joj je crtež @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ova datoteka je sačuvana bez PDF kompatibilnosti, a njeni podaci za uređivanje se ne mogu pročitati ({why}) @@ -6075,6 +6082,9 @@ shape Open Otvoren Find Nearest Swatch… Pronađi najbliži uzorak boje… Find Nearest Swatch Pronađi najbliži uzorak boje Apply Nearest Swatch Primijeni najbliži uzorak boje +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Primijeni ispunu na potez + Apply Stroke to Fill Primijeni potez na ispunu Select objects to find the swatches nearest their colors. Odaberite objekte da pronađete uzorke boja najbliže njihovim bojama. @msg select objects or give `color` odaberite objekte ili navedite `color` @msg `color` is not a colour `color` nije boja @@ -6250,6 +6260,29 @@ shape Open Otvoren Minimum angle Najmanji ugao Maximum angle Najveći ugao +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Odaberi povezane + Select Embedded Odaberi ugrađene + Select Missing Odaberi nedostajuće + Select Modified Odaberi izmijenjene + Select by Link Status Odabir po statusu veze + Select by Link Status… Odabir po statusu veze… + Search images Pretraži slike + No images match. Nijedna slika ne odgovara. +@msgplural Selected {n} linked image|Selected {n} linked images Odabrana je {n} povezana slika|Odabrane su {n} povezane slike|Odabrano je {n} povezanih slika +@msgplural Selected {n} embedded image|Selected {n} embedded images Odabrana je {n} ugrađena slika|Odabrane su {n} ugrađene slike|Odabrano je {n} ugrađenih slika +@msgplural Selected {n} missing image|Selected {n} missing images Odabrana je {n} nedostajuća slika|Odabrane su {n} nedostajuće slike|Odabrano je {n} nedostajućih slika +@msgplural Selected {n} modified image|Selected {n} modified images Odabrana je {n} izmijenjena slika|Odabrane su {n} izmijenjene slike|Odabrano je {n} izmijenjenih slika +@msgplural Selected {n} image|Selected {n} images Odabrana je {n} slika|Odabrane su {n} slike|Odabrano je {n} slika +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; još {n} je skrivena ili zaključana|{selected}; još {n} su skrivene ili zaključane|{selected}; još {n} je skriveno ili zaključano +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; još {n} je na sloju predloška|{selected}; još {n} su na slojevima predloška|{selected}; još {n} je na slojevima predloška +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; još {n} je izvan izolirane grupe|{selected}; još {n} su izvan izolirane grupe|{selected}; još {n} je izvan izolirane grupe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; još {n} se sada ne može odabrati|{selected}; još {n} se sada ne mogu odabrati|{selected}; još {n} se sada ne može odabrati + # Compound Shapes add-on Compound Shapes Složeni oblici Shape Mode Buttons Make Compound Shapes Tasteri načina oblika prave složene oblike + +# 3D Box add-on + 3D Box 3D kutija + 3D Box Tool Alat za 3D kutiju diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 34988b565f..a3cb5b42aa 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -615,12 +615,14 @@ Character Alignment Alineació de caràcters Character Direction Direcció de caràcters Character options Opcions de caràcter + Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter Character Styles Estils de caràcter Character: Caràcter: + Paragraph: Paràgraf: Charcoal Carbó Charcoal… Carbó… Check an artboard to save. Marca un tauler per desar. @@ -5181,6 +5183,9 @@ digits Malayalam Malaiàlam @msg library panel `{given}` isn't missing its library al panell de biblioteca `{given}` no li falta la biblioteca @msg library panel `{given}` isn't open el panell de biblioteca `{given}` no està obert @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les imatges enllaçades mostren la previsualització de baixa resolució desada al fitxer fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços +@msg linked type areas past VectorCraft's limits were left out s’han omès les àrees de text enllaçades que superen els límits de VectorCraft +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el text usat com a màscara en àrees enllaçades, en text ajustat o en un traçat compost no retalla +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les imatges enllaçades sense previsualització al fitxer mostren un marcador de posició fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços @msg Live Paint Merge: select a Live Paint group and the paths to add Fusió de pintura interactiva: seleccioneu un grup de pintura interactiva i els traçats que voleu afegir @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first La pintura interactiva accepta traçats i traçats compostos: convertiu abans el text, les imatges i altres objectes a traçats @msg Live Paint: select paths or compound paths Pintura interactiva: seleccioneu traçats o traçats compostos @@ -5323,6 +5328,8 @@ digits Malayalam Malaiàlam @msg no such saved selection no existeix aquesta selecció desada @msg no such segment no existeix aquest segment @msg no such spine point no existeix aquest punt de l’espina +@msg `with` must be a list of at most 10000 spine point indexes `with` ha de ser una llista d’un màxim de 10000 índexs de punts de l’espina +@msg `with` moves points, not a handle `with` mou punts, no una nansa @msg no such spine segment no existeix aquest segment de l’espina @msg no such subpath no existeix aquest subtraçat @msg no such user library no existeix aquesta biblioteca d’usuari @@ -6084,6 +6091,9 @@ anchor Points: Punts: Find Nearest Swatch… Cerca la mostra més propera… Find Nearest Swatch Cerca la mostra més propera Apply Nearest Swatch Aplica la mostra més propera +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplica el farciment al traç + Apply Stroke to Fill Aplica el traç al farciment Select objects to find the swatches nearest their colors. Seleccioneu objectes per trobar les mostres més properes als seus colors. @msg select objects or give `color` seleccioneu objectes o indiqueu `color` @msg `color` is not a colour `color` no és un color @@ -6351,6 +6361,29 @@ breakText Glyphs Glifs Minimum angle Angle mínim Maximum angle Angle màxim +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecciona les enllaçades + Select Embedded Selecciona les incrustades + Select Missing Selecciona les que falten + Select Modified Selecciona les modificades + Select by Link Status Selecciona per estat de l’enllaç + Select by Link Status… Selecciona per estat de l’enllaç… + Search images Cerca imatges + No images match. Cap imatge no coincideix. +@msgplural Selected {n} linked image|Selected {n} linked images S’ha seleccionat {n} imatge enllaçada|S’han seleccionat {n} imatges enllaçades +@msgplural Selected {n} embedded image|Selected {n} embedded images S’ha seleccionat {n} imatge incrustada|S’han seleccionat {n} imatges incrustades +@msgplural Selected {n} missing image|Selected {n} missing images S’ha seleccionat {n} imatge que falta|S’han seleccionat {n} imatges que falten +@msgplural Selected {n} modified image|Selected {n} modified images S’ha seleccionat {n} imatge modificada|S’han seleccionat {n} imatges modificades +@msgplural Selected {n} image|Selected {n} images S’ha seleccionat {n} imatge|S’han seleccionat {n} imatges +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} més està oculta o bloquejada|{selected}; {n} més estan ocultes o bloquejades +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} més és en una capa de plantilla|{selected}; {n} més són en capes de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} més és fora del grup aïllat|{selected}; {n} més són fora del grup aïllat +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} més no es pot seleccionar ara|{selected}; {n} més no es poden seleccionar ara + # Compound Shapes add-on Compound Shapes Formes compostes Shape Mode Buttons Make Compound Shapes Els botons de mode de forma creen formes compostes + +# 3D Box add-on + 3D Box Caixa 3D + 3D Box Tool Eina Caixa 3D diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 57c3092b0d..063ddd591d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1493,7 +1493,9 @@ digits Malayalam Malajálamské Standard Vertical Roman Alignment Standardní svislé zarovnání latinky Strikethrough Přeškrtnutí Character: Znak: + Paragraph: Odstavec: Character options Možnosti znaků + Paragraph options Možnosti odstavce Subscript Dolní index Subscript (on the roadmap) Dolní index (v plánu) Superscript Horní index @@ -4637,6 +4639,8 @@ imageTrace Outline Obrys @msg no such saved selection takový uložený výběr neexistuje @msg no such segment takový segment neexistuje @msg no such spine point takový bod páteře neexistuje +@msg `with` must be a list of at most 10000 spine point indexes `with` musí být seznam nejvýše 10000 indexů bodů páteře +@msg `with` moves points, not a handle `with` posouvá body, ne táhlo @msg no such spine segment takový segment páteře neexistuje @msg no such subpath taková dílčí cesta neexistuje @msg no such user library taková uživatelská knihovna neexistuje @@ -4981,6 +4985,9 @@ imageTrace Outline Obrys @msg graphs come in as plain art, without their data or settings grafy se načtou jako obyčejná grafika, bez svých dat a nastavení @msg an image whose data is cut short was left out obrázek s useknutými daty byl vynechán @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel propojené obrázky se zobrazují jako náhled v nízkém rozlišení uložený v souboru, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení +@msg linked type areas past VectorCraft's limits were left out propojené textové oblasti nad limity aplikace VectorCraft byly vynechány +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text použitý jako maska v propojených oblastech, obtékaném textu nebo složené cestě neořezává +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel propojené obrázky bez náhledu v souboru se zobrazují jako zástupný symbol, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise text v oblasti v rámcích příliš nízkých pro řádek písma, ve kterém se zde zobrazuje, dostal vyšší rámce ({_1}): jinak by nebyl vidět @msg its editing data doesn't say where its art is z jeho dat pro úpravy není zřejmé, kde je kresba @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) tento soubor byl uložen bez kompatibility s PDF a jeho data pro úpravy nelze přečíst ({why}) @@ -6100,6 +6107,9 @@ anchor Points: Body: Find Nearest Swatch… Najít nejbližší položku vzorníku… Find Nearest Swatch Najít nejbližší položku vzorníku Apply Nearest Swatch Použít nejbližší položku vzorníku +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Použít výplň na tah + Apply Stroke to Fill Použít tah na výplň Select objects to find the swatches nearest their colors. Vyberte objekty, k jejichž barvám chcete najít nejbližší položky vzorníku. @msg select objects or give `color` vyberte objekty nebo zadejte `color` @msg `color` is not a colour `color` není barva @@ -6365,6 +6375,29 @@ breakText Glyphs Glyfy Minimum angle Minimální úhel Maximum angle Maximální úhel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Vybrat propojené + Select Embedded Vybrat vložené + Select Missing Vybrat chybějící + Select Modified Vybrat upravené + Select by Link Status Vybrat podle stavu propojení + Select by Link Status… Vybrat podle stavu propojení… + Search images Hledat obrazy + No images match. Žádný obraz neodpovídá. +@msgplural Selected {n} linked image|Selected {n} linked images Vybrán {n} propojený obraz|Vybrány {n} propojené obrazy|Vybráno {n} propojených obrazů +@msgplural Selected {n} embedded image|Selected {n} embedded images Vybrán {n} vložený obraz|Vybrány {n} vložené obrazy|Vybráno {n} vložených obrazů +@msgplural Selected {n} missing image|Selected {n} missing images Vybrán {n} chybějící obraz|Vybrány {n} chybějící obrazy|Vybráno {n} chybějících obrazů +@msgplural Selected {n} modified image|Selected {n} modified images Vybrán {n} upravený obraz|Vybrány {n} upravené obrazy|Vybráno {n} upravených obrazů +@msgplural Selected {n} image|Selected {n} images Vybrán {n} obraz|Vybrány {n} obrazy|Vybráno {n} obrazů +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; další {n} je skrytý nebo zamčený|{selected}; další {n} jsou skryté nebo zamčené|{selected}; dalších {n} je skrytých nebo zamčených +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; další {n} je na vrstvě šablony|{selected}; další {n} jsou na vrstvách šablony|{selected}; dalších {n} je na vrstvách šablony +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; další {n} je mimo izolovanou skupinu|{selected}; další {n} jsou mimo izolovanou skupinu|{selected}; dalších {n} je mimo izolovanou skupinu +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; další {n} teď nelze vybrat|{selected}; další {n} teď nelze vybrat|{selected}; dalších {n} teď nelze vybrat + # Compound Shapes add-on Compound Shapes Složené tvary Shape Mode Buttons Make Compound Shapes Tlačítka režimů tvarů vytvářejí složené tvary + +# 3D Box add-on + 3D Box 3D kvádr + 3D Box Tool Nástroj 3D kvádr diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b5980d5727..9db09ea0f8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1403,7 +1403,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Standard lodret romersk justering Strikethrough Gennemstreget Character: Tegn: + Paragraph: Afsnit: Character options Tegnindstillinger + Paragraph options Afsnitsindstillinger Subscript Sænket skrift Subscript (on the roadmap) Sænket skrift (på vejkortet) Superscript Hævet skrift @@ -4611,6 +4613,9 @@ imageTrace Outline Kontur @msg an image VectorCraft can't read was left out et billede, som VectorCraft ikke kan læse, blev udeladt @msg an image whose data is cut short was left out et billede, hvis data er afkortet, blev udeladt @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkede billeder viser den gemte forhåndsvisning i lav opløsning, indtil deres filer findes: link dem igen i Links-panelet +@msg linked type areas past VectorCraft's limits were left out sammenkædede tekstområder ud over VectorCrafts grænser blev udeladt +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst brugt som maske i sammenkædede områder, ombrudt tekst eller en sammensat kurve beskærer ikke +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkede billeder uden forhåndsvisning i filen viser en pladsholder, indtil deres filer findes: link dem igen i Links-panelet @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise rammetekst i rammer, der er for lave til en tekstlinje i den skrifttype, den viser i, fik højere rammer ({_1}): teksten ville ellers ikke blive vist @msg its editing data doesn't say where its art is dens redigeringsdata siger ikke, hvor dens grafik er @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) denne fil blev gemt uden PDF-kompatibilitet, og dens redigeringsdata kan ikke læses ({why}) @@ -5966,6 +5971,9 @@ anchor Points: Punkter: Find Nearest Swatch… Find nærmeste farveprøve… Find Nearest Swatch Find nærmeste farveprøve Apply Nearest Swatch Anvend nærmeste farveprøve +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Anvend udfyldning på kontur + Apply Stroke to Fill Anvend kontur på udfyldning Select objects to find the swatches nearest their colors. Markér objekter for at finde de farveprøver, der ligger tættest på deres farver. @msg select objects or give `color` markér objekter, eller angiv `color` @msg `color` is not a colour `color` er ikke en farve @@ -6231,6 +6239,29 @@ breakText Glyphs Glyffer Minimum angle Mindste vinkel Maximum angle Største vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markér linkede + Select Embedded Markér integrerede + Select Missing Markér manglende + Select Modified Markér ændrede + Select by Link Status Markér efter linkstatus + Select by Link Status… Markér efter linkstatus… + Search images Søg i billeder + No images match. Ingen billeder passer. +@msgplural Selected {n} linked image|Selected {n} linked images Markerede {n} linket billede|Markerede {n} linkede billeder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerede {n} integreret billede|Markerede {n} integrerede billeder +@msgplural Selected {n} missing image|Selected {n} missing images Markerede {n} manglende billede|Markerede {n} manglende billeder +@msgplural Selected {n} modified image|Selected {n} modified images Markerede {n} ændret billede|Markerede {n} ændrede billeder +@msgplural Selected {n} image|Selected {n} images Markerede {n} billede|Markerede {n} billeder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} mere er skjult eller låst|{selected}; {n} mere er skjult eller låst +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} mere er på et skabelonlag|{selected}; {n} mere er på skabelonlag +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} mere er uden for den isolerede gruppe|{selected}; {n} mere er uden for den isolerede gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} mere kan ikke markeres nu|{selected}; {n} mere kan ikke markeres nu + # Compound Shapes add-on Compound Shapes Sammensatte figurer Shape Mode Buttons Make Compound Shapes Knapper til formtilstande opretter sammensatte figurer + +# 3D Box add-on + 3D Box 3D-boks + 3D Box Tool 3D-boksværktøj diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5e38f90f52..d28aa09df7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3252,7 +3252,9 @@ effect Points Punkte Patterns Muster Stroke Options Konturoptionen Character: Zeichen: + Paragraph: Absatz: Character options Zeichenoptionen + Paragraph options Absatzoptionen Stroke options Konturoptionen Transform options Transformationsoptionen Stroke Weight Konturstärke @@ -4246,6 +4248,8 @@ theme Appearance Erscheinungsbild @msg no such saved selection keine solche gespeicherte Auswahl @msg no such segment kein solches Segment @msg no such spine point kein solcher Achsenpunkt +@msg `with` must be a list of at most 10000 spine point indexes `with` muss eine Liste von höchstens 10000 Achsenpunkt-Indizes sein +@msg `with` moves points, not a handle `with` verschiebt Punkte, keinen Griff @msg no such spine segment kein solches Achsensegment @msg no such subpath kein solcher Teilpfad @msg no such user library keine solche Benutzerbibliothek @@ -4591,6 +4595,9 @@ theme Appearance Erscheinungsbild @msg graphs come in as plain art, without their data or settings Diagramme werden als einfache Grafik übernommen, ohne ihre Daten und Einstellungen @msg an image whose data is cut short was left out ein Bild mit abgeschnittenen Daten wurde ausgelassen @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel verknüpfte Bilder zeigen die in der Datei gespeicherte Vorschau in niedriger Auflösung, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu +@msg linked type areas past VectorCraft's limits were left out verkettete Textbereiche jenseits der Grenzen von VectorCraft wurden ausgelassen +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip als Maske verwendeter Text in verketteten Bereichen, umfließendem Text oder einem zusammengesetzten Pfad beschneidet nicht +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel verknüpfte Bilder ohne Vorschau in der Datei zeigen einen Platzhalter, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise Flächentext in Rahmen, die für eine Zeile der Schrift, in der er hier erscheint, zu niedrig sind, hat höhere Rahmen bekommen ({_1}): Sonst wäre der Text nicht zu sehen @msg its editing data doesn't say where its art is seine Bearbeitungsdaten geben nicht an, wo seine Grafik liegt @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) diese Datei wurde ohne PDF-Kompatibilität gespeichert, und ihre Bearbeitungsdaten können nicht gelesen werden ({why}) @@ -5685,6 +5692,9 @@ anchor Points: Punkte: Find Nearest Swatch… Ähnlichstes Farbfeld suchen… Find Nearest Swatch Ähnlichstes Farbfeld suchen Apply Nearest Swatch Ähnlichstes Farbfeld anwenden +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Fläche auf Kontur anwenden + Apply Stroke to Fill Kontur auf Fläche anwenden Select objects to find the swatches nearest their colors. Wählen Sie Objekte aus, um die Farbfelder zu finden, die ihren Farben am nächsten kommen. @msg select objects or give `color` wählen Sie Objekte aus oder geben Sie `color` an @msg `color` is not a colour `color` ist keine Farbe @@ -5951,6 +5961,29 @@ breakText Glyphs Glyphen Minimum angle Minimaler Winkel Maximum angle Maximaler Winkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Verknüpfte auswählen + Select Embedded Eingebettete auswählen + Select Missing Fehlende auswählen + Select Modified Geänderte auswählen + Select by Link Status Nach Verknüpfungsstatus auswählen + Select by Link Status… Nach Verknüpfungsstatus auswählen… + Search images Bilder suchen + No images match. Kein Bild passt. +@msgplural Selected {n} linked image|Selected {n} linked images {n} verknüpftes Bild ausgewählt|{n} verknüpfte Bilder ausgewählt +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} eingebettetes Bild ausgewählt|{n} eingebettete Bilder ausgewählt +@msgplural Selected {n} missing image|Selected {n} missing images {n} fehlendes Bild ausgewählt|{n} fehlende Bilder ausgewählt +@msgplural Selected {n} modified image|Selected {n} modified images {n} geändertes Bild ausgewählt|{n} geänderte Bilder ausgewählt +@msgplural Selected {n} image|Selected {n} images {n} Bild ausgewählt|{n} Bilder ausgewählt +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} weiteres ist ausgeblendet oder gesperrt|{selected}; {n} weitere sind ausgeblendet oder gesperrt +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} weiteres liegt auf einer Vorlagenebene|{selected}; {n} weitere liegen auf Vorlagenebenen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} weiteres liegt außerhalb der isolierten Gruppe|{selected}; {n} weitere liegen außerhalb der isolierten Gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} weiteres kann gerade nicht ausgewählt werden|{selected}; {n} weitere können gerade nicht ausgewählt werden + # Compound Shapes add-on Compound Shapes Zusammengesetzte Formen Shape Mode Buttons Make Compound Shapes Formmodus-Schaltflächen erstellen zusammengesetzte Formen + +# 3D Box add-on + 3D Box 3D-Quader + 3D Box Tool 3D-Quader-Werkzeug diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 84232bda24..16f80c7309 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1991,6 +1991,7 @@ font-technology Variable Μεταβλητές Patterns Μοτίβα Stroke Options Επιλογές περιγράμματος Character: Χαρακτήρας: + Paragraph: Παράγραφος: Stroke: Περίγραμμα: Style Στυλ Style: Στυλ: @@ -3655,6 +3656,7 @@ digits Malayalam Μαλαγιάλαμ Stray Points Μεμονωμένα σημεία Stroke (X), double-click for the Color Picker Περίγραμμα (X), διπλό κλικ για επιλογέα χρώματος Character options Επιλογές χαρακτήρων + Paragraph options Επιλογές παραγράφου Stroke options Επιλογές περιγράμματος Transform options Επιλογές μετασχηματισμού Stroke Weight Πάχος περιγράμματος @@ -4285,6 +4287,8 @@ digits Malayalam Μαλαγιάλαμ @msg no such saved selection δεν υπάρχει τέτοια αποθηκευμένη επιλογή @msg no such segment δεν υπάρχει τέτοιο τμήμα @msg no such spine point δεν υπάρχει τέτοιο σημείο κεντρικής καμπύλης +@msg `with` must be a list of at most 10000 spine point indexes το `with` πρέπει να είναι λίστα με έως 10000 δείκτες σημείων κεντρικής καμπύλης +@msg `with` moves points, not a handle το `with` μετακινεί σημεία, όχι λαβή @msg no such spine segment δεν υπάρχει τέτοιο τμήμα κεντρικής καμπύλης @msg no such subpath δεν υπάρχει τέτοια υποδιαδρομή @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @@ -4624,6 +4628,9 @@ digits Malayalam Μαλαγιάλαμ @msg graphs come in as plain art, without their data or settings τα γραφήματα εισάγονται ως απλή γραφική, χωρίς τα δεδομένα και τις ρυθμίσεις τους @msg an image whose data is cut short was left out παραλείφθηκε εικόνα με περικομμένα δεδομένα @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες εμφανίζουν την προεπισκόπηση χαμηλής ανάλυσης που έχει αποθηκευτεί, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι +@msg linked type areas past VectorCraft's limits were left out οι συνδεδεμένες περιοχές κειμένου πέρα από τα όρια του VectorCraft παραλείφθηκαν +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip το κείμενο που χρησιμοποιείται ως μάσκα σε συνδεδεμένες περιοχές, σε κείμενο με αναδίπλωση ή σε σύνθετη διαδρομή δεν αποκόπτει +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες χωρίς προεπισκόπηση στο αρχείο εμφανίζουν ένα σύμβολο κράτησης θέσης, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise οι περιοχές κειμένου με πλαίσια πολύ μικρά για μία γραμμή της γραμματοσειράς τους απέκτησαν μεγαλύτερο ύψος ({_1}), διαφορετικά το κείμενο δεν θα εμφανιζόταν @msg its editing data doesn't say where its art is τα δεδομένα επεξεργασίας του δεν προσδιορίζουν τη θέση του σχεδίου @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) το αρχείο αποθηκεύτηκε χωρίς συμβατότητα PDF και τα δεδομένα επεξεργασίας του δεν μπορούν να διαβαστούν ({why}) @@ -6051,6 +6058,9 @@ anchor Points: Σημεία: Find Nearest Swatch… Εύρεση πλησιέστερου δείγματος χρώματος… Find Nearest Swatch Εύρεση πλησιέστερου δείγματος χρώματος Apply Nearest Swatch Εφαρμογή πλησιέστερου δείγματος χρώματος +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Εφαρμογή γεμίσματος στο περίγραμμα + Apply Stroke to Fill Εφαρμογή περιγράμματος στο γέμισμα Select objects to find the swatches nearest their colors. Επιλέξτε αντικείμενα για να βρείτε τα δείγματα χρωμάτων που πλησιάζουν περισσότερο τα χρώματά τους. @msg select objects or give `color` επιλέξτε αντικείμενα ή δώστε `color` @msg `color` is not a colour το `color` δεν είναι χρώμα @@ -6317,6 +6327,29 @@ breakText Glyphs Γλύφοι Minimum angle Ελάχιστη γωνία Maximum angle Μέγιστη γωνία +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Επιλογή συνδεδεμένων + Select Embedded Επιλογή ενσωματωμένων + Select Missing Επιλογή όσων λείπουν + Select Modified Επιλογή τροποποιημένων + Select by Link Status Επιλογή κατά κατάσταση σύνδεσης + Select by Link Status… Επιλογή κατά κατάσταση σύνδεσης… + Search images Αναζήτηση εικόνων + No images match. Καμία εικόνα δεν ταιριάζει. +@msgplural Selected {n} linked image|Selected {n} linked images Επιλέχθηκε {n} συνδεδεμένη εικόνα|Επιλέχθηκαν {n} συνδεδεμένες εικόνες +@msgplural Selected {n} embedded image|Selected {n} embedded images Επιλέχθηκε {n} ενσωματωμένη εικόνα|Επιλέχθηκαν {n} ενσωματωμένες εικόνες +@msgplural Selected {n} missing image|Selected {n} missing images Επιλέχθηκε {n} εικόνα που λείπει|Επιλέχθηκαν {n} εικόνες που λείπουν +@msgplural Selected {n} modified image|Selected {n} modified images Επιλέχθηκε {n} τροποποιημένη εικόνα|Επιλέχθηκαν {n} τροποποιημένες εικόνες +@msgplural Selected {n} image|Selected {n} images Επιλέχθηκε {n} εικόνα|Επιλέχθηκαν {n} εικόνες +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}· {n} ακόμη είναι κρυφή ή κλειδωμένη|{selected}· {n} ακόμη είναι κρυφές ή κλειδωμένες +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}· {n} ακόμη είναι σε επίπεδο προτύπου|{selected}· {n} ακόμη είναι σε επίπεδα προτύπου +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας|{selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}· {n} ακόμη δεν μπορεί να επιλεγεί τώρα|{selected}· {n} ακόμη δεν μπορούν να επιλεγούν τώρα + # Compound Shapes add-on Compound Shapes Σύνθετα σχήματα Shape Mode Buttons Make Compound Shapes Τα κουμπιά λειτουργιών σχημάτων δημιουργούν σύνθετα σχήματα + +# 3D Box add-on + 3D Box Κουτί 3D + 3D Box Tool Εργαλείο κουτιού 3D diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c09b51167c..fafd0122e9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3291,7 +3291,9 @@ digits Malayalam Malayálam Patterns Motivos Stroke Options Opciones de trazo Character: Carácter: + Paragraph: Párrafo: Character options Opciones de carácter + Paragraph options Opciones de párrafo Stroke options Opciones de trazo Transform options Opciones de transformación Stroke Weight Grosor de trazo @@ -4330,6 +4332,8 @@ axis Both Ambos @msg no such saved selection no existe esa selección guardada @msg no such segment no existe ese segmento @msg no such spine point no existe ese punto del eje +@msg `with` must be a list of at most 10000 spine point indexes `with` debe ser una lista de como máximo 10000 índices de puntos del eje +@msg `with` moves points, not a handle `with` mueve puntos, no un manejador @msg no such spine segment no existe ese segmento del eje @msg no such subpath no existe ese subtrazado @msg no such user library no existe esa biblioteca de usuario @@ -4675,6 +4679,9 @@ axis Both Ambos @msg graphs come in as plain art, without their data or settings los gráficos se importan como ilustración normal, sin sus datos ni sus ajustes @msg an image whose data is cut short was left out se omitió una imagen con datos incompletos @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel las imágenes vinculadas muestran la vista previa de baja resolución guardada en el archivo hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos +@msg linked type areas past VectorCraft's limits were left out se omitieron las áreas de texto enlazadas que superan los límites de VectorCraft +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el texto usado como máscara en áreas enlazadas, texto ceñido o un trazado compuesto no recorta +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel las imágenes vinculadas sin vista previa en el archivo muestran un marcador de posición hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise el texto de área en marcos demasiado bajos para una línea de la fuente en que se muestra recibió marcos más altos ({_1}): de otro modo no se vería @msg its editing data doesn't say where its art is sus datos de edición no dicen dónde está su ilustración @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) este archivo se guardó sin compatibilidad con PDF y sus datos de edición no se pueden leer ({why}) @@ -6042,6 +6049,9 @@ anchor Points: Puntos: Find Nearest Swatch… Buscar muestra más cercana… Find Nearest Swatch Buscar muestra más cercana Apply Nearest Swatch Aplicar muestra más cercana +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplicar relleno al trazo + Apply Stroke to Fill Aplicar trazo al relleno Select objects to find the swatches nearest their colors. Seleccione objetos para buscar las muestras más cercanas a sus colores. @msg select objects or give `color` seleccione objetos o indique `color` @msg `color` is not a colour `color` no es un color @@ -6307,6 +6317,29 @@ breakText Glyphs Glifos Minimum angle Ángulo mínimo Maximum angle Ángulo máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleccionar vinculadas + Select Embedded Seleccionar incrustadas + Select Missing Seleccionar ausentes + Select Modified Seleccionar modificadas + Select by Link Status Seleccionar por estado de vínculo + Select by Link Status… Seleccionar por estado de vínculo… + Search images Buscar imágenes + No images match. Ninguna imagen coincide. +@msgplural Selected {n} linked image|Selected {n} linked images Se seleccionó {n} imagen vinculada|Se seleccionaron {n} imágenes vinculadas +@msgplural Selected {n} embedded image|Selected {n} embedded images Se seleccionó {n} imagen incrustada|Se seleccionaron {n} imágenes incrustadas +@msgplural Selected {n} missing image|Selected {n} missing images Se seleccionó {n} imagen ausente|Se seleccionaron {n} imágenes ausentes +@msgplural Selected {n} modified image|Selected {n} modified images Se seleccionó {n} imagen modificada|Se seleccionaron {n} imágenes modificadas +@msgplural Selected {n} image|Selected {n} images Se seleccionó {n} imagen|Se seleccionaron {n} imágenes +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} más está oculta o bloqueada|{selected}; {n} más están ocultas o bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} más está en una capa de plantilla|{selected}; {n} más están en capas de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} más está fuera del grupo aislado|{selected}; {n} más están fuera del grupo aislado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} más no se puede seleccionar ahora|{selected}; {n} más no se pueden seleccionar ahora + # Compound Shapes add-on Compound Shapes Formas compuestas Shape Mode Buttons Make Compound Shapes Los botones de modo de forma crean formas compuestas + +# 3D Box add-on + 3D Box Caja 3D + 3D Box Tool Herramienta Caja 3D diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 909240b3d2..9c0d61be2b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1466,7 +1466,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Tavallinen pystysuuntainen latinalainen tasaus Strikethrough Yliviivaus Character: Merkki: + Paragraph: Kappale: Character options Merkkiasetukset + Paragraph options Kappaleasetukset Subscript Alaindeksi Subscript (on the roadmap) Alaindeksi (suunnitteilla) Superscript Yläindeksi @@ -4545,6 +4547,8 @@ imageTrace Outline Ääriviiva @msg no such saved selection tallennettua valintaa ei ole @msg no such segment segmenttiä ei ole @msg no such spine point selkärangan pistettä ei ole +@msg `with` must be a list of at most 10000 spine point indexes `with`-arvon on oltava luettelo, jossa on enintään 10000 selkärangan pisteen indeksiä +@msg `with` moves points, not a handle `with` siirtää pisteitä, ei kahvaa @msg no such spine segment selkärangan segmenttiä ei ole @msg no such subpath alipolkua ei ole @msg no such user library käyttäjäkirjastoa ei ole @@ -4883,6 +4887,9 @@ imageTrace Outline Ääriviiva @msg graphs come in as plain art, without their data or settings kaaviot tuodaan tavallisena grafiikkana ilman niiden tietoja ja asetuksia @msg an image whose data is cut short was left out kuva, jonka data on katkennut, jätettiin pois @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkitetyt kuvat näyttävät tiedostoon tallennetun matalan tarkkuuden esikatselun, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa +@msg linked type areas past VectorCraft's limits were left out VectorCraftin rajat ylittävät linkitetyt tekstialueet jätettiin pois +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip maskina käytetty teksti linkitetyissä alueissa, rivitetyssä tekstissä tai yhdistelmäpolussa ei rajaa +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkitetyt kuvat, joilla ei ole esikatselua tiedostossa, näkyvät paikkamerkkinä, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise aluetekstin kehykset, jotka olivat liian matalia yhdelle riville niiden fontilla, korotettiin ({_1}): muuten niiden teksti ei näkyisi @msg its editing data doesn't say where its art is sen muokkaustiedoista ei selviä kuvituksen sijainti @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) tämä tiedosto tallennettiin ilman PDF-yhteensopivuutta, eikä sen muokkaustietoja voi lukea ({why}) @@ -6130,6 +6137,9 @@ anchor Points: Pisteet: Find Nearest Swatch… Etsi lähin värimalli… Find Nearest Swatch Etsi lähin värimalli Apply Nearest Swatch Käytä lähintä värimallia +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Käytä täyttöä viivaan + Apply Stroke to Fill Käytä viivaa täyttöön Select objects to find the swatches nearest their colors. Valitse objektit, joiden väreille haluat etsiä lähimmät värimallit. @msg select objects or give `color` valitse objekteja tai anna `color` @msg `color` is not a colour `color` ei ole väri @@ -6400,6 +6410,29 @@ breakText Glyphs Merkit Minimum angle Pienin kulma Maximum angle Suurin kulma +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Valitse linkitetyt + Select Embedded Valitse upotetut + Select Missing Valitse puuttuvat + Select Modified Valitse muokatut + Select by Link Status Valitse linkin tilan mukaan + Select by Link Status… Valitse linkin tilan mukaan… + Search images Hae kuvia + No images match. Mikään kuva ei vastaa hakua. +@msgplural Selected {n} linked image|Selected {n} linked images Valittiin {n} linkitetty kuva|Valittiin {n} linkitettyä kuvaa +@msgplural Selected {n} embedded image|Selected {n} embedded images Valittiin {n} upotettu kuva|Valittiin {n} upotettua kuvaa +@msgplural Selected {n} missing image|Selected {n} missing images Valittiin {n} puuttuva kuva|Valittiin {n} puuttuvaa kuvaa +@msgplural Selected {n} modified image|Selected {n} modified images Valittiin {n} muokattu kuva|Valittiin {n} muokattua kuvaa +@msgplural Selected {n} image|Selected {n} images Valittiin {n} kuva|Valittiin {n} kuvaa +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} muu on piilotettu tai lukittu|{selected}; {n} muuta on piilotettu tai lukittu +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} muu on mallitasolla|{selected}; {n} muuta on mallitasoilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} muu on eristetyn ryhmän ulkopuolella|{selected}; {n} muuta on eristetyn ryhmän ulkopuolella +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} muuta ei voi valita nyt|{selected}; {n} muuta ei voi valita nyt + # Compound Shapes add-on Compound Shapes Yhdistelmämuodot Shape Mode Buttons Make Compound Shapes Muototilapainikkeet luovat yhdistelmämuotoja + +# 3D Box add-on + 3D Box 3D-laatikko + 3D Box Tool 3D-laatikkotyökalu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6738ec8df3..2da80b01cf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3283,7 +3283,9 @@ digits Malayalam Malayalam Patterns Motifs Stroke Options Options de contour Character: Caractère : + Paragraph: Paragraphe : Character options Options de caractère + Paragraph options Options de paragraphe Stroke options Options de contour Transform options Options de transformation Stroke Weight Épaisseur du contour @@ -4320,6 +4322,8 @@ axis Both Les deux @msg no such saved selection sélection enregistrée inexistante @msg no such segment segment inexistant @msg no such spine point point de la dorsale inexistant +@msg `with` must be a list of at most 10000 spine point indexes `with` doit être une liste d’au plus 10000 indices de points de la dorsale +@msg `with` moves points, not a handle `with` déplace des points, pas une poignée @msg no such spine segment segment de la dorsale inexistant @msg no such subpath sous-tracé inexistant @msg no such user library bibliothèque utilisateur inexistante @@ -4663,6 +4667,9 @@ axis Both Les deux @msg graphs come in as plain art, without their data or settings les graphes sont importés comme illustration ordinaire, sans leurs données ni leurs réglages @msg an image whose data is cut short was left out une image aux données tronquées a été ignorée @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les images liées affichent l’aperçu basse résolution enregistré dans le fichier tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens +@msg linked type areas past VectorCraft's limits were left out les zones de texte liées au-delà des limites de VectorCraft ont été omises +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip le texte utilisé comme masque dans des zones liées, un habillage de texte ou un tracé transparent ne découpe pas +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les images liées sans aperçu dans le fichier affichent un espace réservé tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise le texte captif dans des cadres trop bas pour une ligne de la police dans laquelle il s’affiche a reçu des cadres plus hauts ({_1}) : il ne s’afficherait pas autrement @msg its editing data doesn't say where its art is ses données d’édition ne disent pas où se trouve son illustration @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ce fichier a été enregistré sans compatibilité PDF et ses données d’édition sont illisibles ({why}) @@ -6095,6 +6102,9 @@ anchor Points: Points : Find Nearest Swatch… Rechercher la nuance la plus proche… Find Nearest Swatch Rechercher la nuance la plus proche Apply Nearest Swatch Appliquer la nuance la plus proche +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Appliquer le fond au contour + Apply Stroke to Fill Appliquer le contour au fond Select objects to find the swatches nearest their colors. Sélectionnez des objets pour trouver les nuances les plus proches de leurs couleurs. @msg select objects or give `color` sélectionnez des objets ou indiquez `color` @msg `color` is not a colour `color` n’est pas une couleur @@ -6360,6 +6370,29 @@ breakText Glyphs Glyphes Minimum angle Angle minimal Maximum angle Angle maximal +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Sélectionner les images liées + Select Embedded Sélectionner les images incorporées + Select Missing Sélectionner les images manquantes + Select Modified Sélectionner les images modifiées + Select by Link Status Sélectionner par état de lien + Select by Link Status… Sélectionner par état de lien… + Search images Rechercher des images + No images match. Aucune image ne correspond. +@msgplural Selected {n} linked image|Selected {n} linked images {n} image liée sélectionnée|{n} images liées sélectionnées +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} image incorporée sélectionnée|{n} images incorporées sélectionnées +@msgplural Selected {n} missing image|Selected {n} missing images {n} image manquante sélectionnée|{n} images manquantes sélectionnées +@msgplural Selected {n} modified image|Selected {n} modified images {n} image modifiée sélectionnée|{n} images modifiées sélectionnées +@msgplural Selected {n} image|Selected {n} images {n} image sélectionnée|{n} images sélectionnées +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected} ; {n} autre est masquée ou verrouillée|{selected} ; {n} autres sont masquées ou verrouillées +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected} ; {n} autre est sur un calque modèle|{selected} ; {n} autres sont sur des calques modèles +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected} ; {n} autre est hors du groupe isolé|{selected} ; {n} autres sont hors du groupe isolé +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected} ; {n} autre ne peut pas être sélectionnée pour l’instant|{selected} ; {n} autres ne peuvent pas être sélectionnées pour l’instant + # Compound Shapes add-on Compound Shapes Formes composées Shape Mode Buttons Make Compound Shapes Les boutons de mode de forme créent des formes composées + +# 3D Box add-on + 3D Box Boîte 3D + 3D Box Tool Outil Boîte 3D diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 491c89fae0..9e313975e1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -554,12 +554,14 @@ font-technology Variable Változó Character / Paragraph Karakter / bekezdés Character Alignment Karakterigazítás Character options Karakterbeállítások + Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai Character Styles Karakterstílusok Character: Karakter: + Paragraph: Bekezdés: Check Links Csatolások ellenőrzése # Check Script (File › Scripts) and the report it shows on a script written for the reference app. Check Script Szkript ellenőrzése @@ -4689,6 +4691,9 @@ imageTrace Outline Körvonal @msg graphs come in as plain art, without their data or settings a diagramok egyszerű grafikaként kerülnek be, adataik és beállításaik nélkül @msg an image whose data is cut short was left out kimaradt egy csonka adatú kép @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel a csatolt képek a fájlban mentett kis felbontású előnézetet mutatják, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen +@msg linked type areas past VectorCraft's limits were left out a VectorCraft korlátain túli csatolt szövegterületek kimaradtak +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip a csatolt területeken, körbefuttatott szövegben vagy összetett útvonalban maszkként használt szöveg nem vág ki +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel a fájlban előnézet nélküli csatolt képek helyőrzőt mutatnak, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise a túl alacsony keretben lévő területszöveg, amelybe a megjelenítő betűtípus egy sora sem fér el, magasabb keretet kapott ({_1}): különben nem látszana @msg an object can't be read egy objektum nem olvasható @msg an object in perspective would leave the edited grid egy perspektivikus objektum kikerülne a szerkesztett rácsból @@ -5004,6 +5009,8 @@ imageTrace Outline Körvonal @msg no such saved selection nincs ilyen mentett kijelölés @msg no such segment nincs ilyen szakasz @msg no such spine point nincs ilyen gerincpont +@msg `with` must be a list of at most 10000 spine point indexes `with`: legfeljebb 10000 gerincpont-indexből álló lista kell +@msg `with` moves points, not a handle `with` pontokat mozgat, nem fogantyút @msg no such spine segment nincs ilyen gerincszakasz @msg no such subpath nincs ilyen részútvonal @msg no such user library nincs ilyen felhasználói könyvtár @@ -6084,6 +6091,9 @@ anchor Points: Pontok: Find Nearest Swatch… Legközelebbi színminta keresése… Find Nearest Swatch Legközelebbi színminta keresése Apply Nearest Swatch Legközelebbi színminta alkalmazása +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Kitöltés alkalmazása a körvonalra + Apply Stroke to Fill Körvonal alkalmazása a kitöltésre Select objects to find the swatches nearest their colors. Jelöljön ki objektumokat a színeikhez legközelebbi színminták megkereséséhez. @msg select objects or give `color` jelöljön ki objektumokat, vagy adja meg ezt: `color` @msg `color` is not a colour a(z) `color` nem szín @@ -6349,6 +6359,29 @@ breakText Glyphs Glifák Minimum angle Legkisebb szög Maximum angle Legnagyobb szög +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Csatoltak kijelölése + Select Embedded Beágyazottak kijelölése + Select Missing Hiányzók kijelölése + Select Modified Módosítottak kijelölése + Select by Link Status Kijelölés csatolási állapot szerint + Select by Link Status… Kijelölés csatolási állapot szerint… + Search images Képek keresése + No images match. Nincs egyező kép. +@msgplural Selected {n} linked image|Selected {n} linked images Kijelölt csatolt képek: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images Kijelölt beágyazott képek: {n} +@msgplural Selected {n} missing image|Selected {n} missing images Kijelölt hiányzó képek: {n} +@msgplural Selected {n} modified image|Selected {n} modified images Kijelölt módosított képek: {n} +@msgplural Selected {n} image|Selected {n} images Kijelölt képek: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; további rejtett vagy zárolt: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; további sablonrétegen: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; további az elkülönített csoporton kívül: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; további most nem jelölhető ki: {n} + # Compound Shapes add-on Compound Shapes Összetett alakzatok Shape Mode Buttons Make Compound Shapes Az alakzatmód-gombok összetett alakzatokat hoznak létre + +# 3D Box add-on + 3D Box 3D doboz + 3D Box Tool 3D doboz eszköz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ffb0cbf56f..0a6c910fcb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1403,7 +1403,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Perataan Romawi vertikal standar Strikethrough Coret Character: Karakter: + Paragraph: Paragraf: Character options Opsi karakter + Paragraph options Opsi paragraf Subscript Subskrip Subscript (on the roadmap) Subskrip (masih dalam roadmap) Superscript Superskrip @@ -4611,6 +4613,9 @@ imageTrace Outline Kontur @msg an image VectorCraft can't read was left out gambar yang tidak dapat dibaca VectorCraft tidak disertakan @msg an image whose data is cut short was left out gambar yang datanya terpotong tidak disertakan @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gambar tertaut menampilkan pratinjau resolusi rendah yang tersimpan dalam berkas sampai berkasnya ditemukan: tautkan ulang di panel Tautan +@msg linked type areas past VectorCraft's limits were left out area teks tertaut di luar batas VectorCraft dihilangkan +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip teks yang digunakan sebagai masker di area tertaut, teks terbungkus, atau jalur majemuk tidak memotong +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gambar tertaut tanpa pratinjau dalam berkas menampilkan penanda tempat sampai berkasnya ditemukan: tautkan ulang di panel Tautan @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise teks area dalam bingkai yang terlalu pendek untuk satu baris font yang ditampilkannya mendapat bingkai yang lebih tinggi ({_1}): tanpa itu teksnya tidak akan tampil @msg its editing data doesn't say where its art is data pengeditannya tidak menyatakan di mana karya seninya berada @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) berkas ini disimpan tanpa kompatibilitas PDF, dan data pengeditannya tidak dapat dibaca ({why}) @@ -5966,6 +5971,9 @@ anchor Points: Titik: Find Nearest Swatch… Cari Swatch Terdekat… Find Nearest Swatch Cari Swatch Terdekat Apply Nearest Swatch Terapkan Swatch Terdekat +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Terapkan isian ke guratan + Apply Stroke to Fill Terapkan guratan ke isian Select objects to find the swatches nearest their colors. Pilih objek untuk menemukan swatch yang paling dekat dengan warnanya. @msg select objects or give `color` pilih objek atau berikan `color` @msg `color` is not a colour `color` bukan warna @@ -6231,6 +6239,29 @@ breakText Glyphs Glif Minimum angle Sudut minimum Maximum angle Sudut maksimum +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Pilih yang Tertaut + Select Embedded Pilih yang Tersemat + Select Missing Pilih yang Hilang + Select Modified Pilih yang Diubah + Select by Link Status Pilih menurut Status Tautan + Select by Link Status… Pilih menurut Status Tautan… + Search images Cari gambar + No images match. Tidak ada gambar yang cocok. +@msgplural Selected {n} linked image|Selected {n} linked images Telah memilih {n} gambar tertaut +@msgplural Selected {n} embedded image|Selected {n} embedded images Telah memilih {n} gambar tersemat +@msgplural Selected {n} missing image|Selected {n} missing images Telah memilih {n} gambar yang hilang +@msgplural Selected {n} modified image|Selected {n} modified images Telah memilih {n} gambar yang diubah +@msgplural Selected {n} image|Selected {n} images Telah memilih {n} gambar +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} lainnya tersembunyi atau terkunci +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} lainnya berada di layer templat +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} lainnya berada di luar grup yang diisolasi +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} lainnya tidak dapat dipilih sekarang + # Compound Shapes add-on Compound Shapes Bentuk majemuk Shape Mode Buttons Make Compound Shapes Tombol mode bentuk membuat bentuk majemuk + +# 3D Box add-on + 3D Box Kotak 3D + 3D Box Tool Alat Kotak 3D diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cfd99e62b3..3459374cad 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3327,7 +3327,9 @@ digits Malayalam Malayalam Patterns Motivi Stroke Options Opzioni traccia Character: Carattere: + Paragraph: Paragrafo: Character options Opzioni carattere + Paragraph options Opzioni di paragrafo Stroke options Opzioni traccia Transform options Opzioni di trasformazione Stroke Weight Spessore traccia @@ -4372,6 +4374,8 @@ axis Both Entrambi @msg no such saved selection selezione salvata inesistente @msg no such segment segmento inesistente @msg no such spine point punto della dorsale inesistente +@msg `with` must be a list of at most 10000 spine point indexes `with` deve essere un elenco di al massimo 10000 indici di punti della dorsale +@msg `with` moves points, not a handle `with` sposta punti, non una maniglia @msg no such spine segment segmento della dorsale inesistente @msg no such subpath sottotracciato inesistente @msg no such user library libreria utente inesistente @@ -4717,6 +4721,9 @@ axis Both Entrambi @msg graphs come in as plain art, without their data or settings i grafici vengono importati come grafica semplice, senza i loro dati e le loro impostazioni @msg an image whose data is cut short was left out un'immagine con dati incompleti è stata omessa @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel le immagini collegate mostrano l'anteprima a bassa risoluzione salvata nel file finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti +@msg linked type areas past VectorCraft's limits were left out le aree di testo concatenate oltre i limiti di VectorCraft sono state omesse +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip il testo usato come maschera in aree concatenate, testo attorno o un tracciato composto non ritaglia +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel le immagini collegate senza anteprima nel file mostrano un segnaposto finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise il testo in area in cornici troppo basse per una riga del font in cui viene mostrato ha ricevuto cornici più alte ({_1}): altrimenti non sarebbe visibile @msg its editing data doesn't say where its art is i suoi dati di modifica non dicono dove si trova la grafica @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) questo file è stato salvato senza compatibilità PDF e i suoi dati di modifica non si possono leggere ({why}) @@ -5719,6 +5726,9 @@ anchor Points: Punti: Find Nearest Swatch… Trova campione più vicino… Find Nearest Swatch Trova campione più vicino Apply Nearest Swatch Applica campione più vicino +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Applica riempimento alla traccia + Apply Stroke to Fill Applica traccia al riempimento Select objects to find the swatches nearest their colors. Seleziona gli oggetti per trovare i campioni più vicini ai loro colori. @msg select objects or give `color` seleziona gli oggetti o indica `color` @msg `color` is not a colour `color` non è un colore @@ -5985,6 +5995,29 @@ breakText Glyphs Glifi Minimum angle Angolo minimo Maximum angle Angolo massimo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleziona collegate + Select Embedded Seleziona incorporate + Select Missing Seleziona mancanti + Select Modified Seleziona modificate + Select by Link Status Seleziona per stato del collegamento + Select by Link Status… Seleziona per stato del collegamento… + Search images Cerca immagini + No images match. Nessuna immagine corrisponde. +@msgplural Selected {n} linked image|Selected {n} linked images Selezionata {n} immagine collegata|Selezionate {n} immagini collegate +@msgplural Selected {n} embedded image|Selected {n} embedded images Selezionata {n} immagine incorporata|Selezionate {n} immagini incorporate +@msgplural Selected {n} missing image|Selected {n} missing images Selezionata {n} immagine mancante|Selezionate {n} immagini mancanti +@msgplural Selected {n} modified image|Selected {n} modified images Selezionata {n} immagine modificata|Selezionate {n} immagini modificate +@msgplural Selected {n} image|Selected {n} images Selezionata {n} immagine|Selezionate {n} immagini +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; altra {n} è nascosta o bloccata|{selected}; altre {n} sono nascoste o bloccate +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; altra {n} è su un livello modello|{selected}; altre {n} sono su livelli modello +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; altra {n} è fuori dal gruppo isolato|{selected}; altre {n} sono fuori dal gruppo isolato +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; altra {n} non può essere selezionata ora|{selected}; altre {n} non possono essere selezionate ora + # Compound Shapes add-on Compound Shapes Forme composte Shape Mode Buttons Make Compound Shapes I pulsanti dei metodi forma creano forme composte + +# 3D Box add-on + 3D Box Scatola 3D + 3D Box Tool Strumento Scatola 3D diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5da2097f26..715f1fc461 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3090,7 +3090,9 @@ mark-style Japanese 日本式 Strikethrough 打ち消し線 Stroke Options 線オプション Character: 文字: + Paragraph: 段落: Character options 文字オプション + Paragraph options 段落オプション Stroke options 線オプション Transform options 変形オプション Stroke: 線: @@ -4151,6 +4153,8 @@ swatch Bright Violet ビビッドバイオレット @msg no such anchor 指定されたアンカーポイントが見つかりません @msg no such segment 指定されたセグメントが見つかりません @msg no such spine point 指定されたスパインポイントが見つかりません +@msg `with` must be a list of at most 10000 spine point indexes `with` には最大 10000 個のスパインポイントのインデックスのリストを指定してください +@msg `with` moves points, not a handle `with` はポイントを移動します。ハンドルには使えません @msg no such spine segment 指定されたスパインセグメントが見つかりません @msg no such subpath 指定されたサブパスが見つかりません @msg object {id} is not a path オブジェクト {id} はパスではありません @@ -4404,6 +4408,9 @@ swatch Bright Violet ビビッドバイオレット @msg graphs come in as plain art, without their data or settings グラフは通常のアートとして読み込まれ、データと設定は保持されません @msg an image whose data is cut short was left out データが途中で切れている画像は除外されました @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel リンク画像は、元のファイルが見つかるまで、ファイルに保存された低解像度のプレビューで表示されます:リンクパネルで再リンクしてください +@msg linked type areas past VectorCraft's limits were left out VectorCraft の上限を超えるリンクされたテキストエリアは省略されました +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip リンクされたエリア、テキストの回り込み、複合パス内でマスクとして使われた文字はクリップしません +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ファイルにプレビューのないリンク画像は、元のファイルが見つかるまでプレースホルダーで表示されます:リンクパネルで再リンクしてください @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 表示に使われるフォントの 1 行に対して低すぎるフレーム内のエリア内文字は、フレームを高くしました ({_1}): そうしないと文字が表示されません @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it グラデーション「{name}」はファイル内で定義されていません: 代わりに単色を使用しています @msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft がまだ読み込めないブラシ {_1} 個はブラシパネルに追加されませんでした @@ -5784,6 +5791,9 @@ anchor Points: ポイント: Find Nearest Swatch… 最も近いスウォッチを検索… Find Nearest Swatch 最も近いスウォッチを検索 Apply Nearest Swatch 最も近いスウォッチを適用 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 塗りを線に適用 + Apply Stroke to Fill 線を塗りに適用 Select objects to find the swatches nearest their colors. カラーに最も近いスウォッチを探すオブジェクトを選択してください。 @msg select objects or give `color` オブジェクトを選択するか `color` を指定してください @msg `color` is not a colour `color` はカラーではありません @@ -6050,6 +6060,29 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked リンク済みを選択 + Select Embedded 埋め込みを選択 + Select Missing 見つからない画像を選択 + Select Modified 変更された画像を選択 + Select by Link Status リンクの状態で選択 + Select by Link Status… リンクの状態で選択… + Search images 画像を検索 + No images match. 一致する画像はありません。 +@msgplural Selected {n} linked image|Selected {n} linked images リンク済みの画像を {n} 個選択しました +@msgplural Selected {n} embedded image|Selected {n} embedded images 埋め込み画像を {n} 個選択しました +@msgplural Selected {n} missing image|Selected {n} missing images 見つからない画像を {n} 個選択しました +@msgplural Selected {n} modified image|Selected {n} modified images 変更された画像を {n} 個選択しました +@msgplural Selected {n} image|Selected {n} images 画像を {n} 個選択しました +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}。ほかに {n} 個が非表示またはロックされています +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}。ほかに {n} 個がテンプレートレイヤー上にあります +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}。ほかに {n} 個が分離したグループの外にあります +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}。ほかに {n} 個は今は選択できません + # Compound Shapes add-on Compound Shapes 複合シェイプ Shape Mode Buttons Make Compound Shapes シェイプモードボタンで複合シェイプを作成 + +# 3D Box add-on + 3D Box 3Dボックス + 3D Box Tool 3Dボックスツール diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b9f4a70a09..2c80751738 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -191,6 +191,7 @@ Shape ფიგურა Convert to Shape ფიგურად გარდაქმნა Expand Shape ფიგურის გაშლა + Expand Object ობიექტის გაშლა Pattern პატერნი Edit Pattern პატერნის რედაქტირება Tile Edge Color… ფილის კიდის ფერი… @@ -1328,7 +1329,9 @@ digits Malayalam მალაიალამური Standard Vertical Roman Alignment სტანდარტული ვერტიკალური ლათინური სწორება Strikethrough გადახაზული Character: სიმბოლო: + Paragraph: აბზაცი: Character options სიმბოლოს პარამეტრები + Paragraph options აბზაცის პარამეტრები Subscript ქვედა ინდექსი Subscript (on the roadmap) ქვედა ინდექსი (სამომავლო გეგმაშია) Superscript ზედა ინდექსი @@ -4779,6 +4782,9 @@ font-technology Variable ცვლადი Even თანაბრად Stacked დასტად @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები ფაილში შენახულ დაბალი გარჩევადობის მინიატურას აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში +@msg linked type areas past VectorCraft's limits were left out VectorCraft-ის ლიმიტების მიღმა დაკავშირებული ტექსტის არეები გამოტოვებულია +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip დაკავშირებულ არეებში, გარსშემოვლებულ ტექსტში ან შედგენილ ტრაექტორიაში ნიღბად გამოყენებული ტექსტი არ ჭრის +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები, რომელთა მინიატურაც ფაილში არ არის, ადგილის შემნახველს აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise არის ტექსტს ჩარჩოებში, რომლებიც მისი შრიფტის ერთი სტრიქონისთვის ზედმეტად დაბალი იყო, ჩარჩოები გაეზარდა ({_1}): სხვაგვარად ტექსტი არ გამოჩნდებოდა @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same მათზე არსებული ნახატი გვერდისგან {_1}%-ით განსხვავდება: მიუხედავად ამისა, ისინი რედაქტირების მონაცემებიდან აიღება @msg every numbered name for {name} is taken in the document's folder დოკუმენტის საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @@ -5523,6 +5529,8 @@ imageTrace Outline კონტური @msg missing number `{key}` აკლია რიცხვი `{key}` @msg missing integer `{key}` აკლია მთელი რიცხვი `{key}` @msg no such spine point ხერხემლის ასეთი წერტილი არ არსებობს +@msg `with` must be a list of at most 10000 spine point indexes `with` უნდა იყოს ხერხემლის წერტილების არაუმეტეს 10000 ინდექსის სია +@msg `with` moves points, not a handle `with` წერტილებს გადაადგილებს და არა სახელურს @msg no such spine segment ხერხემლის ასეთი სეგმენტი არ არსებობს @msg not a blend ეს გადასვლა არ არის @msg only http, https and mailto URLs open in the browser, not “{url}” ბრაუზერში მხოლოდ http, https და mailto URL-ები იხსნება და არა „{url}“ @@ -6096,6 +6104,9 @@ anchor Points: წერტილები: Find Nearest Swatch… უახლოესი ფერის ნიმუშის პოვნა… Find Nearest Swatch უახლოესი ფერის ნიმუშის პოვნა Apply Nearest Swatch უახლოესი ფერის ნიმუშის გამოყენება +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke შევსების გამოყენება კონტურზე + Apply Stroke to Fill კონტურის გამოყენება შევსებაზე Select objects to find the swatches nearest their colors. აირჩიეთ ობიექტები მათ ფერებთან უახლოესი ფერის ნიმუშების საპოვნელად. @msg select objects or give `color` აირჩიეთ ობიექტები ან მიუთითეთ `color` @msg `color` is not a colour `color` ფერი არ არის @@ -6376,6 +6387,29 @@ font-script Japanese იაპონური Minimum angle მინიმალური კუთხე Maximum angle მაქსიმალური კუთხე +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked დაკავშირებულების არჩევა + Select Embedded ჩაშენებულების არჩევა + Select Missing დაკარგულების არჩევა + Select Modified შეცვლილების არჩევა + Select by Link Status კავშირის მდგომარეობით არჩევა + Select by Link Status… კავშირის მდგომარეობით არჩევა… + Search images გამოსახულებების ძებნა + No images match. შესაბამისი გამოსახულება არ არის. +@msgplural Selected {n} linked image|Selected {n} linked images არჩეულია დაკავშირებული გამოსახულებები: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images არჩეულია ჩაშენებული გამოსახულებები: {n} +@msgplural Selected {n} missing image|Selected {n} missing images არჩეულია დაკარგული გამოსახულებები: {n} +@msgplural Selected {n} modified image|Selected {n} modified images არჩეულია შეცვლილი გამოსახულებები: {n} +@msgplural Selected {n} image|Selected {n} images არჩეულია გამოსახულებები: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; დამალული ან ჩაკეტილია კიდევ: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; შაბლონის ფენაზეა კიდევ: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; იზოლირებული ჯგუფის გარეთაა კიდევ: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ახლა ვერ აირჩევა კიდევ: {n} + # Compound Shapes add-on Compound Shapes შედგენილი ფიგურები Shape Mode Buttons Make Compound Shapes ფიგურის რეჟიმის ღილაკები ქმნის შედგენილ ფიგურებს + +# 3D Box add-on + 3D Box 3D ყუთი + 3D Box Tool 3D ყუთის ხელსაწყო diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index ac5d1193a7..01c96a7383 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3079,7 +3079,9 @@ mark-style Japanese 일본식 Strikethrough 취소선 Stroke Options 선 옵션 Character: 문자: + Paragraph: 단락: Character options 문자 옵션 + Paragraph options 단락 옵션 Stroke options 선 옵션 Transform options 변형 옵션 Stroke: 선: @@ -4078,6 +4080,8 @@ theme Appearance 외관 @msg no such anchor 해당 앵커가 없습니다 @msg no such segment 해당 세그먼트가 없습니다 @msg no such spine point 해당 스파인 포인트가 없습니다 +@msg `with` must be a list of at most 10000 spine point indexes `with`는 스파인 포인트 인덱스 최대 10000개의 목록이어야 합니다 +@msg `with` moves points, not a handle `with`는 포인트를 이동하며 핸들에는 쓸 수 없습니다 @msg no such spine segment 해당 스파인 세그먼트가 없습니다 @msg no such subpath 해당 하위 패스가 없습니다 @msg object {id} is not a path 개체 {id}은(는) 패스가 아닙니다 @@ -4331,6 +4335,9 @@ theme Appearance 외관 @msg graphs come in as plain art, without their data or settings 그래프는 데이터와 설정 없이 일반 아트로 가져왔습니다 @msg an image whose data is cut short was left out 데이터가 잘린 이미지는 제외했습니다 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 연결된 그림은 해당 파일을 찾을 때까지 파일에 저장된 저해상도 미리 보기로 표시됩니다: 링크 패널에서 다시 연결하세요 +@msg linked type areas past VectorCraft's limits were left out VectorCraft 한도를 넘는 연결된 문자 영역은 제외되었습니다 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 연결된 영역, 문자 감싸기 또는 컴파운드 패스에서 마스크로 사용된 문자는 클리핑하지 않습니다 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 파일에 미리 보기가 없는 연결된 그림은 해당 파일을 찾을 때까지 자리 표시자로 표시됩니다: 링크 패널에서 다시 연결하세요 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 표시되는 글꼴의 한 줄보다 낮은 프레임의 영역 문자는 프레임을 더 높였습니다({_1}). 그렇지 않으면 문자가 표시되지 않습니다 @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it 그레이디언트 “{name}”이(가) 파일에 정의되어 있지 않아 단색으로 대체했습니다 @msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft에서 아직 읽을 수 없는 브러시는 브러시 패널에서 제외되었습니다({_1}) @@ -5680,6 +5687,9 @@ anchor Points: 포인트: Find Nearest Swatch… 가장 가까운 견본 찾기… Find Nearest Swatch 가장 가까운 견본 찾기 Apply Nearest Swatch 가장 가까운 견본 적용 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 칠을 선에 적용 + Apply Stroke to Fill 선을 칠에 적용 Select objects to find the swatches nearest their colors. 색상에 가장 가까운 견본을 찾을 개체를 선택하십시오. @msg select objects or give `color` 개체를 선택하거나 `color`를 지정하십시오 @msg `color` is not a colour `color`은(는) 색상이 아닙니다 @@ -5946,6 +5956,29 @@ breakText Glyphs 글리프 Minimum angle 최소 각도 Maximum angle 최대 각도 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 연결됨 선택 + Select Embedded 포함됨 선택 + Select Missing 없는 이미지 선택 + Select Modified 수정된 이미지 선택 + Select by Link Status 링크 상태로 선택 + Select by Link Status… 링크 상태로 선택… + Search images 이미지 검색 + No images match. 일치하는 이미지가 없습니다. +@msgplural Selected {n} linked image|Selected {n} linked images 연결된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} embedded image|Selected {n} embedded images 포함된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} missing image|Selected {n} missing images 없는 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} modified image|Selected {n} modified images 수정된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} image|Selected {n} images 이미지 {n}개를 선택했습니다 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}. {n}개는 숨겨졌거나 잠겨 있습니다 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}. {n}개는 템플릿 레이어에 있습니다 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}. {n}개는 격리된 그룹 밖에 있습니다 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}. {n}개는 지금 선택할 수 없습니다 + # Compound Shapes add-on Compound Shapes 컴파운드 모양 Shape Mode Buttons Make Compound Shapes 모양 모드 버튼으로 컴파운드 모양 만들기 + +# 3D Box add-on + 3D Box 3D 상자 + 3D Box Tool 3D 상자 도구 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62385d6c98..fe34d035de 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1417,7 +1417,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Standaard verticale Romeinse uitlijning Strikethrough Doorhalen Character: Teken: + Paragraph: Alinea: Character options Tekenopties + Paragraph options Alineaopties Subscript Subscript Subscript (on the roadmap) Subscript (op de roadmap) Superscript Superscript @@ -4623,6 +4625,9 @@ imageTrace Outline Contour @msg an image VectorCraft can't read was left out een afbeelding die VectorCraft niet kan lezen, is weggelaten @msg an image whose data is cut short was left out een afbeelding waarvan de gegevens zijn afgekapt, is weggelaten @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gekoppelde afbeeldingen tonen het in het bestand opgeslagen voorbeeld met lage resolutie totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen +@msg linked type areas past VectorCraft's limits were left out gekoppelde tekstvlakken buiten de limieten van VectorCraft zijn weggelaten +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst die als masker wordt gebruikt in gekoppelde vlakken, tekstomloop of een samengesteld pad knipt niet uit +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gekoppelde afbeeldingen zonder voorbeeld in het bestand tonen een tijdelijke aanduiding totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise vlaktekst in kaders die te kort zijn voor één regel van het lettertype waarin de tekst wordt weergegeven, heeft hogere kaders gekregen ({_1}): anders zou de tekst niet zichtbaar zijn @msg its editing data doesn't say where its art is zijn bewerkingsgegevens zeggen niet waar de illustratie zich bevindt @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) dit bestand is opgeslagen zonder PDF-compatibiliteit en de bewerkingsgegevens kunnen niet worden gelezen ({why}) @@ -5580,6 +5585,8 @@ swatch Bright Violet Felviolet @msg missing number `{key}` getal `{key}` ontbreekt @msg missing integer `{key}` geheel getal `{key}` ontbreekt @msg no such spine point dat aspunt bestaat niet +@msg `with` must be a list of at most 10000 spine point indexes `with` moet een lijst van hoogstens 10000 aspuntindexen zijn +@msg `with` moves points, not a handle `with` verplaatst punten, geen handgreep @msg no such spine segment dat assegment bestaat niet @msg not a blend geen vermenging @msg select a blend or give `id` selecteer een vermenging of geef `id` op @@ -6010,6 +6017,9 @@ anchor Points: Punten: Find Nearest Swatch… Dichtstbijzijnde staal zoeken… Find Nearest Swatch Dichtstbijzijnde staal zoeken Apply Nearest Swatch Dichtstbijzijnde staal toepassen +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Vulling op streek toepassen + Apply Stroke to Fill Streek op vulling toepassen Select objects to find the swatches nearest their colors. Selecteer objecten om de stalen te vinden die het dichtst bij hun kleuren liggen. @msg select objects or give `color` selecteer objecten of geef `color` op @msg `color` is not a colour `color` is geen kleur @@ -6275,6 +6285,29 @@ breakText Glyphs Glyphs Minimum angle Minimale hoek Maximum angle Maximale hoek +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Gekoppelde selecteren + Select Embedded Ingesloten selecteren + Select Missing Ontbrekende selecteren + Select Modified Gewijzigde selecteren + Select by Link Status Selecteren op koppelingsstatus + Select by Link Status… Selecteren op koppelingsstatus… + Search images Afbeeldingen zoeken + No images match. Geen afbeelding komt overeen. +@msgplural Selected {n} linked image|Selected {n} linked images {n} gekoppelde afbeelding geselecteerd|{n} gekoppelde afbeeldingen geselecteerd +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} ingesloten afbeelding geselecteerd|{n} ingesloten afbeeldingen geselecteerd +@msgplural Selected {n} missing image|Selected {n} missing images {n} ontbrekende afbeelding geselecteerd|{n} ontbrekende afbeeldingen geselecteerd +@msgplural Selected {n} modified image|Selected {n} modified images {n} gewijzigde afbeelding geselecteerd|{n} gewijzigde afbeeldingen geselecteerd +@msgplural Selected {n} image|Selected {n} images {n} afbeelding geselecteerd|{n} afbeeldingen geselecteerd +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; nog {n} is verborgen of vergrendeld|{selected}; nog {n} zijn verborgen of vergrendeld +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; nog {n} staat op een sjabloonlaag|{selected}; nog {n} staan op sjabloonlagen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; nog {n} staat buiten de geïsoleerde groep|{selected}; nog {n} staan buiten de geïsoleerde groep +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; nog {n} kan nu niet worden geselecteerd|{selected}; nog {n} kunnen nu niet worden geselecteerd + # Compound Shapes add-on Compound Shapes Samengestelde vormen Shape Mode Buttons Make Compound Shapes Vormmodus-knoppen maken samengestelde vormen + +# 3D Box add-on + 3D Box 3D-doos + 3D Box Tool 3D-doosgereedschap diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 908f36c948..6bb9ee44cf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1406,7 +1406,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Standardowe pionowe wyrównanie łacińskie Strikethrough Przekreślenie Character: Znak: + Paragraph: Akapit: Character options Opcje znaków + Paragraph options Opcje akapitu Subscript Indeks dolny Subscript (on the roadmap) Indeks dolny (w planach) Superscript Indeks górny @@ -4460,6 +4462,8 @@ imageTrace Outline Kontur @msg no such saved selection brak takiego zapisanego zaznaczenia @msg no such segment brak takiego segmentu @msg no such spine point brak takiego punktu grzbietu +@msg `with` must be a list of at most 10000 spine point indexes `with` musi być listą co najwyżej 10000 indeksów punktów grzbietu +@msg `with` moves points, not a handle `with` przesuwa punkty, nie uchwyt @msg no such spine segment brak takiego segmentu grzbietu @msg no such subpath brak takiej ścieżki podrzędnej @msg no such user library brak takiej biblioteki użytkownika @@ -4807,6 +4811,9 @@ imageTrace Outline Kontur @msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykła grafika, bez ich danych i ustawień @msg an image whose data is cut short was left out pominięto obraz z uciętymi danymi @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel połączone obrazy pokazują zapisany w pliku podgląd niskiej rozdzielczości, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza +@msg linked type areas past VectorCraft's limits were left out połączone obszary tekstu poza limitami VectorCraft zostały pominięte +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst użyty jako maska w połączonych obszarach, oblewanym tekście lub ścieżce złożonej nie przycina +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel połączone obrazy bez podglądu w pliku pokazują symbol zastępczy, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise tekst akapitowy w ramkach niższych niż wiersz wyświetlanej czcionki otrzymał wyższe ramki ({_1}): inaczej tekst nie byłby widoczny @msg its editing data doesn't say where its art is jego dane edycyjne nie określają położenia kompozycji @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ten plik zapisano bez zgodności z PDF, a jego danych edycyjnych nie można odczytać ({why}) @@ -5954,6 +5961,9 @@ anchor Points: Punkty: Find Nearest Swatch… Znajdź najbliższą próbkę… Find Nearest Swatch Znajdź najbliższą próbkę Apply Nearest Swatch Zastosuj najbliższą próbkę +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Zastosuj wypełnienie do obrysu + Apply Stroke to Fill Zastosuj obrys do wypełnienia Select objects to find the swatches nearest their colors. Zaznacz obiekty, aby znaleźć próbki najbliższe ich kolorom. @msg select objects or give `color` zaznacz obiekty lub podaj `color` @msg `color` is not a colour `color` nie jest kolorem @@ -6220,6 +6230,29 @@ breakText Glyphs Glify Minimum angle Kąt minimalny Maximum angle Kąt maksymalny +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Zaznacz połączone + Select Embedded Zaznacz osadzone + Select Missing Zaznacz brakujące + Select Modified Zaznacz zmodyfikowane + Select by Link Status Zaznacz według stanu połączenia + Select by Link Status… Zaznacz według stanu połączenia… + Search images Szukaj obrazów + No images match. Żaden obraz nie pasuje. +@msgplural Selected {n} linked image|Selected {n} linked images Zaznaczono {n} połączony obraz|Zaznaczono {n} połączone obrazy|Zaznaczono {n} połączonych obrazów +@msgplural Selected {n} embedded image|Selected {n} embedded images Zaznaczono {n} osadzony obraz|Zaznaczono {n} osadzone obrazy|Zaznaczono {n} osadzonych obrazów +@msgplural Selected {n} missing image|Selected {n} missing images Zaznaczono {n} brakujący obraz|Zaznaczono {n} brakujące obrazy|Zaznaczono {n} brakujących obrazów +@msgplural Selected {n} modified image|Selected {n} modified images Zaznaczono {n} zmodyfikowany obraz|Zaznaczono {n} zmodyfikowane obrazy|Zaznaczono {n} zmodyfikowanych obrazów +@msgplural Selected {n} image|Selected {n} images Zaznaczono {n} obraz|Zaznaczono {n} obrazy|Zaznaczono {n} obrazów +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; jeszcze {n} jest ukryty lub zablokowany|{selected}; jeszcze {n} są ukryte lub zablokowane|{selected}; jeszcze {n} jest ukrytych lub zablokowanych +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; jeszcze {n} jest na warstwie szablonu|{selected}; jeszcze {n} są na warstwach szablonu|{selected}; jeszcze {n} jest na warstwach szablonu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; jeszcze {n} jest poza izolowaną grupą|{selected}; jeszcze {n} są poza izolowaną grupą|{selected}; jeszcze {n} jest poza izolowaną grupą +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć + # Compound Shapes add-on Compound Shapes Kształty złożone Shape Mode Buttons Make Compound Shapes Przyciski trybów kształtu tworzą kształty złożone + +# 3D Box add-on + 3D Box Bryła 3D + 3D Box Tool Narzędzie Bryła 3D diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index eb376906ca..cbdda2921a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2748,7 +2748,9 @@ digits Malayalam Malaiala Stroke Options Opções de Traçado Stroke Weight Peso do Traçado Character: Caractere: + Paragraph: Parágrafo: Character options Opções de caractere + Paragraph options Opções de parágrafo Stroke options Opções de traçado Transform options Opções de transformação Stroke: Traçado: @@ -3910,6 +3912,8 @@ axis Both Ambos @msg no such saved selection seleção salva inexistente @msg no such segment segmento inexistente @msg no such spine point ponto da coluna inexistente +@msg `with` must be a list of at most 10000 spine point indexes `with` deve ser uma lista de no máximo 10000 índices de pontos da coluna +@msg `with` moves points, not a handle `with` move pontos, não uma alça @msg no such spine segment segmento da coluna inexistente @msg no such subpath subtraçado inexistente @msg no such user library biblioteca do usuário inexistente @@ -4901,6 +4905,9 @@ axis Both Ambos @msg object {id} is not a selected top-level object o objeto {id} não é um objeto selecionado de nível superior @msg {path}: not a file {path}: não é um arquivo @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel as imagens vinculadas mostram a visualização de baixa resolução salva no arquivo até que seus arquivos sejam encontrados: revincule-as no painel Links +@msg linked type areas past VectorCraft's limits were left out as áreas de texto encadeadas além dos limites do VectorCraft foram omitidas +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip o texto usado como máscara em áreas encadeadas, texto com quebra ou um caminho composto não recorta +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel as imagens vinculadas sem visualização no arquivo mostram um espaço reservado até que seus arquivos sejam encontrados: revincule-as no painel Links @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise o texto de área em molduras baixas demais para uma linha da fonte em que aparece recebeu molduras mais altas ({_1}): senão o texto não apareceria @msg every numbered name for {name} is taken in the document's folder todos os nomes numerados para {name} já existem na pasta do documento @msg No linked files to look for Nenhum arquivo vinculado para procurar @@ -6016,6 +6023,9 @@ anchor Points: Pontos: Find Nearest Swatch… Localizar Amostra Mais Próxima… Find Nearest Swatch Localizar Amostra Mais Próxima Apply Nearest Swatch Aplicar Amostra Mais Próxima +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplicar Preenchimento ao Traçado + Apply Stroke to Fill Aplicar Traçado ao Preenchimento Select objects to find the swatches nearest their colors. Selecione objetos para localizar as amostras mais próximas de suas cores. @msg select objects or give `color` selecione objetos ou informe `color` @msg `color` is not a colour `color` não é uma cor @@ -6438,6 +6448,29 @@ swatch Yellow Green Verde-amarelado Minimum angle Ângulo Mínimo Maximum angle Ângulo Máximo +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecionar vinculadas + Select Embedded Selecionar incorporadas + Select Missing Selecionar ausentes + Select Modified Selecionar modificadas + Select by Link Status Selecionar por status do vínculo + Select by Link Status… Selecionar por status do vínculo… + Search images Pesquisar imagens + No images match. Nenhuma imagem corresponde. +@msgplural Selected {n} linked image|Selected {n} linked images {n} imagem vinculada selecionada|{n} imagens vinculadas selecionadas +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} imagem incorporada selecionada|{n} imagens incorporadas selecionadas +@msgplural Selected {n} missing image|Selected {n} missing images {n} imagem ausente selecionada|{n} imagens ausentes selecionadas +@msgplural Selected {n} modified image|Selected {n} modified images {n} imagem modificada selecionada|{n} imagens modificadas selecionadas +@msgplural Selected {n} image|Selected {n} images {n} imagem selecionada|{n} imagens selecionadas +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; mais {n} está oculta ou bloqueada|{selected}; mais {n} estão ocultas ou bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; mais {n} está em uma camada de modelo|{selected}; mais {n} estão em camadas de modelo +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; mais {n} está fora do grupo isolado|{selected}; mais {n} estão fora do grupo isolado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; mais {n} não pode ser selecionada agora|{selected}; mais {n} não podem ser selecionadas agora + # Compound Shapes add-on Compound Shapes Formas Compostas Shape Mode Buttons Make Compound Shapes Os Botões de Modo de Forma Criam Formas Compostas + +# 3D Box add-on + 3D Box Caixa 3D + 3D Box Tool Ferramenta Caixa 3D diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d700736c6c..df48bf8abe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3322,7 +3322,9 @@ digits Malayalam Малаялам Patterns Узоры Stroke Options Параметры обводки Character: Символ: + Paragraph: Абзац: Character options Параметры символа + Paragraph options Параметры абзаца Stroke options Параметры обводки Transform options Параметры трансформирования Stroke Weight Толщина обводки @@ -4367,6 +4369,8 @@ axis Both Оба @msg no such saved selection такого сохранённого выделения нет @msg no such segment такого сегмента нет @msg no such spine point такой точки остова нет +@msg `with` must be a list of at most 10000 spine point indexes `with` должен быть списком не более чем из 10000 индексов точек остова +@msg `with` moves points, not a handle `with` перемещает точки, а не маркер @msg no such spine segment такого сегмента остова нет @msg no such subpath такого вложенного контура нет @msg no such user library такой пользовательской библиотеки нет @@ -4712,6 +4716,9 @@ axis Both Оба @msg graphs come in as plain art, without their data or settings диаграммы импортируются как обычная графика, без их данных и настроек @msg an image whose data is cut short was left out изображение с обрезанными данными пропущено @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel связанные изображения показываются как сохранённый в файле просмотр низкого разрешения, пока их файлы не найдены: восстановите связи на панели «Связи» +@msg linked type areas past VectorCraft's limits were left out связанные текстовые области за пределами ограничений VectorCraft пропущены +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, используемый как маска в связанных областях, обтекающем тексте или составном контуре, не обрезает +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel связанные изображения без просмотра в файле показываются как заполнитель, пока их файлы не найдены: восстановите связи на панели «Связи» @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текст в области в рамках, слишком низких для строки шрифта, которым он отображается, получил более высокие рамки ({_1}): иначе он не был бы виден @msg its editing data doesn't say where its art is в его данных редактирования не указано, где находится графика @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) этот файл сохранён без совместимости с PDF, и его данные редактирования не удаётся прочитать ({why}) @@ -6077,6 +6084,9 @@ anchor Points: Точки: Find Nearest Swatch… Найти ближайший образец… Find Nearest Swatch Найти ближайший образец Apply Nearest Swatch Применить ближайший образец +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Применить заливку к обводке + Apply Stroke to Fill Применить обводку к заливке Select objects to find the swatches nearest their colors. Выделите объекты, чтобы найти образцы, ближайшие к их цветам. @msg select objects or give `color` выделите объекты или укажите `color` @msg `color` is not a colour `color` не является цветом @@ -6454,6 +6464,29 @@ shape Open Открытый Minimum angle Минимальный угол Maximum angle Максимальный угол +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Выделить связанные + Select Embedded Выделить внедрённые + Select Missing Выделить отсутствующие + Select Modified Выделить изменённые + Select by Link Status Выделить по состоянию связи + Select by Link Status… Выделить по состоянию связи… + Search images Поиск изображений + No images match. Нет подходящих изображений. +@msgplural Selected {n} linked image|Selected {n} linked images Выделено {n} связанное изображение|Выделено {n} связанных изображения|Выделено {n} связанных изображений +@msgplural Selected {n} embedded image|Selected {n} embedded images Выделено {n} внедрённое изображение|Выделено {n} внедрённых изображения|Выделено {n} внедрённых изображений +@msgplural Selected {n} missing image|Selected {n} missing images Выделено {n} отсутствующее изображение|Выделено {n} отсутствующих изображения|Выделено {n} отсутствующих изображений +@msgplural Selected {n} modified image|Selected {n} modified images Выделено {n} изменённое изображение|Выделено {n} изменённых изображения|Выделено {n} изменённых изображений +@msgplural Selected {n} image|Selected {n} images Выделено {n} изображение|Выделено {n} изображения|Выделено {n} изображений +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ещё {n} скрыто или заблокировано|{selected}; ещё {n} скрыты или заблокированы|{selected}; ещё {n} скрыты или заблокированы +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ещё {n} на слое-шаблоне|{selected}; ещё {n} на слоях-шаблонах|{selected}; ещё {n} на слоях-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить + # Compound Shapes add-on Compound Shapes Составные фигуры Shape Mode Buttons Make Compound Shapes Кнопки режимов фигур создают составные фигуры + +# 3D Box add-on + 3D Box 3D-параллелепипед + 3D Box Tool Инструмент «3D-параллелепипед» diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 85f4812d15..142a85f22c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3213,7 +3213,9 @@ digits Malayalam Malayalam Patterns Mönster Stroke Options Konturalternativ Character: Tecken: + Paragraph: Stycke: Character options Teckenalternativ + Paragraph options Styckealternativ Stroke options Konturalternativ Transform options Transformeringsalternativ Stroke Weight Konturtjocklek @@ -4235,6 +4237,8 @@ axis Both Båda @msg no such saved selection den sparade markeringen finns inte @msg no such segment segmentet finns inte @msg no such spine point ryggradspunkten finns inte +@msg `with` must be a list of at most 10000 spine point indexes `with` måste vara en lista med högst 10000 ryggradspunktsindex +@msg `with` moves points, not a handle `with` flyttar punkter, inte ett handtag @msg no such spine segment ryggradssegmentet finns inte @msg no such subpath delbanan finns inte @msg no such user library användarbiblioteket finns inte @@ -4574,6 +4578,9 @@ axis Both Båda @msg graphs come in as plain art, without their data or settings diagram läses in som vanlig grafik, utan sina data och inställningar @msg an image whose data is cut short was left out en bild med avkortade data utelämnades @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel länkade bilder visar förhandsgranskningen med låg upplösning som sparats i filen tills deras filer hittas: länka om dem i panelen Länkar +@msg linked type areas past VectorCraft's limits were left out länkade textområden utöver VectorCrafts gränser utelämnades +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text som används som mask i länkade områden, ombruten text eller en sammansatt bana beskär inte +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel länkade bilder utan förhandsgranskning i filen visar en platshållare tills deras filer hittas: länka om dem i panelen Länkar @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise områdestext i ramar som var för låga för en rad i det typsnitt den visas med fick högre ramar ({_1}): annars skulle texten inte synas @msg its editing data doesn't say where its art is dess redigeringsdata anger inte var dess grafik finns @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) den här filen sparades utan PDF-kompatibilitet och dess redigeringsdata kan inte läsas ({why}) @@ -6152,6 +6159,9 @@ shape Open Öppen Find Nearest Swatch… Sök närmaste färgruta… Find Nearest Swatch Sök närmaste färgruta Apply Nearest Swatch Använd närmaste färgruta +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Använd fyllning på kontur + Apply Stroke to Fill Använd kontur på fyllning Select objects to find the swatches nearest their colors. Markera objekt för att hitta de färgrutor som ligger närmast deras färger. @msg select objects or give `color` markera objekt eller ange `color` @msg `color` is not a colour `color` är ingen färg @@ -6421,6 +6431,29 @@ digits Hindi Hindi Minimum angle Minsta vinkel Maximum angle Största vinkel +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markera länkade + Select Embedded Markera inbäddade + Select Missing Markera saknade + Select Modified Markera ändrade + Select by Link Status Markera efter länkstatus + Select by Link Status… Markera efter länkstatus… + Search images Sök bilder + No images match. Ingen bild matchar. +@msgplural Selected {n} linked image|Selected {n} linked images Markerade {n} länkad bild|Markerade {n} länkade bilder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerade {n} inbäddad bild|Markerade {n} inbäddade bilder +@msgplural Selected {n} missing image|Selected {n} missing images Markerade {n} saknad bild|Markerade {n} saknade bilder +@msgplural Selected {n} modified image|Selected {n} modified images Markerade {n} ändrad bild|Markerade {n} ändrade bilder +@msgplural Selected {n} image|Selected {n} images Markerade {n} bild|Markerade {n} bilder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} till är dold eller låst|{selected}; {n} till är dolda eller låsta +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} till ligger på ett mallager|{selected}; {n} till ligger på mallager +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} till ligger utanför den isolerade gruppen|{selected}; {n} till ligger utanför den isolerade gruppen +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} till kan inte markeras nu|{selected}; {n} till kan inte markeras nu + # Compound Shapes add-on Compound Shapes Sammansatta former Shape Mode Buttons Make Compound Shapes Formlägesknapparna skapar sammansatta former + +# 3D Box add-on + 3D Box 3D-låda + 3D Box Tool 3D-lådverktyg diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 39ac29fa78..5bc0190aa6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1823,6 +1823,12 @@ fn blend_spine_param_errors_say_what_is_wrong() { ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 1e12, "y": 0}), "x and y must be finite"), ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 0, "handle": "up"}), "handle must be in or out"), ("object.blend.spine.moveAnchor", json!({"anchor": 5, "x": 0, "y": 0}), "no such spine point"), + ( + "object.blend.spine.moveAnchor", + json!({"anchor": 0, "x": 0, "y": 0, "with": "1"}), + "`with` must be a list of at most 10000 spine point indexes", + ), + ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 0, "with": [1], "handle": "in"}), "`with` moves points, not a handle"), ("object.blend.spine.moveAnchor", json!({"id": other, "anchor": 0, "x": 0, "y": 0}), "not a blend"), ("object.blend.spine.reshapeSegment", json!({"segment": 0, "dx": 1e12}), "t, dx and dy must be finite"), ("object.blend.spine.reshapeSegment", json!({"segment": 5, "dy": 10}), "no such spine segment"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5c6446de73..c296f66aa0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3115,7 +3115,9 @@ digits Malayalam Malayalam Patterns Desenler Stroke Options Kontur Seçenekleri Character: Karakter: + Paragraph: Paragraf: Character options Karakter seçenekleri + Paragraph options Paragraf seçenekleri Stroke options Kontur seçenekleri Transform options Dönüştürme seçenekleri Stroke Weight Kontur Kalınlığı @@ -4411,6 +4413,9 @@ axis Both Her İkisi @msg graphs come in as plain art, without their data or settings grafikler, verileri ve ayarları olmadan düz çizim olarak içe aktarılır @msg an image whose data is cut short was left out verileri kısa kesilen bir resim dışarıda bırakıldı @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel bağlantılı resimler, dosyaları bulunana kadar dosyaya kaydedilen düşük çözünürlüklü önizlemeyi gösterir: bunları Bağlantılar panelinde yeniden bağlayın +@msg linked type areas past VectorCraft's limits were left out VectorCraft sınırlarını aşan bağlantılı metin alanları dışarıda bırakıldı +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip bağlantılı alanlarda, kaydırılan metinde veya bileşik yolda maske olarak kullanılan metin kırpmaz +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel dosyada önizlemesi olmayan bağlantılı resimler, dosyaları bulunana kadar bir yer tutucu gösterir: bunları Bağlantılar panelinde yeniden bağlayın @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise çerçevelerdeki alan türü, daha uzun çerçevelerde gösterdiği yazı tipinin bir satırı için çok kısa ({_1}): bunların türü aksi halde gösterilmez @msg its editing data doesn't say where its art is düzenleme verileri sanatın nerede olduğunu söylemiyor @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) bu dosya PDF uyumluluğu olmadan kaydedildi ve düzenleme verileri okunamıyor ({why}) @@ -5427,6 +5432,8 @@ theme Appearance Görünüm @msg mask art ends outside a mask dictionary maske çizimi bir maske sözlüğünün dışında bitiyor @msg missing number `{key}` `{key}` sayısı eksik @msg no such spine point böyle bir omurga noktası yok +@msg `with` must be a list of at most 10000 spine point indexes `with` en fazla 10000 omurga noktası dizininden oluşan bir liste olmalıdır +@msg `with` moves points, not a handle `with` noktaları taşır, tutamacı değil @msg no such spine segment böyle bir omurga segmenti yok @msg not a blend bir karışım değil @msg select a blend or give `id` bir karışım seçin veya `id` belirtin @@ -6057,6 +6064,9 @@ anchor Points: Noktalar: Find Nearest Swatch… En Yakın Renk Örneğini Bul… Find Nearest Swatch En Yakın Renk Örneğini Bul Apply Nearest Swatch En Yakın Renk Örneğini Uygula +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Dolguyu Kontura Uygula + Apply Stroke to Fill Konturu Dolguya Uygula Select objects to find the swatches nearest their colors. Renklerine en yakın renk örneklerini bulmak için nesneleri seçin. @msg select objects or give `color` nesneleri seçin veya `color` verin @msg `color` is not a colour `color` bir renk değil @@ -6322,6 +6332,29 @@ breakText Glyphs Glifler Minimum angle En Küçük Açı Maximum angle En Büyük Açı +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Bağlantılıları Seç + Select Embedded Gömülüleri Seç + Select Missing Eksikleri Seç + Select Modified Değiştirilenleri Seç + Select by Link Status Bağlantı Durumuna Göre Seç + Select by Link Status… Bağlantı Durumuna Göre Seç… + Search images Görüntülerde ara + No images match. Eşleşen görüntü yok. +@msgplural Selected {n} linked image|Selected {n} linked images {n} bağlantılı görüntü seçildi +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} gömülü görüntü seçildi +@msgplural Selected {n} missing image|Selected {n} missing images {n} eksik görüntü seçildi +@msgplural Selected {n} modified image|Selected {n} modified images {n} değiştirilmiş görüntü seçildi +@msgplural Selected {n} image|Selected {n} images {n} görüntü seçildi +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} tane daha gizli veya kilitli +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} tane daha şablon katmanında +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} tane daha izole grubun dışında +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} tane daha şu anda seçilemiyor + # Compound Shapes add-on Compound Shapes Bileşik Şekiller Shape Mode Buttons Make Compound Shapes Şekil Modu Düğmeleri Bileşik Şekiller Yapar + +# 3D Box add-on + 3D Box 3B Kutu + 3D Box Tool 3B Kutu Aracı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4bb7083401..5f823ba124 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3320,7 +3320,9 @@ effect Points Точки Patterns Візерунки Stroke Options Параметри обведення Character: Символ: + Paragraph: Абзац: Character options Параметри символу + Paragraph options Параметри абзацу Stroke options Параметри обведення Transform options Параметри трансформування Stroke Weight Товщина обведення @@ -4356,6 +4358,8 @@ axis Both Обидві @msg no such saved selection такого збереженого виділення немає @msg no such segment такого сегменту немає @msg no such spine point такої точки осі немає +@msg `with` must be a list of at most 10000 spine point indexes `with` має бути списком щонайбільше з 10000 індексів точок осі +@msg `with` moves points, not a handle `with` переміщує точки, а не маркер @msg no such spine segment такого сегмента осі немає @msg no such subpath такого вкладеного контуру немає @msg no such user library такої користувацької бібліотеки немає @@ -4701,6 +4705,9 @@ axis Both Обидві @msg graphs come in as plain art, without their data or settings діаграми імпортуються як звичайна графіка, без їхніх даних і налаштувань @msg an image whose data is cut short was left out зображення з обрізаними даними пропущено @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel пов’язані зображення показуються як збережений у файлі перегляд низької роздільності, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки» +@msg linked type areas past VectorCraft's limits were left out пов’язані текстові області понад обмеження VectorCraft пропущено +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, використаний як маска у пов’язаних областях, тексті з обтіканням або складеному контурі, не обрізає +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel пов’язані зображення без перегляду у файлі показуються як заповнювач, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки» @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текст в області в рамках, занизьких для рядка шрифту, яким він показується, отримав вищі рамки ({_1}): інакше його не було б видно @msg its editing data doesn't say where its art is у даних редагування не зазначено, де знаходиться графіка @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) цей файл збережений без сумісності з PDF, і його дані редагування не вдається прочитати ({why}) @@ -5699,6 +5706,9 @@ anchor Points: Точки: Find Nearest Swatch… Знайти найближчий зразок… Find Nearest Swatch Знайти найближчий зразок Apply Nearest Swatch Застосувати найближчий зразок +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Застосувати заливку до обведення + Apply Stroke to Fill Застосувати обведення до заливки Select objects to find the swatches nearest their colors. Виділіть об’єкти, щоб знайти зразки, найближчі до їхніх кольорів. @msg select objects or give `color` виділіть об’єкти або вкажіть `color` @msg `color` is not a colour `color` не є кольором @@ -5965,6 +5975,29 @@ breakText Glyphs Гліфи Minimum angle Мінімальний кут Maximum angle Максимальний кут +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Виділити пов’язані + Select Embedded Виділити вбудовані + Select Missing Виділити відсутні + Select Modified Виділити змінені + Select by Link Status Виділити за станом зв’язку + Select by Link Status… Виділити за станом зв’язку… + Search images Пошук зображень + No images match. Немає відповідних зображень. +@msgplural Selected {n} linked image|Selected {n} linked images Виділено {n} пов’язане зображення|Виділено {n} пов’язані зображення|Виділено {n} пов’язаних зображень +@msgplural Selected {n} embedded image|Selected {n} embedded images Виділено {n} вбудоване зображення|Виділено {n} вбудовані зображення|Виділено {n} вбудованих зображень +@msgplural Selected {n} missing image|Selected {n} missing images Виділено {n} відсутнє зображення|Виділено {n} відсутні зображення|Виділено {n} відсутніх зображень +@msgplural Selected {n} modified image|Selected {n} modified images Виділено {n} змінене зображення|Виділено {n} змінені зображення|Виділено {n} змінених зображень +@msgplural Selected {n} image|Selected {n} images Виділено {n} зображення|Виділено {n} зображення|Виділено {n} зображень +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ще {n} приховане або заблоковане|{selected}; ще {n} приховані або заблоковані|{selected}; ще {n} приховані або заблоковані +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ще {n} на шарі-шаблоні|{selected}; ще {n} на шарах-шаблонах|{selected}; ще {n} на шарах-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити + # Compound Shapes add-on Compound Shapes Складені фігури Shape Mode Buttons Make Compound Shapes Кнопки режимів фігур створюють складені фігури + +# 3D Box add-on + 3D Box 3D-паралелепіпед + 3D Box Tool Інструмент «3D-паралелепіпед» diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 330792405e..7d157502cf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -468,12 +468,14 @@ font-technology Variable Biến thiên Character / Paragraph Ký tự / Đoạn văn Character Alignment Căn chỉnh ký tự Character options Tùy chọn ký tự + Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự Character Styles Các kiểu ký tự Character: Ký tự: + Paragraph: Đoạn văn: Check Links Kiểm tra liên kết # Check Script (File › Scripts) and the report it shows on a script written for the reference app. Check Script Kiểm tra script @@ -4535,6 +4537,9 @@ theme Appearance Giao diện @msg line {line}: value for `{var}` must be true or false dòng {line}: giá trị của `{var}` phải là true hoặc false @msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes dòng {line}: giá trị của `{var}` dài hơn {MAX_GRAPH_CSV} byte @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel ảnh liên kết hiển thị bản xem trước độ phân giải thấp đã lưu trong tệp cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết +@msg linked type areas past VectorCraft's limits were left out các vùng chữ liên kết vượt quá giới hạn của VectorCraft đã bị bỏ qua +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip chữ dùng làm mặt nạ trong các vùng liên kết, chữ bao quanh hoặc đường dẫn phức không cắt xén +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ảnh liên kết không có bản xem trước trong tệp hiển thị ô giữ chỗ cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết @msg Live Paint Merge: select a Live Paint group and the paths to add Hợp nhất tô trực tiếp: chọn nhóm tô trực tiếp và các đường dẫn để thêm @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Tô trực tiếp nhận đường dẫn và đường dẫn phức: hãy chuyển văn bản, hình ảnh và các đối tượng khác thành đường dẫn trước @msg Live Paint: select paths or compound paths Tô trực tiếp: chọn đường dẫn hoặc đường dẫn phức @@ -4656,6 +4661,8 @@ theme Appearance Giao diện @msg no such saved selection không có vùng chọn đã lưu như vậy @msg no such segment không có đoạn như vậy @msg no such spine point không có điểm trục như vậy +@msg `with` must be a list of at most 10000 spine point indexes `with` phải là danh sách tối đa 10000 chỉ số điểm trục +@msg `with` moves points, not a handle `with` di chuyển các điểm, không phải tay nắm @msg no such spine segment không có đoạn trục như vậy @msg no such subpath không có nhánh con như vậy @msg no such user library không có thư viện người dùng như vậy @@ -5700,6 +5707,9 @@ anchor Points: Điểm: Find Nearest Swatch… Tìm mẫu màu gần nhất… Find Nearest Swatch Tìm mẫu màu gần nhất Apply Nearest Swatch Áp dụng mẫu màu gần nhất +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Áp dụng màu tô cho nét + Apply Stroke to Fill Áp dụng nét cho màu tô Select objects to find the swatches nearest their colors. Chọn đối tượng để tìm các mẫu màu gần nhất với màu của chúng. @msg select objects or give `color` chọn đối tượng hoặc cung cấp `color` @msg `color` is not a colour `color` không phải là màu @@ -5966,6 +5976,29 @@ breakText Glyphs Glyph Minimum angle Góc tối thiểu Maximum angle Góc tối đa +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Chọn ảnh đã liên kết + Select Embedded Chọn ảnh đã nhúng + Select Missing Chọn ảnh bị thiếu + Select Modified Chọn ảnh đã sửa đổi + Select by Link Status Chọn theo trạng thái liên kết + Select by Link Status… Chọn theo trạng thái liên kết… + Search images Tìm ảnh + No images match. Không có ảnh nào khớp. +@msgplural Selected {n} linked image|Selected {n} linked images Đã chọn {n} ảnh đã liên kết +@msgplural Selected {n} embedded image|Selected {n} embedded images Đã chọn {n} ảnh đã nhúng +@msgplural Selected {n} missing image|Selected {n} missing images Đã chọn {n} ảnh bị thiếu +@msgplural Selected {n} modified image|Selected {n} modified images Đã chọn {n} ảnh đã sửa đổi +@msgplural Selected {n} image|Selected {n} images Đã chọn {n} ảnh +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; thêm {n} ảnh bị ẩn hoặc khóa +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; thêm {n} ảnh nằm trên lớp mẫu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; thêm {n} ảnh nằm ngoài nhóm đã tách biệt +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; thêm {n} ảnh hiện không thể chọn + # Compound Shapes add-on Compound Shapes Hình phức hợp Shape Mode Buttons Make Compound Shapes Nút chế độ hình dạng tạo hình phức hợp + +# 3D Box add-on + 3D Box Hộp 3D + 3D Box Tool Công cụ Hộp 3D diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 48f040a9cb..643b922180 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1883,6 +1883,8 @@ file-filter Templates 模板 @msg the blend has no spine 混合对象没有脊线 @msg the spine has no segments 脊线没有线段 @msg no such spine point 没有此脊线点 +@msg `with` must be a list of at most 10000 spine point indexes `with` 必须是最多 10000 个脊线点索引的列表 +@msg `with` moves points, not a handle `with` 移动的是点,不是手柄 @msg no such spine segment 没有此脊线线段 @msg a key object sits on that point 该点上有关键对象 @msg a spine keeps at least two points 脊线至少保留两个点 @@ -3158,7 +3160,9 @@ digits Malayalam 马拉雅拉姆数字 Patterns 图案 Stroke Options 描边选项 Character: 字符: + Paragraph: 段落: Character options 字符选项 + Paragraph options 段落选项 Stroke options 描边选项 Transform options 变换选项 Stroke Weight 描边粗细 @@ -3464,6 +3468,9 @@ digits Malayalam 马拉雅拉姆数字 Update Changed Links 更新已更改的链接 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗? @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接 +@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串接文字区域已省略 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串接区域、绕排文字或复合路径中用作蒙版的文字不会剪切 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 文件中没有预览的链接图片在找到其文件之前显示占位符:请在“链接”面板中重新链接 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容纳所显示字体一行的区域文字已加高框架 ({_1}):否则文字不会显示 Update Modified Links 更新已修改的链接 UPPERCASE 大写 @@ -5941,6 +5948,9 @@ anchor Points: 点: Find Nearest Swatch… 查找最接近的色板… Find Nearest Swatch 查找最接近的色板 Apply Nearest Swatch 应用最接近的色板 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 将填色应用于描边 + Apply Stroke to Fill 将描边应用于填色 Select objects to find the swatches nearest their colors. 选择对象以查找与其颜色最接近的色板。 @msg select objects or give `color` 请选择对象或提供 `color` @msg `color` is not a colour `color` 不是颜色 @@ -6206,6 +6216,29 @@ breakText Glyphs 字形 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 选择已链接 + Select Embedded 选择嵌入 + Select Missing 选择缺失 + Select Modified 选择已修改 + Select by Link Status 按链接状态选择 + Select by Link Status… 按链接状态选择… + Search images 搜索图像 + No images match. 没有匹配的图像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已选择 {n} 个已链接的图像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已选择 {n} 个嵌入的图像 +@msgplural Selected {n} missing image|Selected {n} missing images 已选择 {n} 个缺失的图像 +@msgplural Selected {n} modified image|Selected {n} modified images 已选择 {n} 个已修改的图像 +@msgplural Selected {n} image|Selected {n} images 已选择 {n} 个图像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 个已隐藏或锁定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 个位于模板图层上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 个位于隔离的编组之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 个现在无法选择 + # Compound Shapes add-on Compound Shapes 复合形状 Shape Mode Buttons Make Compound Shapes 形状模式按钮创建复合形状 + +# 3D Box add-on + 3D Box 3D 盒子 + 3D Box Tool 3D 盒子工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f0c659b50a..945626915d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2856,6 +2856,8 @@ file-filter Templates 範本 @msg the blend has no spine 漸變物件沒有脊線 @msg the spine has no segments 脊線沒有線段 @msg no such spine point 沒有這個脊線點 +@msg `with` must be a list of at most 10000 spine point indexes `with` 必須是最多 10000 個脊線點索引的清單 +@msg `with` moves points, not a handle `with` 移動的是點,不是控制把手 @msg no such spine segment 沒有這個脊線線段 @msg a key object sits on that point 該點上有關鍵物件 @msg a spine keeps at least two points 脊線至少要保留兩個點 @@ -4185,7 +4187,9 @@ digits Malayalam 馬來亞拉姆數字 Patterns 圖樣 Stroke Options 筆畫選項 Character: 字元: + Paragraph: 段落: Character options 字元選項 + Paragraph options 段落選項 Stroke options 筆畫選項 Transform options 變形選項 Stroke Weight 筆畫寬度 @@ -4494,6 +4498,9 @@ digits Malayalam 馬來亞拉姆數字 Update Changed Links 更新已變更的連結 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎? @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結 +@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串連文字區域已略過 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串連區域、繞圖文字或複合路徑中用作遮色片的文字不會剪裁 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 檔案中沒有預覽的連結圖片在找到其檔案之前顯示預留位置:請在「連結」面板中重新連結 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容納所顯示字體一行的區域文字已加高框架 ({_1}):否則文字不會顯示 Update Modified Links 更新已修改的連結 UPPERCASE 全部大寫 @@ -5737,6 +5744,9 @@ anchor Points: 點: Find Nearest Swatch… 尋找最接近的色票… Find Nearest Swatch 尋找最接近的色票 Apply Nearest Swatch 套用最接近的色票 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 將填色套用至筆畫 + Apply Stroke to Fill 將筆畫套用至填色 Select objects to find the swatches nearest their colors. 選取物件以尋找與其顏色最接近的色票。 @msg select objects or give `color` 請選取物件或提供 `color` @msg `color` is not a colour `color` 不是顏色 @@ -6003,6 +6013,29 @@ breakText Glyphs 字符 Minimum angle 最小角度 Maximum angle 最大角度 +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 選取已連結 + Select Embedded 選取已內嵌 + Select Missing 選取遺失 + Select Modified 選取已修改 + Select by Link Status 依連結狀態選取 + Select by Link Status… 依連結狀態選取… + Search images 搜尋影像 + No images match. 沒有符合的影像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已選取 {n} 個已連結的影像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已選取 {n} 個已內嵌的影像 +@msgplural Selected {n} missing image|Selected {n} missing images 已選取 {n} 個遺失的影像 +@msgplural Selected {n} modified image|Selected {n} modified images 已選取 {n} 個已修改的影像 +@msgplural Selected {n} image|Selected {n} images 已選取 {n} 個影像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 個已隱藏或鎖定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 個位於範本圖層上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 個位於隔離的群組之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 個現在無法選取 + # Compound Shapes add-on Compound Shapes 複合形狀 Shape Mode Buttons Make Compound Shapes 形狀模式按鈕製作複合形狀 + +# 3D Box add-on + 3D Box 3D 盒子 + 3D Box Tool 3D 盒子工具 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b0aa93d84..afb8cbbc4b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -154,6 +154,10 @@ pub struct VectorcraftApp { /// A `ui.pointer` request taken from the channel while synthetic input sent before it was not /// yet applied: it runs, ahead of the channel, on the first frame after that input is applied. deferred_control: Option, + /// When synthetic input was last dropped before a UI pass took it, the sequence number of the + /// next control request ([`ControlRequest::next_seq`]): a `ui.pointer` request made before it + /// came after that input and is answered with an error. + synthetic_dropped_before: u64, /// Window captures asked for and not answered yet. pending_screenshots: Vec, /// Admitted captures whose settled frame has not come yet (issued one at a time). diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a419204162..dff97c9a55 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -58,12 +58,15 @@ mod tree; mod ui_commands; pub use bar::menu_bar; +pub(crate) use bar::menu_open; pub(crate) use bar::{home_key, home_showing}; #[cfg(test)] use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut, shown_shortcut}; pub(crate) use invoke::graph_dialog; +#[cfg(test)] +pub(crate) use invoke::with_held_keys; pub use invoke::{click_target, invoke, invoke_from_system_menu}; #[cfg(test)] pub(crate) use labels::lists_plugin; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index a0e4e0d6ac..1d8d001975 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -42,6 +42,10 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { (ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles)) }) .inner; + // Whether a top-level menu is open: the docking renderer lowers the floating panels' OS windows + // while one is, or the menu would open under them. + ctx.data_mut(|d| d.insert_temp(menu_open_id(), open)); + let field = ctx.data(|d| d.get_temp::(field_key)); if !open && focused_text_field(&ctx).is_none() { ctx.data_mut(|d| d.remove::(field_key)); @@ -58,6 +62,16 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { end } +/// Where the menu bar keeps whether one of its top-level menus is open. +fn menu_open_id() -> egui::Id { + egui::Id::unique("menu-bar-open") +} + +/// Whether a menu of the in-window menu bar is open (`false` when no menu bar was drawn yet). +pub(crate) fn menu_open(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(menu_open_id())).unwrap_or(false) +} + /// Whether the pointer at `p` is really over the menu title `title`: inside it, and with no /// popup above it (a tall menu that egui moves up can cover the bar; hovering that menu must /// not switch to the title under it). diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 963eab802f..5b0d0f3c40 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -15,10 +15,13 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups -/// that hold the selected objects (`scope: "group"`). -pub(super) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { +/// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified +/// chosen with Shift add to the selection (`add: true`). +pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + // Select Linked, Embedded, Missing and Modified with Shift add to the selection. + crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, } } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e9776e78f4..1bb536f76e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -578,6 +578,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), + crate::addons::select::link_status::COMMAND => crate::addons::select::link_status::run(app, p), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), crate::addons::document::BATCH_TRACE => crate::addons::document::batch_trace(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 673ceb81fd..78553cc7bd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -135,7 +135,7 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]) or an item /// another stands in for ([`swapped_out`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - let en = enabled(app, id); + let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)); if (!en && hidden_when_disabled(id)) || swapped_out(app, id) { return None; } diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index cc177a4de1..ff39d90cff 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -270,6 +270,28 @@ pub(crate) fn showing(ui: &UiState, panel: &str) -> bool { (ui.open_panel.as_deref() == Some(panel) && iconic) || (!iconic && layout.panel_state(&panel.to_string()) == craft_ui::docking::PanelState::Front) } +/// Can either panel that uses row thumbnails be seen, including in a floating window or flyout? +/// An iconic group's open flyout is named for the icon that opened it; its active tab can differ. +fn thumbnail_panel_showing(ui: &UiState, ctx: &egui::Context) -> bool { + if !ui.dock || ui.screen_mode >= 3 { + return false; + } + let layout = layout_of(ui); + let regular = ["layers", "links"] + .iter() + .any(|panel| !in_iconic_column(&layout, panel) && layout.panel_state(&(*panel).to_string()) == craft_ui::docking::PanelState::Front); + let flyout = craft_ui::docking::flyout::(ctx, area_id()); + let iconic = flyout.as_ref().and_then(|anchor| { + dock_columns(&layout) + .into_iter() + .filter(|column| column.iconic) + .flat_map(|column| &column.groups) + .find(|group| group.panels.contains(anchor)) + .and_then(|group| group.active_panel()) + }); + regular || iconic.is_some_and(|panel| matches!(panel.as_str(), "layers" | "links")) +} + /// Where a panel with no other destination goes: a panel of the first expanded dock column, /// else of any column. fn first_dock_panel(layout: &Layout, except: &str) -> Option { @@ -1113,6 +1135,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } let modal = modal_open(app, &ctx); + // Palette windows are OS windows of their own, held above the app's window while it is active, + // so a dialog or a menu drawn in the main window would be covered by them. + #[cfg(not(target_arch = "wasm32"))] + palette_window_levels(&ctx, &layout, modal, egui::Popup::is_any_open(&ctx) || crate::menus::menu_open(&ctx)); let mut blocked = Vec::new(); if modal || egui::Popup::is_any_open(&ctx) { blocked.push(ctx.content_rect()); @@ -1169,11 +1195,64 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.open_dropped_files(window.dropped, None, shift); } forward_keys(app, &ctx, output.forwarded_events, output.forwarded_modifiers); + if !thumbnail_panel_showing(&app.ui, &ctx) { + // No panel can ask for these rows again this pass. Keep the cache of open documents, but + // discard worker jobs queued behind the one already rendering. + crate::panels::layers::show_thumbs_of(None); + } } /// Whether a modal is open: a dialog, About, the command palette, a native file dialog, or a /// window behind the modal backdrop last frame (export progress, plug-in runs). Floating panels /// in OS windows of their own take no input meanwhile, as the main window behind it takes none. +/// The window level and visibility a palette window takes: hidden under a modal dialog (a click +/// must not bring it back over the dialog), at the normal level under a menu or another popup drawn +/// in the main window (so the menu is seen), and otherwise its palette level, which craft-ui leaves +/// a palette at when it creates one: topmost while the app is active, behind other applications' +/// windows while it is not. +#[cfg(not(target_arch = "wasm32"))] +fn palette_window_state(modal: bool, popup: bool, active: bool) -> (egui::WindowLevel, bool) { + if modal { + return (egui::WindowLevel::Normal, false); + } + if popup { + // Hidden as under a dialog: a menu is drawn in the main window, and lowering a palette + // window is not always enough for it to go behind the window (the OS may keep it above + // while the app is activated through it). + return (egui::WindowLevel::Normal, false); + } + let level = if active { + egui::WindowLevel::AlwaysOnTop + } else if cfg!(target_os = "windows") { + egui::WindowLevel::AlwaysOnBottom + } else { + egui::WindowLevel::Normal + }; + (level, true) +} + +/// Sends the palette windows of `layout` the level and visibility [`palette_window_state`] gives +/// when they change. craft-ui varies a palette's level through the viewport builder, which egui +/// applies when the window opens and not to one already on screen, so the commands go explicitly to +/// the windows there are. +#[cfg(not(target_arch = "wasm32"))] +fn palette_window_levels(ctx: &egui::Context, layout: &Layout, modal: bool, popup: bool) { + let active = ctx.input(|i| i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true))); + let key = area_id().with("palette-levels-state"); + if ctx.data(|d| d.get_temp::<(bool, bool, bool)>(key)) == Some((modal, popup, active)) { + return; + } + ctx.data_mut(|d| d.insert_temp(key, (modal, popup, active))); + + let (level, visible) = palette_window_state(modal, popup, active); + for window in &layout.floating { + let viewport = craft_ui::docking::DockArea::::window_viewport(area_id(), window.id); + ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::WindowLevel(level)); + ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::Visible(visible)); + } +} + +/// Does a modal dialog block the app's other windows ([`modal_open`] for the docking renderer)? pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { app.ui.dialog.is_some() || app.ui.about diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 77e3d08bc6..a7c6614044 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -34,6 +34,9 @@ struct Host { child_transition_overlay: Option<(ViewportId, Rect, bool)>, child_empty_overlay: Option<(ViewportId, Rect)>, child_pass_through_overlay: Option<(ViewportId, Rect)>, + child_raise_overlay: Option<(ViewportId, Rect, bool)>, + child_raise_layer: Option<(ViewportId, egui::LayerId)>, + child_layer_order: HashMap>, /// The window with the keyboard. focus: ViewportId, time: f64, @@ -98,8 +101,23 @@ impl Host { host.borrow().child_transition_overlay.filter(|(viewport, _, _)| *viewport == id).map(|(_, rect, painted)| (rect, painted)); let child_empty_overlay = host.borrow().child_empty_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); let child_pass_through_overlay = host.borrow().child_pass_through_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let child_raise_overlay = host.borrow().child_raise_overlay.filter(|(viewport, _, _)| *viewport == id).map(|(_, rect, raise)| (rect, raise)); + let child_raise_layer = host.borrow().child_raise_layer.filter(|(viewport, _)| *viewport == id).map(|(_, layer)| layer); + let mut layer_order = Vec::new(); let mut full = ctx.run_ui(input, |ui| { + layer_order = ui.ctx().memory(|memory| memory.layer_ids().collect()); + if let Some((rect, _)) = child_raise_overlay { + egui::Area::new(egui::Id::unique("Child raised overlay")).order(egui::Order::Background).fixed_pos(rect.min).show(ui.ctx(), |ui| { + ui.allocate_space(rect.size()); + }); + } (viewport.viewport_ui_cb)(ui); + if let Some(layer) = child_raise_layer { + ui.ctx().move_to_top(layer); + } + if child_raise_overlay.is_some_and(|(_, raise)| raise) { + ui.ctx().move_to_top(egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay"))); + } if let Some(rect) = child_overlay { egui::Window::new("Child overlay").fixed_pos(rect.min).fixed_size(rect.size()).show(ui.ctx(), |ui| { ui.label("Child overlay"); @@ -151,6 +169,7 @@ impl Host { let mut shown = Vec::new(); full.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); let mut host = host.borrow_mut(); + host.child_layer_order.insert(id, layer_order); if let Some(window) = host.windows.get_mut(&id) { window.texts = shown; } @@ -174,6 +193,9 @@ impl Harness { child_transition_overlay: None, child_empty_overlay: None, child_pass_through_overlay: None, + child_raise_overlay: None, + child_raise_layer: None, + child_layer_order: HashMap::new(), focus: ViewportId::ROOT, time: 0.0, commands: Vec::new(), @@ -374,6 +396,84 @@ fn a_modal_blocks_native_windows_and_takes_the_keyboard_from_them() { assert_eq!(h.app.session.tool_id(), "pen", "the window takes keys again once the modal closes"); } +/// The level and visibility a palette window takes under a dialog or a menu, and otherwise: a +/// palette stays out of the way of anything drawn in the main window. +#[test] +fn a_palette_window_keeps_out_of_the_way_of_the_main_windows_dialog_and_menus() { + use egui::WindowLevel; + assert_eq!(palette_window_state(true, true, true), (WindowLevel::Normal, false), "hidden under a dialog, even in a menu"); + assert_eq!(palette_window_state(true, false, true), (WindowLevel::Normal, false), "hidden under a dialog"); + assert_eq!(palette_window_state(false, true, true), (WindowLevel::Normal, false), "hidden under a menu: it is drawn in the main window"); + assert_eq!(palette_window_state(false, false, true), (WindowLevel::AlwaysOnTop, true), "its palette level while the app is active"); + let inactive = palette_window_state(false, false, false); + assert!(inactive.1, "shown while the app is inactive"); + assert_ne!(inactive.0, WindowLevel::AlwaysOnTop, "and not above other applications' windows: {:?}", inactive.0); +} + +/// With a menu of the in-window menu bar open, the palettes take the normal level (still shown): +/// the menu is drawn in the main window, or it would open under them. +#[test] +fn a_menu_of_the_menu_bar_lowers_the_palette_windows() { + let mut h = Harness::new(); + let viewport = h.float("navigator"); + h.host.borrow_mut().commands.clear(); + let layout = layout_of(&h.app.ui); + h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("menu-bar-open"), true)); + assert!(crate::menus::menu_open(&h.ctx), "the menu bar's state says a menu is open"); + palette_window_levels(&h.ctx, &layout, false, crate::menus::menu_open(&h.ctx)); + h.frames(1); + let commands: Vec<(egui::ViewportId, ViewportCommand)> = h.host.borrow().commands.clone(); + let levels: Vec = commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::WindowLevel(level) if *id == viewport => Some(*level), + _ => None, + }) + .collect(); + assert!(levels.contains(&egui::WindowLevel::Normal), "the palette drops its topmost level under the menu: {levels:?}"); + assert!( + commands.iter().any(|(id, command)| *id == viewport && matches!(command, ViewportCommand::Visible(false))), + "and is hidden until the menu closes" + ); +} +/// A modal dialog is drawn in the main window, so the palettes' OS windows leave their topmost +/// level while it is open and take it back after, or the dialog would be covered by them. +#[test] +fn a_modal_lowers_the_native_palette_windows() { + let mut h = Harness::new(); + let viewport = h.float("swatches"); + let levels = |h: &Harness| -> Vec { + h.host + .borrow() + .commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::WindowLevel(level) if *id == viewport => Some(*level), + _ => None, + }) + .collect() + }; + let hidden = |h: &Harness| -> Vec { + h.host + .borrow() + .commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::Visible(visible) if *id == viewport => Some(*visible), + _ => None, + }) + .collect() + }; + h.app.ui.about = true; + h.frames(4); + assert!(levels(&h).contains(&egui::WindowLevel::Normal), "the palette leaves AlwaysOnTop under the modal: {:?}", levels(&h)); + assert_eq!(hidden(&h), [false], "and is hidden, so a click cannot bring it up over the dialog: {:?}", hidden(&h)); + h.app.ui.about = false; + h.frames(4); + assert!(levels(&h).contains(&egui::WindowLevel::AlwaysOnTop), "and takes its palette level back: {:?}", levels(&h)); + assert_eq!(hidden(&h), [false, true], "shown again with the dialog gone: {:?}", hidden(&h)); +} + #[test] fn a_file_dropped_on_a_native_window_opens() { let mut h = Harness::new(); @@ -528,6 +628,7 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { }, ]); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); h.host.borrow_mut().child_transparent_overlay = Some((viewport, field.expand(10.0))); @@ -560,6 +661,7 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { }, ]); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); } @@ -658,6 +760,380 @@ fn wheel_stays_under_an_empty_interactive_overlay() { assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); } +#[test] +fn a_raised_overlay_blocks_the_next_font_wheel_event() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + let overlay_layer = egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay")); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.frame(vec![]); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).unwrap_or_else(|| panic!("overlay absent from {order:?}")); + assert!(field_index > overlay_index, "the font field must start above the overlay: {order:?}"); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerGone, + ]); + h.frame(vec![]); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).unwrap_or_else(|| panic!("overlay absent from {order:?}")); + assert!(overlay_index > field_index, "the overlay must finish above the font field: {order:?}"); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + h.frame(vec![]); + h.frame(vec![]); + assert!( + h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "the raised overlay must receive the wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + assert_eq!(h.ctx.input_for(viewport, |input| input.pointer.latest_pos()), None); +} + +#[test] +fn an_overlay_raised_with_the_wheel_event_does_not_change_the_font() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let overlay_layer = egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay")); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).expect("overlay in layer order"); + assert!(field_index > overlay_index, "the font field must be above the overlay before the wheel event: {order:?}"); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + h.frame(vec![]); + h.frame(vec![]); + assert!( + h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "the raised overlay must receive the wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_closed_overlay_does_not_replay_its_wheel_into_the_panel() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.host.borrow_mut().child_raise_overlay = None; + h.frame(vec![]); + h.frame(vec![]); + assert!( + !h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "a closed overlay cannot receive a later wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_wheel_before_opening_a_floating_font_menu_changes_the_font() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ]); + h.frames(3); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_delayed_wheel_does_not_change_a_font_field_that_moved() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + crate::font_menu::offset_wheel_fields_for_test(&h.ctx, viewport, vec2(300.0, 0.0)); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn wheel_events_on_both_sides_of_an_overlay_are_checked_separately() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let covered = pos2(field.min.x + 4.0, field.center().y); + let clear = pos2(field.max.x - 4.0, field.center().y); + let overlay = Rect::from_min_max(field.min - vec2(2.0, 2.0), pos2(field.center().x, field.max.y + 2.0)); + assert!(covered.x < overlay.max.x && clear.x > overlay.max.x); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, clear).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(covered), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + h.frame(vec![]); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); + assert_eq!(h.ctx.input_for(viewport, |input| input.pointer.latest_pos()), Some(clear)); +} + +#[test] +fn leaving_a_floating_font_field_resets_queued_fractional_wheel_input() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let inside = pos2(field.min.x + 4.0, field.center().y); + let outside = pos2(field.max.x + 500.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(inside), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(outside), + ]); + h.frame(vec![]); + h.frame(vec![]); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(inside), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_floating_wheel_turn_precedes_a_pointer_leave_in_the_menu_order() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + h.app.ui.recent_fonts = ["Source Sans 3", "Source Serif 4", "Inter"].map(str::to_string).into(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let inside = pos2(field.min.x + 4.0, field.center().y); + let outside = pos2(field.max.x + 500.0, field.center().y); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([Event::PointerMoved(inside), wheel.clone()]); + h.frame(vec![]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap()[0]["family"], "Source Serif 4"); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([wheel, Event::PointerMoved(outside)]); + h.frame(vec![]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap()[0]["family"], "Inter"); +} + +#[test] +fn moving_under_an_overlay_resets_queued_fractional_font_wheel_input() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let covered = pos2(field.min.x + 4.0, field.center().y); + let clear = pos2(field.max.x - 4.0, field.center().y); + let overlay = Rect::from_min_max(field.min - vec2(2.0, 2.0), pos2(field.center().x, field.max.y + 2.0)); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, true)); + h.frames(2); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(covered), + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + #[test] fn wheel_without_a_move_uses_the_floating_viewports_pointer() { let mut h = Harness::new(); @@ -684,5 +1160,6 @@ fn wheel_without_a_move_uses_the_floating_viewports_pointer() { source: egui::MouseWheelSource::Unknown, }); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); } diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index f8287944be..60b59a2a8e 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -161,6 +161,52 @@ fn a_tab_dragged_out_floats_and_comes_back_where_it_was_after_its_window_closes( assert!(h.tab("layers").is_some()); } +#[test] +fn thumbnail_work_is_needed_only_while_layers_or_links_can_be_seen() { + let mut h = Harness::new(); + h.app.run("window.panel", json!({"panel": "layers"})).unwrap(); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx)); + h.app.ui.dock = false; + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "Tab hides every panel"); + h.app.ui.dock = true; + h.app.ui.screen_mode = 3; + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "presentation mode hides panels"); + h.app.ui.screen_mode = 0; + h.app.run("window.panel.float", json!({"panel": "layers"})).unwrap(); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "a floating Layers panel still needs thumbnails"); + h.app.run("window.panel", json!({"panel": "layers", "toggle": true})).unwrap(); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx)); + h.app.run("window.panel", json!({"panel": "links"})).unwrap(); + h.frame(vec![]); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "the Links flyout also uses row thumbnails"); +} + +#[test] +fn a_collapsed_dock_uses_the_flyouts_active_tab_for_thumbnail_work() { + let mut h = Harness::new(); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + // A customized layout keeps the group's active tab independent of the icon that opened it. + h.app.ui.docking = Some(layout_of(&h.app.ui)); + h.app.run("window.panel", json!({"panel": "properties"})).unwrap(); + h.frame(vec![]); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "Properties does not use row thumbnails"); + // A tab press emits Activate without revealing a different flyout anchor. + gesture(&mut h.app, Action::Activate { panel: "layers".into() }).unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout is still named for its opening icon"); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "the active Layers tab keeps thumbnail jobs"); + gesture(&mut h.app, Action::Activate { panel: "properties".into() }).unwrap(); + h.frame(vec![]); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "returning to Properties drops hidden Layers jobs"); + h.app.run("window.panel", json!({"panel": "layers"})).unwrap(); + h.frame(vec![]); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx)); + gesture(&mut h.app, Action::Activate { panel: "properties".into() }).unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("layers")); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "a Properties tab under the Layers icon does not need thumbnails"); +} + /// A Character field shortcut with the Character panel in front of its floating window brings /// that window forward and leaves the panel showing. #[test] diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 3c9138f8d8..afddf276f5 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -2291,6 +2291,29 @@ mod tests { assert_eq!(set_names(&app), before, "no set added"); } + /// Where the host can read part of a file, Load Actions… reads one byte past 8 MiB: a larger + /// file is refused without reading all of it, and a smaller one loads. + #[test] + fn load_actions_reads_a_file_no_further_than_one_byte_past_its_limit() { + let mut app = app_with_sets(); + let files = with_files(&mut app, "/sets/big.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/small.vcactions"})).unwrap(); + files.borrow_mut().insert("/sets/big.vcactions".into(), vec![b' '; files::MAX_SET_FILE + 100]); + app.services.read = Some(Box::new(|_: &str| Err("the whole file was read".to_string()))); + let asked = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let (f, a) = (files.clone(), asked.clone()); + app.services.read_head = Some(Box::new(move |path: &str, max: usize| { + a.borrow_mut().push(max); + let bytes = f.borrow().get(path).cloned().ok_or_else(|| "no such file".to_string())?; + Ok(bytes.into_iter().take(max).collect()) + })); + let before = set_names(&app); + assert_eq!(app.run(LOAD_SET, json!({"path": "/sets/big.vcactions"})).unwrap_err(), "the action set file is larger than 8 MiB"); + assert_eq!(set_names(&app), before, "no set added"); + assert_eq!(app.run(LOAD_SET, json!({"path": "/sets/small.vcactions"})).unwrap()["name"], json!("Mine 2")); + assert_eq!(*asked.borrow(), [files::MAX_SET_FILE + 1; 2], "each read stops one byte past the limit"); + } + /// Save Actions… does not write a set that Load Actions… would refuse: more than 1,000 actions. #[test] fn save_actions_does_not_write_a_set_load_actions_refuses() { diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index ef00fccceb..ead40505fa 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -181,7 +181,8 @@ pub(crate) fn can_load(app: &VectorcraftApp) -> bool { /// the file's text `data`, and adds its set after the others, with its actions. A set with the /// same name as one in the panel gets the next free number (`Print 2`). Loaded actions keep their /// function keys. The current set and the other sets stay as they are → -/// `{set: index, name, actions: n}`. +/// `{set: index, name, actions: n}`. Where the host can read part of a file (the desktop), a file +/// larger than 8 MiB is refused after its first 8 MiB and one byte are read. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { Some(Value::String(data)) => { @@ -200,7 +201,12 @@ pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { crate::picks::open(app, &pick).ok_or("cancelled")? } }; - let bytes = app.services.read.as_ref().ok_or("no file reader")?(&path)?; + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, + (None, Some(read)) => read(&path)?, + (None, None) => return Err("no file reader".into()), + }; if bytes.len() > MAX_SET_FILE { return Err("the action set file is larger than 8 MiB".into()); } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index f687b0f2c9..a27dfa3ec2 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -13,7 +13,8 @@ //! (dropped on its row) or onto the object; Alt copies instead. Dropped on Duplicate Selected Item //! or Delete Selected Item, a fill/stroke row (with the other selected rows, when it is one of //! them) or an effect row is copied or removed. Cmd-click and Shift-click select several -//! fills/strokes for Duplicate and Delete. +//! fills/strokes for Duplicate and Delete. Delete on a selected Opacity row sets it back to +//! Default (100%, Normal). use std::sync::OnceLock; @@ -59,11 +60,16 @@ impl Sel { Sel::None | Sel::Effect(_) | Sel::Contents | Sel::Opacity => None, } } - /// Is a fill/stroke or effect row selected (what Duplicate and Delete act on)? An Opacity row - /// is not an item: it can't be copied or removed. + /// Is a fill/stroke or effect row selected (what Duplicate acts on)? An Opacity row is not an + /// item: it can't be copied. fn editable(self) -> bool { matches!(self, Sel::Item(_) | Sel::Effect(_) | Sel::ItemEffect(..)) } + /// Does Delete act on the selected row? A fill/stroke or effect row is removed; deleting an + /// Opacity row sets it back to Default (100%, Normal) (#5742). + fn deletable(self) -> bool { + self.editable() || matches!(self, Sel::Opacity | Sel::ItemOpacity(_)) + } } /// The selected row of `node` (the first selected object): a selected effect row while that @@ -490,7 +496,7 @@ fn delete_key(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); let sel = current_sel(app, &ctx, node.as_ref()); if keys - && sel.editable() + && sel.deletable() && ctx.memory(|m| m.focused().is_none()) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { @@ -1088,7 +1094,8 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, opaci let link = name_link(ui, pos2(lx, r.center().y), ("ap-op-link", item), tl!("Opacity:")).clicked(); if link || resp.clicked() { select_row(app, ui.ctx(), this); - // The panel has the keyboard (Delete then removes nothing, rather than the object). + // The panel has the keyboard (Delete then sets the row back to Default, rather than + // deleting the object). super::set_row_keys(ui.ctx(), ROW_KEYS, true); } if link { @@ -1415,7 +1422,8 @@ fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, node: Option<&Node>, sel: Sel) if duplicate.clicked() { duplicate_selected(app, ui, node, sel); } - let delete = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Selected Item"), false, can, 24.0); + let can_delete = can || (has && sel.deletable()); + let delete = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Selected Item"), false, can_delete, 24.0); if delete.clicked() { delete_selected(app, ui, node, sel); } @@ -1558,8 +1566,20 @@ fn highlight_copies(app: &mut VectorcraftApp, ctx: &egui::Context, n: &Node, sel set_pstate(ctx, "ap-multi", Highlight { owner: Some(n.id), rows, order, anchor, active }); } -/// Remove the highlighted fills/strokes or effects; a removed item effect leaves its fill/stroke selected. +/// Remove the highlighted fills/strokes or effects; a removed item effect leaves its fill/stroke +/// selected. A selected Opacity row is set back to Default (100%, Normal) and stays selected. fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: Sel) { + match sel { + Sel::Opacity => { + app.run("transparency.set", json!({"item": null, "opacity": 100, "blend": "Normal"})).ok(); + return; + } + Sel::ItemOpacity(i) => { + app.run("transparency.set", aligned(app, json!({"item": i, "opacity": 100, "blend": "Normal"}))).ok(); + return; + } + _ => {} + } let ok = match selected_effects(ui.ctx(), node, sel) { Some((item, ks)) => app.run("effect.remove", aligned(app, json!({"item": item, "indices": ks}))).is_ok(), None if matches!(sel, Sel::Item(_)) => { @@ -1616,7 +1636,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Duplicate Item"), has && sel.editable(), false) { duplicate_selected(app, ui, node.as_ref(), sel); } - if menu_item(ui, tl!("Remove Item"), has && sel.editable(), false) { + if menu_item(ui, tl!("Remove Item"), has && sel.deletable(), false) { delete_selected(app, ui, node.as_ref(), sel); } if menu_item(ui, tl!("Clear Appearance"), has, false) { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 7d9cdd3293..82042a9a38 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -85,6 +85,47 @@ fn removing_items_keeps_a_surviving_item_opacity_row_selected() { assert_eq!(app.session.appearance_item(), None); } +/// #5742: Delete Selected Item on an Opacity row sets it back to Default (100%, Normal): the +/// object's own, or a fill's, leaving the other untouched. Duplicate stays off for it. +#[test] +fn deleting_an_opacity_row_sets_it_back_to_default() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + app.run("transparency.set", json!({"item": null, "opacity": 50, "blend": "Multiply"})).unwrap(); + app.run("transparency.set", json!({"item": 0, "opacity": 40, "blend": "Screen"})).unwrap(); + let owner = Some(NodeId(id)); + let ctx = egui::Context::default(); + let delete = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let node = first_subject(app); + let sel = current_sel(app, ui.ctx(), node.as_ref()); + assert!(sel.deletable() && !sel.editable(), "{sel:?}"); + delete_selected(app, ui, node.as_ref(), sel); + }); + out.textures_delta.clear(); + }; + let node = |app: &VectorcraftApp| first_subject(app).unwrap(); + // The fill's Opacity row: only the fill goes back to Default. + app.run("appearance.setActiveItem", json!({ "index": 0 })).unwrap(); + set_pstate(&ctx, "ap-sel", (owner, Sel::ItemOpacity(0))); + delete(&mut app); + let n = node(&app); + assert_eq!((n.appearance.items[0].opacity(), n.appearance.items[0].blend()), (1.0, BlendMode::Normal)); + assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply)); + assert_eq!(pstate::<(Option, Sel)>(&ctx, "ap-sel").1, Sel::ItemOpacity(0)); + // The object's Opacity row. + app.run("appearance.setActiveItem", json!({ "index": null })).unwrap(); + set_pstate(&ctx, "ap-sel", (owner, Sel::Opacity)); + delete(&mut app); + let n = node(&app); + assert_eq!(opacity_text(n.opacity, n.blend), "Default"); + // One step, so Undo brings the object's opacity back. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app).opacity, 0.5); +} + #[test] fn opacity_labels() { assert_eq!(opacity_text(1.0, BlendMode::Normal), "Default"); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 495ce2f119..7e68824c19 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -651,7 +651,7 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti Some(Ok(Value::Null)) } -enum TextInput { +pub(crate) enum TextInput { Key(ToolKey, Mods), Copy, Cut, @@ -659,83 +659,87 @@ enum TextInput { Face(Face), } -/// Route editing keys (with modifiers), clipboard events and Cmd+C/X/V to the Type tool (Cmd+A is -/// left to the Select All shortcut, which selects the text being edited). -pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) { +/// Takes an editing key (with modifiers), a clipboard event or Cmd+C/X/V for the Type tool into +/// `todo` (Cmd+A is left to the Select All shortcut, which selects the text being edited). Returns +/// false for an event the tool takes, which is then removed from the input. +pub(crate) fn type_input(e: &egui::Event, todo: &mut Vec) -> bool { + match e { + egui::Event::Copy => { + todo.push(TextInput::Copy); + false + } + egui::Event::Cut => { + todo.push(TextInput::Cut); + false + } + egui::Event::Paste(s) => { + todo.push(TextInput::Paste(Some(s.clone()))); + false + } + egui::Event::Key { key, pressed, modifiers: m, .. } => { + let mods = Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl && !m.command, space: false }; + let tk = match key { + Key::ArrowLeft => Some(ToolKey::Left), + Key::ArrowRight => Some(ToolKey::Right), + Key::ArrowUp => Some(ToolKey::Up), + Key::ArrowDown => Some(ToolKey::Down), + Key::Home => Some(ToolKey::Home), + Key::End => Some(ToolKey::End), + Key::Backspace => Some(ToolKey::Backspace), + Key::Delete => Some(ToolKey::Delete), + Key::Tab if !m.command => Some(ToolKey::Tab), + _ => None, + }; + if let Some(tk) = tk { + if *pressed { + todo.push(TextInput::Key(tk, mods)); + } + return false; + } + // Type › Bold and Italic, as page layout apps have them while text is edited. + if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) { + if *pressed { + todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic })); + } + return false; + } + if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) { + if *pressed { + todo.push(match key { + Key::C => TextInput::Copy, + Key::X => TextInput::Cut, + _ => TextInput::Paste(None), + }); + } + return false; + } + true + } + _ => true, + } +} + +/// Keeps `ctx` for the Type tool's clipboard, which Edit › Copy and Cut also write to. +pub(crate) fn keep_ctx(ctx: &egui::Context) { CTX.get_or_init(|| ctx.clone()); - let mut todo = vec![]; - ctx.input_mut(|i| { - i.events.retain(|e| match e { - egui::Event::Copy => { - todo.push(TextInput::Copy); - false +} + +/// Applies an editing key or clipboard event taken by [`type_input`] to the Type tool. +pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) { + match t { + TextInput::Key(k, m) => text_key(app, k, m), + TextInput::Copy => { + text_copy(app); + } + TextInput::Cut => { + if text_copy(app) { + text_key(app, ToolKey::Delete, Mods::default()); } - egui::Event::Cut => { - todo.push(TextInput::Cut); - false - } - egui::Event::Paste(s) => { - todo.push(TextInput::Paste(Some(s.clone()))); - false - } - egui::Event::Key { key, pressed, modifiers: m, .. } => { - let mods = Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl && !m.command, space: false }; - let tk = match key { - Key::ArrowLeft => Some(ToolKey::Left), - Key::ArrowRight => Some(ToolKey::Right), - Key::ArrowUp => Some(ToolKey::Up), - Key::ArrowDown => Some(ToolKey::Down), - Key::Home => Some(ToolKey::Home), - Key::End => Some(ToolKey::End), - Key::Backspace => Some(ToolKey::Backspace), - Key::Delete => Some(ToolKey::Delete), - Key::Tab if !m.command => Some(ToolKey::Tab), - _ => None, - }; - if let Some(tk) = tk { - if *pressed { - todo.push(TextInput::Key(tk, mods)); - } - return false; - } - // Type › Bold and Italic, as page layout apps have them while text is edited. - if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) { - if *pressed { - todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic })); - } - return false; - } - if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) { - if *pressed { - todo.push(match key { - Key::C => TextInput::Copy, - Key::X => TextInput::Cut, - _ => TextInput::Paste(None), - }); - } - return false; - } - true - } - _ => true, - }) - }); - for t in todo { - match t { - TextInput::Key(k, m) => text_key(app, k, m), - TextInput::Copy => { - text_copy(app); - } - TextInput::Cut => { - if text_copy(app) { - text_key(app, ToolKey::Delete, Mods::default()); - } - } - TextInput::Paste(s) => text_paste(app, s, false), - TextInput::Face(f) => { - if let Err(e) = toggle_face(app, f) { - app.status(e); - } + } + TextInput::Paste(s) => text_paste(app, s, false), + TextInput::Face(f) => { + if let Err(e) = toggle_face(app, f) { + app.status(e); } } } @@ -994,6 +998,9 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { /// The panel state key of the panel menu's Show Snap to Glyph Options. const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options"; +/// Set when Show Snap to Glyph Options is chosen: the next frame scrolls the panel to the options, +/// which come after every character attribute (#5273). +const SNAP_TO_GLYPH_REVEAL: &str = "ch-snap-to-glyph-reveal"; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { show_owned(app, ui, crate::font_menu::WheelOwner::Character); @@ -1007,13 +1014,18 @@ fn show_owned(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::Wh } } -/// The Snap to Glyph options (Show Snap to Glyph Options): which guides View › Snap to Glyph gives, -/// each a checkbox running `view.snapToGlyph.options`. Dimmed while Snap to Glyph is off. +/// The Snap to Glyph options (Show Snap to Glyph Options): View › Snap to Glyph itself, then which +/// guides it gives, each a checkbox running `view.snapToGlyph.options` (dimmed while Snap to Glyph +/// is off). Shown from the panel menu, the panel scrolls to them (#5273). fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); ui.separator(); - widgets::section_header(ui, "Snap to Glyph"); + let top = ui.cursor().min; let (o, enabled) = (app.session.prefs.glyph_snap, app.ui.view.snap_to_glyph); + // A UI command that takes no params: it can't refuse. + if widgets::check(ui, "Snap to Glyph", enabled, true) { + app.run("view.snapToGlyph", json!({})).ok(); + } egui::Grid::new("ch-snap-to-glyph").num_columns(2).show(ui, |ui| { for (i, (label, key, on)) in [ ("Baseline", "baseline", o.baseline), @@ -1035,6 +1047,10 @@ fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { } } }); + if pstate::(ui.ctx(), SNAP_TO_GLYPH_REVEAL) { + set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, false); + ui.scroll_to_rect(egui::Rect::from_min_max(top, ui.min_rect().max), Some(egui::Align::BOTTOM)); + } } /// The character attributes of the type selected (an empty state without any). @@ -1222,6 +1238,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let glyph = pstate::(ui.ctx(), SNAP_TO_GLYPH_OPTIONS); if menu_item(ui, if glyph { tl!("Hide Snap to Glyph Options") } else { tl!("Show Snap to Glyph Options") }, true, false) { set_pstate(ui.ctx(), SNAP_TO_GLYPH_OPTIONS, !glyph); + set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, !glyph); } // Show Font Height Options shows the Set Font Height Reference dropdown under Font Size. let heights: bool = pstate(ui.ctx(), FONT_HEIGHT_OPTIONS); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 4a4264fe70..2a35193852 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1207,6 +1207,43 @@ fn snap_to_glyph_options_show_from_the_menu_and_set_the_options() { assert!(!section(&mut app).iter().any(|(t, _)| t == "Proximity Guides")); } +/// #5273: the Snap to Glyph options come after every character attribute, so showing them from the +/// panel menu scrolls a short panel down to them; their first checkbox turns View › Snap to Glyph +/// on and off, which undims the others. +#[test] +fn snap_to_glyph_options_scroll_into_view_and_turn_snapping_on() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Glyphs"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + const VIEW: f32 = 160.0; + // The panel as a short dock shows it: in a scroll area. + let panel = |app: &mut VectorcraftApp, ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(VIEW).show(ui, |ui| show(app, ui)); + }; + let texts = frame_events(&ctx, &mut app, vec![], menu); + let item = texts.iter().find(|(t, _)| t.trim() == "Show Snap to Glyph Options").unwrap().1; + click(&ctx, &mut app, item.center(), menu); + // The scroll is animated: it lands over the next second. + let mut texts = vec![]; + for i in 0..30 { + let raw = egui::RawInput { time: Some(10.0 + f64::from(i) * 0.1), ..Default::default() }; + texts = super::super::tests_appearance::frame_raw(&ctx, &mut app, raw, panel); + } + for label in ["Snap to Glyph", "Anchor Point"] { + let r = text_rect(&texts, label); + assert!(r.top() >= 0.0 && r.bottom() <= VIEW + 1.0, "{label} at {r:?} is outside the panel"); + } + assert!(!app.ui.view.snap_to_glyph); + click(&ctx, &mut app, text_rect(&texts, "Snap to Glyph").center(), panel); + assert!(app.ui.view.snap_to_glyph, "the first checkbox turns Snap to Glyph on"); + let texts = frame_events(&ctx, &mut app, vec![], panel); + click(&ctx, &mut app, text_rect(&texts, "Anchor Point").center(), panel); + assert!(!app.session.prefs.glyph_snap.anchors, "the options take clicks once it is on"); +} + /// After Select All in a frame of threaded text, the Character and Paragraph panels and Copy act on /// the text of every frame of the story. #[test] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 2a737d2fb8..98c082fc79 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -69,7 +69,7 @@ use model::{push_rows, rows_of_doc}; use rows::{drag_ghost, key, rename_id, resolve_click, row}; #[cfg(test)] use thumbs::THUMBS; -pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, show_thumbs_of, thumb_options}; +pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, retain_open_thumbs, show_thumbs_of, thumb_options}; /// Width of the eye and the lock columns. const COLUMN: f32 = 25.0; diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index f7abe7aa3e..000a3c07eb 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -16,6 +16,25 @@ pub(super) fn rename_id() -> egui::Id { egui::Id::unique("layers-rename") } +/// Whether a row's name is italic: a layer whose Layer Options › Print is off does not print, and +/// the panel shows that in its name, as the reference application does (a template layer's Print is +/// off too). +fn prints_italic(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { printable: false, .. }) +} + +/// Paints the row name `name` at `pos` (left, vertically centred), italic when `italic`, and +/// returns its rect. Row names are painted rather than widgets, so italics come from a layout job's +/// text format: egui slants the glyphs itself, no italic face is needed. +fn paint_name(painter: &egui::Painter, pos: egui::Pos2, name: &str, font: egui::FontId, color: Color32, italic: bool) -> egui::Rect { + let mut job = egui::text::LayoutJob::default(); + job.append(name, 0.0, egui::TextFormat { font_id: font, color, italics: italic, ..Default::default() }); + let galley = painter.layout_job(job); + let rect = egui::Align2::LEFT_CENTER.anchor_size(pos, galley.size()); + painter.galley(rect.min, galley, color); + rect +} + /// The colour of the layer holding `id`. fn layer_colour(doc: &Document, id: NodeId) -> Color32 { let [r, g, b] = doc.layer_color(id); @@ -57,7 +76,7 @@ pub(super) fn drag_ghost(ui: &Ui, view: &View, src: NodeId, pos: egui::Pos2) { } let label = n.identify_label(view.identify_xml_id); let name = if view.identify_xml_id { label } else { painted_name(n, &label, crate::i18n::current()) }; - ui.painter().text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(13.0), t.text); + paint_name(ui.painter(), egui::pos2(x, r.center().y), &name, egui::FontId::proportional(13.0), t.text, prints_italic(n)); }); } @@ -316,7 +335,7 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { } else { painted_name(n, &n.display_name(), crate::i18n::current()) }; - let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if item.dim { t.text_dim } else { t.text }); + let text = paint_name(&painter, egui::pos2(x, r.center().y), &shown, font, if item.dim { t.text_dim } else { t.text }, prints_italic(n)); name_end = text.right(); // A clipping path's name is underlined, a masked object's with a dashed line. if clip_path { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 6f65e5d8c7..f138b6cbf2 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -211,6 +211,67 @@ fn two_rects() -> (VectorcraftApp, NodeId, [NodeId; 2]) { (app, layer, [NodeId(a), NodeId(b)]) } +/// The painted names one headless frame of the panel draws italic. +fn italic_names(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + fn collect(shape: &egui::Shape, names: &mut Vec) { + match shape { + egui::Shape::Text(t) => { + if t.galley.job.sections.iter().any(|s| s.format.italics) { + names.push(t.galley.text().to_string()); + } + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, names)), + _ => {} + } + } + let mut names = Vec::new(); + out.shapes.iter().for_each(|c| collect(&c.shape, &mut names)); + names +} + +/// A layer whose Layer Options › Print is off has its name italic in the panel (#5739), as the +/// reference application shows it; a printing layer's name stays upright, and unticking Print again +/// makes it upright. +#[test] +fn a_layer_that_does_not_print_has_its_name_italic() { + let (mut app, layer, _) = two_rects(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "a printing layer's name is upright"); + app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": false})).unwrap(); + assert!(italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print off: its name is italic"); + app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": true})).unwrap(); + assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print on again: upright again"); +} + +#[test] +fn closing_a_document_releases_only_its_layer_thumbnails() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let first = app.session.active().unwrap().uid; + frame(&mut app, &ctx, vec![], false); + assert!(THUMBS.with(|c| c.borrow().cached(first))); + + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let second = app.session.active().unwrap().uid; + frame(&mut app, &ctx, vec![], false); + assert!(THUMBS.with(|c| c.borrow().cached(second))); + + // Close the first document the way File › Close does (Don't Save), with no panel drawn after. + assert_eq!(app.run("file.close", json!({"index": 0})).unwrap(), json!({"pending": crate::unsaved::KIND})); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != first), "the first document closed"); + THUMBS.with(|c| { + let thumbs = c.borrow(); + assert!(!thumbs.cached(first), "closed document textures are released"); + assert!(thumbs.cached(second), "open document textures stay cached"); + }); +} + #[test] fn row_thumbnails_wait_for_the_end_of_a_drag() { let (mut app, _, _) = two_rects(); diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index 78e1217c2d..49ce4b61b9 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use vectorcraft_doc::{NodeKind, TextKind}; use vectorcraft_geom::PathData; @@ -51,6 +52,8 @@ type ThumbJob = ((u64, NodeId), Weak, u32); #[derive(Default)] pub(super) struct Thumbs { entries: HashMap<(u64, NodeId), ThumbEntry>, + /// Documents still open. None until the app first synchronizes its documents. + open_docs: Option>, /// What the worker is rendering, by row. pending: HashMap<(u64, NodeId), (Weak, u32)>, worker: Option>, @@ -249,6 +252,50 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, } impl Thumbs { + #[cfg(test)] + pub(super) fn cached(&self, uid: u64) -> bool { + self.entries.keys().any(|key| key.0 == uid) + } + + /// Release thumbnails and queued jobs for documents that have closed, keeping the cache for + /// other open documents even when the panels are hidden or another document is active. When a + /// document closes, the worker drops its jobs, the one running included, and the images it + /// finished that the panels have not collected yet. + fn retain_open(&mut self, uids: &[u64]) { + if self.open_docs.as_ref().is_some_and(|open| open.len() == uids.len() && uids.iter().all(|uid| open.contains(uid))) { + return; + } + let open: HashSet = uids.iter().copied().collect(); + let closed = self.open_docs.as_ref().is_some_and(|before| before.iter().any(|uid| !open.contains(uid))); + let stale = + self.entries.keys().chain(self.pending.keys()).any(|key| !open.contains(&key.0)) || self.showing.is_some_and(|uid| !open.contains(&uid)); + self.entries.retain(|key, _| open.contains(&key.0)); + self.pending.retain(|key, _| open.contains(&key.0)); + self.showing = self.showing.filter(|uid| open.contains(uid)); + if closed { + // Images finished before now are dropped with the rest of the queue: the open + // documents' rows are asked for again. + if let Some(w) = &self.worker { + let open = open.clone(); + w.forget(move |key| !open.contains(&key.0)); + if w.poll().is_none() { + self.worker = None; + } + } + self.pending.clear(); + } else if stale + && let Some(w) = &self.worker + && !w.discard({ + let open = open.clone(); + move |key| !open.contains(&key.0) + }) + { + self.worker = None; + self.pending.clear(); + } + self.open_docs = Some(open); + } + /// Keep `img` (None: nothing drawn) as the thumbnail of row `key` showing `node`. fn upload(&mut self, ctx: &egui::Context, key: (u64, NodeId), node: Weak, px: u32, img: Option<&vectorcraft_render::Rendered>, ms: f64) { let color = img.map(crate::canvas::color_image); @@ -280,7 +327,7 @@ impl Thumbs { /// The panels draw the rows of document `uid` (None: no document). When that is another /// document than before, the worker drops the jobs it has not started for every other /// document, so they don't hold up this one's thumbnails, and those rows are asked for again - /// when their document shows again. The thumbnails made already stay. + /// when their document shows again. The thumbnails of still-open documents stay. pub(super) fn show(&mut self, uid: Option) { if self.showing == uid { return; @@ -298,6 +345,9 @@ impl Thumbs { /// Keep the thumbnail `d` the worker finished. fn receive(&mut self, ctx: &egui::Context, d: Done) { let (key, node, px) = d.key; + if self.open_docs.as_ref().is_some_and(|open| !open.contains(&key.0)) { + return; + } if self.pending.get(&key).is_some_and(|(p, ppx)| p.ptr_eq(&node) && *ppx == px) { self.pending.remove(&key); } @@ -383,6 +433,11 @@ pub(crate) fn show_thumbs_of(uid: Option) { THUMBS.with(|c| c.borrow_mut().show(uid)); } +/// Forget thumbnails of documents no longer open, even if neither thumbnail panel is shown. +pub(crate) fn retain_open_thumbs(uids: &[u64]) { + THUMBS.with(|c| c.borrow_mut().retain_open(uids)); +} + /// A real rendered thumbnail of row `n`, cached by node identity (unchanged nodes keep their `Arc` /// allocation, so the address is a free change detector). Only rendered for visible rows; see /// [`Thumbs::texture`] for when. @@ -440,6 +495,47 @@ mod tests { use super::*; + #[test] + fn a_finished_job_cannot_restore_a_closed_documents_thumbnail() { + let mut thumbs = Thumbs::default(); + let ctx = egui::Context::default(); + thumbs.retain_open(&[2]); + thumbs.receive(&ctx, Done { key: ((1, NodeId(1)), Weak::new(), 16), img: None, ms: 0.0 }); + assert!(thumbs.entries.is_empty(), "a closed document's late result is discarded"); + thumbs.receive(&ctx, Done { key: ((2, NodeId(2)), Weak::new(), 16), img: None, ms: 0.0 }); + assert!(thumbs.entries.contains_key(&(2, NodeId(2))), "an open document's result is kept"); + } + + #[test] + fn closing_a_document_drops_the_image_its_running_job_finishes_while_the_panels_are_hidden() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + thumbs.retain_open(&[1, 2]); + // A job of document 1 is running, so discarding the queue cannot drop it. + let (started, running) = std::sync::mpsc::channel::<()>(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let key = (1, NodeId(1)); + let job: crate::thumb_worker::JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job))); + running.recv().expect("the job starts"); + // Another row of document 1 waits behind it. + let queued = (1, NodeId(3)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(queued, (queued, Weak::new(), 1), Box::new(|_| None)))); + // Document 1 closes while no panel collects results, then its running job finishes. + thumbs.retain_open(&[2]); + release.send(()).ok(); + // A job of document 2 queued after them comes back first: document 1's images were dropped. + let next = (2, NodeId(2)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(next, (next, Weak::new(), 1), Box::new(|_| None)))); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the same worker finishes document 2's job"); + assert_eq!(done.key.0, next, "no worker keeps the closed document's image"); + } + /// An open zigzag of `anchors` anchors. fn line(anchors: usize) -> PathData { let pts: Vec = (0..anchors).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64 * 50.0)).collect(); diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 2439ba8f27..33bcbb0479 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -130,13 +130,22 @@ fn grabbed(drag: &PanelDrag, library: &str) -> Option { } /// The kind and `library.add` params of what `drag` holds, to add to library `library`: a color -/// (not one of that library's own), or a gradient or pattern swatch, by its name. +/// (not one of that library's own; a spot colour with its swatch's name), or a gradient or pattern +/// swatch, by its name. fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { let PanelDrag::Paint { paint, params, library: from, .. } = drag else { return None }; let swatch = || params.get("swatch").and_then(Value::as_str); match paint { Paint::Solid { color, .. } if from.as_ref().is_none_or(|(l, _)| l != library) => { - Some((ItemKind::Color, json!({ "kind": "fillColor", "color": color }))) + // A spot swatch's name (and tint) come along, so the library keeps the ink. + let mut add = json!({ "kind": "fillColor", "color": color }); + if let Some(s) = swatch() { + add["swatch"] = json!(s); + if let Some(t) = params.get("tint") { + add["tint"] = t.clone(); + } + } + Some((ItemKind::Color, add)) } Paint::Gradient(_) => swatch().map(|s| (ItemKind::Gradient, json!({ "kind": "fillGradient", "swatch": s }))), Paint::Pattern { .. } => swatch().map(|s| (ItemKind::Pattern, json!({ "kind": "fillPattern", "swatch": s }))), diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 64c3543498..5f7f575c8f 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -375,6 +375,29 @@ fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { assert!(matches!(fill(&app), Paint::Pattern { ref pattern, .. } if pattern == "Checks"), "{:?}", fill(&app)); } +/// A spot swatch dropped on the list (as the Swatches panel drags it, with its name) is added as +/// a spot colour of that ink, at its tint (#5812). +#[test] +fn a_spot_swatch_dropped_on_the_list_stays_spot() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + app.run("swatch.new", json!({"name": "Kiss-cut", "color": "#ff00ff", "spot": true})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::panels::set_pstate(&ctx, LIST_VIEW, true); + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let into = at(&texts, "Brand").center() + vec2(0.0, 80.0); + for tint in [1.0, 0.5] { + let paint = app.session.active().unwrap().doc.tint_paint("Kiss-cut", tint).unwrap(); + let drag = PanelDrag::Paint { params: crate::panels::paint_params(&paint), paint, rows: None, library: None }; + drop_at(&mut app, &ctx, drag, into); + } + let lib = app.session.libraries.get("Brand").unwrap(); + let inks: Vec<_> = lib.colors.iter().map(|c| (c.spot.as_deref(), c.tint)).collect(); + assert_eq!(inks, [(Some("Kiss-cut"), 1.0), (Some("Kiss-cut"), 0.5)]); +} + /// New Group… and Rename Group… ask for a name and act on the library and group they came /// from; the dialog shows only the name. #[test] diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index d924d06f3f..a7fe30185f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -4,7 +4,8 @@ //! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, //! Go To, Update and Edit Original act on the selected rows; Link Info shows the details of the //! first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: -//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Show filters, Sort, thumbnail size +//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / +//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size //! and Show in Folder. //! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI @@ -534,6 +535,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { row(ui, tl!("Status"), status.into()); } +/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / +/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). @@ -597,6 +600,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "links.reveal", json!({})); } ui.separator(); + // Select Linked, Embedded, Missing and Modified: every such image in the document, not only + // the rows shown; with Shift, added to the selection. + use crate::addons::select::link_status; + for (i, (status, label, _)) in link_status::STATUSES.iter().enumerate() { + if menu_item(ui, tl!(label), app.ui.link_statuses.has.get(i).copied().unwrap_or(false), false) { + let p = json!({ "status": status }); + let p = if ui.input(|i| i.modifiers.shift) { link_status::with_shift(p) } else { p }; + crate::menus::invoke(app, link_status::COMMAND, p); + } + } + ui.separator(); for (id, label) in SHOW { if menu_item(ui, tl!(label), true, o.show == id) { set_options(ui.ctx(), |o| o.show = id); diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 66f907f92a..8cb29ef305 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -380,14 +380,66 @@ fn selected_alignment(app: &VectorcraftApp, fallback: &ParaStyle) -> Option), and +/// its alignment buttons align text as the Paragraph panel's do +/// (). The bar keeps to the three that +/// don't justify, for its room; all seven are in the Paragraph options the link opens. +const CONTROL_BAR_ALIGNMENTS: usize = 3; + +/// The spacing between the Control bar's alignment buttons, as in the Paragraph panel's row. +const CONTROL_BAR_BUTTON_SPACING: f32 = 3.0; + +/// The width of the Paragraph panel in the Control bar's popover, as the Character panel's. +const CONTROL_BAR_POPOVER_WIDTH: f32 = 260.0; + +/// The Control bar's Paragraph link, as it is drawn and measured. +fn control_bar_link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Paragraph:")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The Control bar's paragraph controls while type is selected or edited (#5372), after its +/// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, +/// and the Align left, Align center and Align right buttons, `size` points square as the bar's others. `reserve` gives the room the controls +/// after them keep, asked only when type is selected: short of room, the buttons are left out, +/// then the link too. Returns whether the link shows. +pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, size: f32, reserve: impl FnOnce(&Ui) -> f32) -> bool { + let Some((_, para)) = text_style(app) else { return false }; + let text = control_bar_link_text(ui); + let link_width = widgets::text_width(ui, text.clone()); + let room = ui.available_width() - reserve(ui); + let link_room = link_width + ui.spacing().item_spacing.x; + if room < link_room { + return false; + } + let link = ui.link(text).on_hover_text(tl!("Paragraph options")); + widgets::popover(&link, link.clicked(), |ui| { + ui.set_width(CONTROL_BAR_POPOVER_WIDTH); + show(app, ui); + }); + if room >= link_room + (size + CONTROL_BAR_BUTTON_SPACING) * CONTROL_BAR_ALIGNMENTS as f32 { + let spacing = ui.spacing().item_spacing.x; + ui.spacing_mut().item_spacing.x = CONTROL_BAR_BUTTON_SPACING; + first_alignment_buttons(app, ui, ¶, size, CONTROL_BAR_ALIGNMENTS); + ui.spacing_mut().item_spacing.x = spacing; + } + true +} + /// Type › Bullets and Numbering › Apply Bullets (`type.applyBullets {bullet?}`): the paragraphs of /// the selected type, or those the Type tool's selection touches, become a bulleted list with /// `bullet`; without it, a list keeps its bullet and other paragraphs take the dot. diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 163427da5a..0423bc0c95 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -543,3 +543,150 @@ fn reset_panel_resets_the_hyphenation_options() { assert_eq!(serde_json::to_value(¶).unwrap().get("justification"), None, "saves no justification options"); } } + +type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + +/// An English context for headless Control bar frames, with AccessKit on to find its controls. +fn control_bar_ctx() -> egui::Context { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// A document with the type `texts` (`text.create` params) makes, all of it selected. +fn control_bar_app(texts: &[Value]) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + let ids: Vec = texts.iter().map(|p| app.run("text.create", p.clone()).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + app +} + +/// The second of two headless frames of the whole Control bar, `width` wide (the first lays it out). +fn control_bar_nodes(ctx: &egui::Context, app: &mut VectorcraftApp, width: f32, events: Vec) -> Nodes { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 300.0)); + let mut nodes = Vec::new(); + for events in [events, vec![]] { + let mut out = + ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::control_bar(app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + nodes +} + +/// The control named `name` (a button's or link's label, a label's text). +fn control_bar_node(nodes: &Nodes, name: &str) -> Option { + nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone()) +} + +/// Where the control named `name` ends, if it shows. +fn control_bar_end(nodes: &Nodes, name: &str) -> Option { + control_bar_node(nodes, name).and_then(|n| n.bounds()).map(|b| b.x1) +} + +/// The Control bar's Paragraph alignment buttons. +const BAR_ALIGNMENTS: [&str; 3] = ["Align left", "Align center", "Align right"]; + +/// #5372: with type selected, the Control bar shows a Paragraph section after the Character one, as +/// the public documentation's Control panel does: a Paragraph: link that opens the Paragraph panel +/// in a popover under it, and the Align left, Align center and Align right buttons. A click aligns +/// the selected type, and the button of its alignment shows selected. The buttons show on a bar of +/// common window widths. +#[test] +fn the_control_bar_shows_the_paragraph_alignment_of_the_selected_type() { + let ctx = control_bar_ctx(); + let mut app = control_bar_app(&[json!({"x": 20, "y": 50, "text": "Point"})]); + // Pinned, so that the room the buttons need can't creep up past common window widths. + for width in [1440.0, 1920.0] { + let nodes = control_bar_nodes(&ctx, &mut app, width, vec![]); + let ends = BAR_ALIGNMENTS.map(|n| control_bar_end(&nodes, n)); + assert!(ends.iter().all(|e| e.is_some_and(|x| x <= f64::from(width) - 10.0)), "pinned: the buttons show on a {width} pt window: {ends:?}"); + } + let width = 1920.0; + let nodes = control_bar_nodes(&ctx, &mut app, width, vec![]); + let center = |n: &egui::accesskit::Node| { + let b = n.bounds().unwrap_or_else(|| panic!("{n:?}")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + control_bar_nodes(&ctx, app, width, vec![egui::Event::PointerMoved(at), press(true)]); + control_bar_nodes(&ctx, app, width, vec![press(false)]); + control_bar_nodes(&ctx, app, width, vec![]) + }; + // A selected button shows pressed. + let on = |n: &egui::accesskit::Node| n.toggled() == Some(egui::accesskit::Toggled::True); + let button = control_bar_node(&nodes, "Align center").unwrap_or_else(|| panic!("the Control bar has Align center")); + assert!(!on(&button), "left-aligned type: Align center is not selected"); + assert!(control_bar_node(&nodes, "Align left").is_some_and(|n| on(&n)), "Align left shows selected"); + let undo = app.session.active().unwrap().history.undo.len(); + let nodes = click(&mut app, center(&button)); + assert_eq!(text_style(&app).unwrap().1.justify, Justify::Center, "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(control_bar_node(&nodes, "Align center").is_some_and(|n| on(&n)), "Align center shows selected"); + assert!(!control_bar_node(&nodes, "Align left").is_some_and(|n| on(&n)), "Align left no longer selected"); + // The Paragraph: link opens the Paragraph panel in a popover: its justifications show there, + // no panel docks, and a second click closes it. + let link = control_bar_node(&nodes, "Paragraph:").unwrap_or_else(|| panic!("the Paragraph: link")); + assert_eq!(link.description(), Some("Paragraph options")); + assert!(control_bar_node(&nodes, "Justify all lines").is_none(), "closed"); + let nodes = click(&mut app, center(&link)); + assert!(control_bar_node(&nodes, "Justify all lines").is_some(), "the popover shows the Paragraph panel"); + assert_eq!(app.ui.open_panel, None, "no panel docks"); + let nodes = click(&mut app, center(&link)); + assert!(control_bar_node(&nodes, "Justify all lines").is_none(), "a second click closes it"); +} + +/// #5372: at any width the Control bar trims itself from its right end, ending inside its margin. +/// With type selected the inline X/Y/W/H fields go first, then the Distribute and Align buttons, +/// area type's vertical alignment, the Paragraph buttons and last the Paragraph: link, while the +/// Transform link keeps its room; a wider bar never leaves out what a narrower one showed. For one point +/// type object, area type (its vertical alignment) and two objects (the Distribute buttons). +#[test] +fn the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right() { + let ctx = control_bar_ctx(); + let point = |x: i32| json!({"x": x, "y": 50, "text": "Point"}); + let area = json!({"x": 20, "y": 20, "text": "Area", "area": {"width": 100, "height": 120}}); + const VERTICAL: [&str; 4] = ["Align Top", "Align Center", "Align Bottom", "Justify Vertically"]; + for (case, texts) in [("point type", vec![point(20)]), ("area type", vec![area]), ("two objects", vec![point(20), point(300)])] { + let mut app = control_bar_app(&texts); + // Each group of controls in the bar's order, by its first and last control. + let mut groups: Vec<(&str, Vec<&str>)> = vec![("link", vec!["Paragraph:"]), ("buttons", BAR_ALIGNMENTS.to_vec())]; + if case == "area type" { + groups.push(("vertical alignment", VERTICAL.to_vec())); + } + groups.push(("Align", vec!["Horizontal Align Left", "Vertical Align Bottom"])); + if case == "two objects" { + groups.push(("Distribute", vec!["Vertical Distribute Top", "Horizontal Distribute Right"])); + } + groups.push(("X/Y/W/H", vec!["X:", "H:"])); + let mut seen = vec![false; groups.len()]; + for width in (600..=2400).step_by(10) { + let nodes = control_bar_nodes(&ctx, &mut app, width as f32, vec![]); + let inside = |x: f64| x <= f64::from(width) - 10.0; + let shown: Vec = groups + .iter() + .map(|(group, names)| { + let ends: Vec> = names.iter().map(|n| control_bar_end(&nodes, n)).collect(); + assert!(ends.iter().all(Option::is_some) || ends.iter().all(Option::is_none), "{case}, {width}: {group} {ends:?}"); + if let Some(Some(end)) = ends.last() { + assert!(inside(*end), "{case}, {width}: {group} ends at {end}"); + } + ends.iter().all(Option::is_some) + }) + .collect(); + // Narrower bars are already full before the section (the Character controls). + let transform = control_bar_end(&nodes, "Transform"); + assert!(!shown[0] || transform.is_some_and(inside), "{case}, {width}: Transform ends at {transform:?}"); + for (i, ((group, _), on)) in groups.iter().zip(&shown).enumerate() { + assert!(!seen[i] || *on, "{case}, {width}: {group} left out after a narrower bar showed it"); + assert!(!*on || shown[..i].iter().all(|s| *s), "{case}, {width}: {group} shows while a group before it is left out"); + seen[i] |= on; + } + } + assert!(seen.iter().all(|s| *s), "{case}: a wide bar shows every group: {seen:?}"); + } +} diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 79632f4004..f7bcfb5ae3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -122,6 +122,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // any tool (, #4817). let blend_options = n_sel == 1 && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Blend { .. })); let merge_live_paint = n_sel > 1 && can_merge_live_paint(app); + // Repeat Options for one selected repeat (radial, grid or mirror), or one object of its source + // art in isolation mode: Object › Repeat › Options, the dialog of the repeat options pages + // (, + // #5181). + let repeat_options = n_sel == 1 && crate::menus::enabled(app, "object.repeat.options"); let mut actions: Vec<(&str, &str)> = vec![]; if n_sel > 1 { actions.push((tl!("Group"), "object.group")); @@ -133,6 +138,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if blend_options { actions.push((tl!("Blend Options"), "ui.blendOptions")); } + if repeat_options { + actions.push((tl!("Repeat Options"), "object.repeat.options")); + } if is_group { actions.push((tl!("Ungroup"), "object.ungroup")); actions.push((tl!("Isolate Group"), "object.isolate")); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 7c5e69e119..70d80ffa2b 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1339,6 +1339,34 @@ fn blend_options_is_a_quick_action_for_one_blend() { assert!(!shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "a rectangle"); } +/// One selected repeat, radial, grid or mirror, has Repeat Options in Quick Actions (#5181), which +/// opens the Repeat Options dialog with its values; a plain rectangle, or a repeat selected with +/// another object, does not. +#[test] +fn repeat_options_is_a_quick_action_for_one_repeat() { + let ctx = egui::Context::default(); + for (cmd, field) in [("object.repeat.radial", "instances"), ("object.repeat.grid", "rows"), ("object.repeat.mirror", "angle")] { + let mut app = new_app(); + let a = rect(&mut app, 20.0, 20.0, 40.0, 40.0); + let repeat = app.run(cmd, json!({"ids": [a]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [repeat]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(shows(&texts, "Repeat Options"), "{cmd}"); + let depth = undo_depth(&app); + press(&mut app, &ctx, text_at(&texts, "Repeat Options").center()); + let d = app.ui.dialog.as_ref().expect("the Repeat Options dialog opens"); + assert_eq!(d.kind, "command", "{cmd}"); + assert!(d.fields.contains_key(field), "{cmd}: the dialog has the repeat's {field}"); + assert_eq!(undo_depth(&app), depth, "opening the dialog changes nothing"); + app.ui.dialog = None; + let c = rect(&mut app, 20.0, 200.0, 40.0, 40.0); + app.run("select.set", json!({"ids": [repeat, c]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Repeat Options"), "{cmd}: a repeat and another object"); + app.run("select.set", json!({"ids": [c]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Repeat Options"), "a rectangle"); + } +} + /// Quick Actions offer Lock for a selected member in isolation and for a selected group outside it. #[test] fn lock_is_a_quick_action_in_and_outside_isolation_mode() { diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 0f1cf3db5f..3cd54cc851 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -461,14 +461,23 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// The Control bar's underlined "Transform" link: a click toggles the Transform panel in a /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let resp = ui.link(egui::RichText::new(tl!("Transform")).size(12.0).color(t.text).underline()).on_hover_text(tl!("Transform options")); + let resp = ui.link(link_text(ui)).on_hover_text(tl!("Transform options")); widgets::popover(&resp, resp.clicked(), |ui| { ui.set_width(300.0); show(app, ui); }); } +/// The Transform link's text, as [`link`] draws it and [`link_width`] measures it. +fn link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Transform")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The width of the Transform [`link`] in `ui`. +pub fn link_width(ui: &Ui) -> f32 { + widgets::text_width(ui, link_text(ui)) +} + /// The width and height of [`constrain_link`]'s button. pub const CONSTRAIN_LINK_SIZE: f32 = 22.0; diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 1b28f7d1fb..3a7f5d89ad 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -1,7 +1,8 @@ //! Background rendering (native): heavy documents render off the UI thread while the canvas shows //! the previous frame reprojected to the current view. A second worker renders a low-resolution //! frame for the parts that frame does not reach (`canvas::fill_uncovered`). Light documents -//! render synchronously so edits never lag behind overlays. +//! render synchronously so edits never lag behind overlays, after a first frame that renders here +//! too: the UI thread waits for it only briefly (`canvas::FIRST_FRAME_GRACE`). use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender, channel}; @@ -80,16 +81,31 @@ impl Worker { (Self { tx, rx, pending: None }, jobs, done_tx) } - pub fn submit(&mut self, job: Job) { + /// Queue `job`, unless the job pending is the same frame. Whether it was queued. + pub fn submit(&mut self, job: Job) -> bool { if self.pending.as_ref() == Some(&job.key) { - return; + return false; } self.pending = Some(job.key.clone()); - let _ = self.tx.send(job); + // A worker that has stopped renders nothing: the canvas keeps the frame it shows. + self.tx.send(job).is_ok() } + /// The newest finished frame, if any. pub fn poll(&mut self) -> Option { - let mut last = None; + self.newest(None) + } + + /// The newest finished frame, waiting up to `timeout` for one when none has finished yet. + pub fn wait(&mut self, timeout: std::time::Duration) -> Option { + let first = self.rx.try_recv().ok().or_else(|| self.rx.recv_timeout(timeout).ok())?; + self.newest(Some(first)) + } + + /// The newest of `first` and the frames finished since, the pending job cleared when it is + /// the one. + fn newest(&mut self, first: Option) -> Option { + let mut last = first; while let Ok(d) = self.rx.try_recv() { last = Some(d); } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index d7fe9e593b..81b152a790 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -37,6 +37,10 @@ pub type PickSave = Box Option>; pub type ReadFn = Box Result, String>>; +/// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file +/// is not read. +pub type ReadHeadFn = Box Result, String>>; + pub type WriteFn = Box Result<(), String>>; pub type ExistsFn = Box bool>; @@ -76,6 +80,10 @@ pub struct Services { /// Show a save dialog (suggested name, folder, file types); returns a path. pub pick_save: Option, pub read: Option, + /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one + /// byte past the limit, so a larger file is refused without reading all of it. Without it, the + /// whole file is read with `read`. + pub read_head: Option, pub write: Option, /// Is there a file or folder at a path (desktop)? The app asks before replacing a file that a /// save panel's name names once the app gives it an extension ([`picks::ask_to_replace`]). diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index c2e5497404..1232aba364 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -139,13 +139,15 @@ fn runs_a_command(i: &egui::InputState, key: Key, cmd_only: bool) -> bool { _ => None, }) .collect(); - let shortcuts = all_shortcuts(); - let bound = |m: &Modifiers| { - shortcuts - .iter() - .any(|(sc, ..)| sc.logical_key == key && (sc.modifiers.command || (!cmd_only && sc.modifiers.any())) && m.matches_logically(sc.modifiers)) - }; - !presses.is_empty() && presses.iter().all(bound) + !presses.is_empty() && presses.iter().all(|m| chord_runs_a_command(key, *m, cmd_only)) +} + +/// Is a command shortcut bound to `key` held with `m`, matched logically? +/// `cmd_only`: only chords with Cmd count. +fn chord_runs_a_command(key: Key, m: Modifiers, cmd_only: bool) -> bool { + all_shortcuts() + .iter() + .any(|(sc, ..)| sc.logical_key == key && (sc.modifiers.command || (!cmd_only && sc.modifiers.any())) && m.matches_logically(sc.modifiers)) } /// Whether a key press runs a shortcut of the keymap in effect, the user's own included. The web @@ -233,7 +235,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { let composing = app.session.tool_composing(); // Tool keys first (Enter/Escape end paths; arrows change polygon sides while dragging). let busy = app.session.tool_busy(); - for (k, tk) in [(Key::Enter, ToolKey::Enter), (Key::Escape, ToolKey::Escape)] { + // Enter in the Type tool types a line break, so it goes to the tool with the frame's text, + // below: the loop then skips Enter, the first key. + let enter_types = app.session.tool_wants_text(); + for (k, tk) in [(Key::Enter, ToolKey::Enter), (Key::Escape, ToolKey::Escape)].into_iter().skip(usize::from(enter_types)) { if !typing && !composing && ctx.input(|i| i.key_pressed(k)) { // A chord a command is bound to (Cmd+Enter) runs only that command, in the shortcuts // below, also when the tool claims the key. While the Type tool edits text only Cmd @@ -507,27 +512,11 @@ fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: boo ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { .. } | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)))); return; } - // A deferred pointer/navigation notice has not established its destination yet. Its - // clipboard suffix must not cut or paste at the old caret; only the notice's own actual - // handler (kept in the raw vector) may run. - if crate::ime::deferred(app, ctx) { - ctx.input_mut(|input| { - input.events.retain(|event| match event { - egui::Event::Cut | egui::Event::Paste(_) => false, - egui::Event::Key { key: egui::Key::X | egui::Key::V, pressed: true, modifiers, .. } - if modifiers.command && !modifiers.shift && !modifiers.alt => - { - false - } - _ => true, - }) - }); - } crate::panels::actions::play_function_key(app, ctx); - // Editing keys with modifiers and the clipboard (Cmd+A is Select All's, below: the text). - crate::panels::character::route_type_input(app, ctx); - // Enter was already delivered above as ToolKey::Enter (newline). Only chords with the - // command key run commands: the rest type or edit. + // Cmd+A is Select All's, below: the text. Enter went to the tool in `type_text`, unless a + // command is bound to its chord, and so did the editing keys and the clipboard events (a + // cut or paste after a deferred pointer or navigation notice is dropped there). Only chords + // with the command key run commands: the rest type or edit. let hits = dispatch(app, ctx, |hit| hit.trigger.chord.mods.cmd); for c in hits { run_hit(app, ctx, &c); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index efe9917492..80aa03365f 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1967,7 +1967,7 @@ fn parses() { /// An IME replacement on the Type tool arrives as `DeleteSurroundingBytes` + `Commit` events /// and is taken once, in order: the marked text is dropped, the committed text replaces it, and -/// the events never reach `route_type_input` as typed characters. +/// the events are never typed as characters. #[test] fn ime_delete_surrounding_bytes_edits_the_type_tool_once() { use vectorcraft_tools::{PointerEvent, PointerKind}; diff --git a/crates/ui-egui/src/shortcuts/typing.rs b/crates/ui-egui/src/shortcuts/typing.rs index 4ed15a6b38..cdd8c16f82 100644 --- a/crates/ui-egui/src/shortcuts/typing.rs +++ b/crates/ui-egui/src/shortcuts/typing.rs @@ -1,4 +1,5 @@ -use super::{EngineResult, Key, Mods, SurroundingUnit, ToolKey, UiRequest, VectorcraftApp, ViewInfo}; +use super::{EngineResult, Key, Mods, SurroundingUnit, ToolKey, UiRequest, VectorcraftApp, ViewInfo, chord_runs_a_command}; +use crate::panels::character::TextInput; /// Drop each key press made with Ctrl and Alt held that is followed by the text it typed. Firefox /// on Windows reports AltGr as Ctrl and Alt held, so AltGr+L on a Polish layout arrives as a @@ -51,9 +52,14 @@ enum Seq { InterruptNavigation, InterruptCommand, ResetCompleted(egui::ImeResetId), + /// Enter, which types a line break. + Enter(Mods), + /// An editing key with modifiers, an arrow, Home, End, Tab or a clipboard event. + Edit(TextInput), } -/// Typed text and IME events, in the order they came, to the Type tool. +/// Typed text, IME events, editing keys, Enter and clipboard events, in the order they came, to the +/// Type tool. Escape is handled before them, in [`handle`]. pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { let view = app.view_info(); // Switching apps mid-composition needs nothing: the macOS IME keeps its marked text and goes @@ -62,14 +68,18 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { // A frame that began composing keeps its editing keys for the IME: a Backspace that empties the // marked text must not then delete the committed character before it. let was_composing = app.session.tool_composing(); + crate::panels::character::keep_ctx(ctx); // Text, IME events and plain Backspace/Delete are taken together, in the order they arrived, so // a keyboard-hook IME (UniKey/OpenKey) whose tone key sends Backspace(s) and then re-injects // characters in one frame interleaves correctly. Taken as two passes (all text, then the keys) - // the deletes land after the inserts and the diacritics are lost. Each handled event is removed - // so `route_type_input` below does not process the same Backspace/Delete again. + // the deletes land after the inserts and the diacritics are lost. Enter, the other editing keys + // and the clipboard events join them: ← or a paste lands between the texts around it, and each + // Enter types its own line break. Each handled event is removed from the input. let seq = type_sequence(ctx); let viewport = ctx.viewport_id(); let mut old_composition_retired = false; + // Set once the IME commits text in this frame. + let mut committed = false; for e in seq { // Before the UI, a changed composition or guard is settled `pending`: a token bound here // could outlive a route this pass invalidates later (a palette/dialog/Home) and attach to @@ -91,10 +101,19 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { // erases after it belong to the old caret, not to the destination it will establish. if crate::ime::deferred(app, ctx) { match &e { - Seq::Text(_) | Seq::Erase(..) => continue, + // A cut or paste must not change the text at the old caret either. + Seq::Text(_) | Seq::Erase(..) | Seq::Edit(TextInput::Cut | TextInput::Paste(_)) => continue, _ => {} } } + // Editing keys and clipboard events belong to the IME while it composes, and in a frame + // that began composing until the IME commits or the composition is retired. + if matches!(&e, Seq::Edit(_)) && (app.session.tool_composing() || (was_composing && !committed && !old_composition_retired)) { + continue; + } + if let Seq::Commit(t) = &e { + committed |= !t.is_empty() && t != "\n" && t != "\r"; + } let preedit_empty = match &e { Seq::Preedit(text, _) => Some(text.is_empty()), _ => None, @@ -114,9 +133,11 @@ pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { old_composition_retired } -/// Take this frame's typed text, IME events and plain Backspace/Delete, in the order they arrived. +/// Take this frame's typed text, IME events, editing keys, Enter and clipboard events, in the order +/// they arrived. fn type_sequence(ctx: &egui::Context) -> Vec { let mut seq = vec![]; + let mut edits = vec![]; ctx.input_mut(|i| { // Move the events out instead of cloning their strings: a keyboard hook that reinjects a // batch keeps the batch in `seq` only, not in both the input list and a second copy. @@ -149,13 +170,20 @@ fn type_sequence(ctx: &egui::Context) -> Vec { // routed as a key or shortcut). egui::Event::MiddleClickPaste { text, .. } => seq.push(Seq::Text(text)), // Only unmodified Backspace/Delete interleave with injected text; word-delete and other - // modified forms stay with `route_type_input`. + // modified forms are taken with the other editing keys below. egui::Event::Key { key: key @ (Key::Backspace | Key::Delete), pressed: true, modifiers: m, .. } if !m.command && !m.alt && !m.ctrl => { let tk = if key == Key::Backspace { ToolKey::Backspace } else { ToolKey::Delete }; seq.push(Seq::Erase(tk, Mods { shift: m.shift, ..Mods::default() })); } + // A command bound to the chord (Cmd+Enter) runs instead of the line break, in the + // shortcuts after this. + egui::Event::Key { key: Key::Enter, pressed, modifiers: m, .. } if !chord_runs_a_command(Key::Enter, m, true) => { + if pressed { + seq.push(Seq::Enter(crate::canvas::mods(m, false))); + } + } e @ egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => { primary_down = pressed; if pressed { @@ -169,22 +197,25 @@ fn type_sequence(ctx: &egui::Context) -> Vec { } kept.push(e); } - e @ egui::Event::Key { key, pressed: true, modifiers, .. } - if matches!(key, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End) - || key == Key::A && modifiers.command => - { - seq.push(Seq::InterruptNavigation); - kept.push(e); + e => { + let interrupt = match &e { + egui::Event::Key { key, pressed: true, modifiers, .. } + if matches!(key, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End) + || *key == Key::A && modifiers.command => + { + Some(Seq::InterruptNavigation) + } + egui::Event::Key { pressed: true, modifiers, .. } if is_shortcut_chord(*modifiers) => Some(Seq::InterruptCommand), + egui::Event::Cut | egui::Event::Paste(_) => Some(Seq::InterruptCommand), + _ => None, + }; + seq.extend(interrupt); + // The other editing keys and the clipboard events apply in this order too. + if crate::panels::character::type_input(&e, &mut edits) { + kept.push(e); + } + seq.extend(edits.drain(..).map(Seq::Edit)); } - e @ egui::Event::Key { pressed: true, modifiers, .. } if is_shortcut_chord(modifiers) => { - seq.push(Seq::InterruptCommand); - kept.push(e); - } - e @ (egui::Event::Cut | egui::Event::Paste(_)) => { - seq.push(Seq::InterruptCommand); - kept.push(e); - } - other => kept.push(other), } } i.events = kept; @@ -287,8 +318,8 @@ fn apply_type_event( } // While composing (or in a frame that began composing), editing keys belong to the IME. Seq::Erase(tk, m) if !was_composing && !app.session.tool_composing() => { - // Mirror `route_type_input`/`text_key`: surface an erase error in the status bar - // instead of discarding it, and report the successful edit as application-origin. + // Mirror `text_key`: surface an erase error in the status bar instead of discarding it, + // and report the successful edit as application-origin. let target_before = crate::ime::target(&mut app.session, view); let before = crate::ime::stamp(&mut app.session, view); let r = app.session.tool_key(tk, m, view); @@ -312,5 +343,22 @@ fn apply_type_event( } r } + // An Enter that confirms the composition types no line break. + Seq::Enter(_) if was_composing || app.session.tool_composing() => Ok(vec![]), + Seq::Enter(m) => { + let target_before = crate::ime::target(&mut app.session, view); + let before = crate::ime::stamp(&mut app.session, view); + let r = app.session.tool_key(ToolKey::Enter, m, view); + if r.is_ok() { + crate::ime::note_application_edit(app, ctx, view, target_before, before); + } + crate::canvas::apply_requests(app, r); + Ok(vec![]) + } + // `text_key` and `text_paste` report the edit as application-origin. + Seq::Edit(t) => { + crate::panels::character::apply_type_input(app, t); + Ok(vec![]) + } } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2baf6f6ee7..7f562f0579 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -34,9 +34,12 @@ impl Default for View { } impl View { - /// The view a document opens at: the one it was saved with, else fitted on first display. + /// The view a document opens at: the one it was saved with, else fitted on first display, on + /// the artboard the opened file names as its active one ([`vectorcraft_doc::Document::opened_artboard`]), + /// else the first. pub fn of(st: &vectorcraft_engine::DocState) -> Self { - st.view.as_ref().and_then(Self::saved).unwrap_or_default() + let artboard = st.doc.opened_artboard.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)).unwrap_or(0); + Self { artboard, ..st.view.as_ref().and_then(Self::saved).unwrap_or_default() } } /// The view `v` saved (the one a document was saved with, or a View → New View… one), within @@ -325,6 +328,18 @@ impl Dialog { } } +/// The last Replace Font request whose warning the status bar shows, to refresh it as the +/// document changes. +#[derive(Clone, Debug)] +pub struct ReplaceFontWarning { + pub document_uid: u64, + pub revision: u64, + pub request: serde_json::Value, + pub selection: Option>, + pub text: String, + pub styles: Vec<(String, String)>, +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct UiState { @@ -382,6 +397,11 @@ pub struct UiState { /// is open. Not saved. #[serde(skip)] pub context_intertwine: Option<(u64, vectorcraft_doc::NodeId, vectorcraft_geom::Point, vectorcraft_doc::NodeId)>, + /// Which link statuses the active document's images and placed documents have, for Select › + /// Linked, Embedded, Missing and Modified to be on only when some do (refreshed by + /// [`crate::addons::select::link_status::refresh`]). Not saved. + #[serde(skip)] + pub link_statuses: crate::addons::select::link_status::Present, /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). #[serde(default)] pub slot_tool: std::collections::BTreeMap, @@ -456,6 +476,9 @@ pub struct UiState { /// Last tool shown for each toolbar group (flyout selection sticks). pub group_tool: Vec, pub status: String, + /// The Replace Font request behind the status bar's warning ([`ReplaceFontWarning`]). Not saved. + #[serde(skip)] + pub replace_font_warning: Option, pub palette_open: bool, pub palette_query: String, /// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation. Not saved: @@ -942,6 +965,7 @@ impl Default for UiState { shape_modes_compound: false, context_locked: None, context_intertwine: None, + link_statuses: Default::default(), slot_tool: Default::default(), floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), @@ -968,6 +992,7 @@ impl Default for UiState { flyout: None, group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), status: String::new(), + replace_font_warning: None, palette_open: false, palette_query: String::new(), screen_mode: 0, @@ -1176,6 +1201,30 @@ mod tests { assert_eq!(next_zoom_with_display(b, true, true), zoom_from_display_percent(150.0, true)); } + #[test] + fn a_document_opens_on_the_artboard_its_file_names_as_active() { + let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); + let first = doc.artboards[0].clone(); + for id in [2, 3] { + let x0 = f64::from(id - 1) * 150.0; + doc.artboards.push(vectorcraft_doc::Artboard { id, rect: vectorcraft_geom::Rect::new(x0, 0.0, x0 + 100.0, 100.0), ..first.clone() }); + } + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + for (opened, active) in [(Some(3), 2), (None, 0), (Some(9), 0)] { + let mut d = doc.clone(); + d.opened_artboard = opened; + app.session.add_document(d, None); + app.sync_views(); + assert_eq!(app.view().map(|v| v.artboard), Some(active), "{opened:?}"); + } + // With the view the document was saved with too. + doc.opened_artboard = Some(2); + doc.last_view = Some(vectorcraft_doc::SavedView { name: String::new(), center: Point::new(400.0, 50.0), zoom: 2.0, rotation: 0.0 }); + app.session.add_document(doc, None); + app.sync_views(); + assert_eq!(app.view().map(|v| (v.artboard, v.zoom)), Some((1, 2.0))); + } + #[test] fn dialog_fields() { let d = Dialog::new("rectangle", serde_json::json!({"width": "1in", "height": 50})); diff --git a/crates/ui-egui/src/tests/synthetic.rs b/crates/ui-egui/src/tests/synthetic.rs index c6e64a12fa..e61cb8fa19 100644 --- a/crates/ui-egui/src/tests/synthetic.rs +++ b/crates/ui-egui/src/tests/synthetic.rs @@ -117,6 +117,172 @@ fn a_pointer_release_after_a_key_waits_for_the_key() { assert!(closed, "C reached the Arc tool before the release"); } +/// An MCP pointer gesture can select a tool just before sending its pointer events. A key queued +/// by the previous call must reach the old tool before that selection changes it. +#[test] +fn tool_selection_after_a_key_waits_for_the_key() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "pen"})).unwrap(); + let ctx = egui::Context::default(); + let (key, _key_reply) = ControlRequest::new("ui.key", json!({"key": "B", "shift": true, "text": "B"})); + let (select, select_reply) = ControlRequest::new("ui.tool.select", json!({"tool": "arc"})); + tx.send(key).unwrap(); + tx.send(select).unwrap(); + + app.drain_control(&ctx); + assert!(select_reply.try_recv().is_err(), "selection waits while Shift+B is queued"); + assert_eq!(app.session.tool_id(), "pen"); + let mut key_reached_tool = false; + let mut selected = None; + for _ in 0..8 { + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + app.drain_control(&ctx); + if let Ok(reply) = select_reply.try_recv() { + selected = Some(reply); + break; + } + let mut out = ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + key_reached_tool |= app.session.tool_id() == "blobBrush"; + } + assert!(key_reached_tool, "Shift+B reaches the old tool before the explicit selection"); + let selected = selected.expect("the later tool selection runs"); + assert_eq!(selected["ok"], true, "{selected}"); + assert_eq!(app.session.tool_id(), "arc"); +} + +#[test] +fn tool_selection_after_a_discarded_key_does_not_run() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "pen"})).unwrap(); + let ctx = egui::Context::default(); + let (key, _key_reply) = ControlRequest::new("ui.key", json!({"key": "B", "shift": true, "text": "B"})); + let (select, select_reply) = ControlRequest::new("ui.tool.select", json!({"tool": "arc"})); + tx.send(key).unwrap(); + tx.send(select).unwrap(); + for _ in 0..2 { + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + app.drain_control(&ctx); + assert!(select_reply.try_recv().is_err(), "selection waits for the key"); + } + assert!(app.synthetic_injected); + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + app.drain_control(&ctx); + let selected = select_reply.try_recv().expect("the waiting selection is answered"); + assert_eq!(selected["ok"], false, "{selected}"); + assert_eq!(app.session.tool_id(), "pen", "the discarded key cannot precede a tool switch"); +} + +/// A waiting `ui.pointer` request whose caller gave it up is dropped at once: the requests sent +/// after it run without waiting for the input sent before it to be applied. +#[test] +fn a_given_up_pointer_does_not_hold_back_later_requests() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + let (key, _key_reply) = ControlRequest::new("ui.key", json!({"key": "c"})); + let (up, up_reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 200, "y": 180}]})); + let ticket = up.ticket(); + let (list, list_reply) = ControlRequest::new("ui.tool.list", json!({})); + tx.send(key).unwrap(); + tx.send(up).unwrap(); + tx.send(list).unwrap(); + app.drain_control(&ctx); + assert!(list_reply.try_recv().is_err(), "the pointer request waits for the key, ahead of the list"); + assert!(ticket.give_up(), "the waiting pointer request had not started"); + // The key is still queued: no UI pass ran. + app.drain_control(&ctx); + let r = list_reply.try_recv().expect("the list ran past the given-up pointer request"); + assert_eq!(r["ok"], true, "{r}"); + assert!(up_reply.try_recv().is_err(), "the given-up pointer request did not run"); +} + +/// Given-up `ui.pointer` requests made before synthetic input was dropped do not count toward a +/// frame's request limit: a request queued behind a frame's worth of them runs in that frame. +#[test] +fn given_up_stale_pointer_requests_do_not_use_up_the_frame() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + for _ in 0..crate::control::MAX_CONTROL_REQUESTS_PER_FRAME { + let (up, _up_reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 200, "y": 180}]})); + assert!(up.ticket().give_up(), "the pointer request had not started"); + tx.send(up).unwrap(); + } + app.synthetic_dropped_before = ControlRequest::next_seq(); + let (list, list_reply) = ControlRequest::new("ui.tool.list", json!({})); + tx.send(list).unwrap(); + app.drain_control(&ctx); + let r = list_reply.try_recv().expect("the list ran in the same frame"); + assert_eq!(r["ok"], true, "{r}"); +} + +/// A `ui.pointer` release sent after a `ui.key` fails when the key's batch is discarded because a +/// dialog opened before a UI pass took it, whether the release was waiting for the key +/// (`waiting`) or still on the channel. A release made after the discard runs. +fn a_release_after_a_discarded_key(waiting: bool) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "arc"})).unwrap(); + let ctx = egui::Context::default(); + control(&mut app, &ctx, "ui.pointer", json!({"events": [{"kind": "down", "x": 100, "y": 100}, {"kind": "drag", "x": 200, "y": 180}]})); + let (key, _key_reply) = ControlRequest::new("ui.key", json!({"key": "c"})); + let (up, up_reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 200, "y": 180}]})); + tx.send(key).unwrap(); + let mut up = Some(up); + if waiting { + tx.send(up.take().unwrap()).unwrap(); + } + // The first frame queues the key; the second injects it. + for _ in 0..2 { + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + app.drain_control(&ctx); + assert!(up_reply.try_recv().is_err(), "the release waits for the key"); + } + assert!(app.synthetic_injected, "the key is in the frame's input"); + if let Some(up) = up { + tx.send(up).unwrap(); + } + // A dialog opens before a UI pass takes the key, so the next frame discards it. + app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + // A release made after the key was discarded, queued behind the first one, runs. + let (later, later_reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 200, "y": 180}]})); + tx.send(later).unwrap(); + app.drain_control(&ctx); + let r = up_reply.try_recv().expect("the release was answered"); + assert_eq!(r["ok"], false, "{r}"); + let r = later_reply.try_recv().expect("the later release was answered"); + assert_eq!(r["ok"], true, "{r}"); + let document = app.session.active().unwrap(); + let arc = *document.selection.objects.last().expect("the arc drawn on the later release"); + let closed = document.doc.node(arc).unwrap().path_data().unwrap().subpaths[0].closed; + assert!(!closed, "the discarded C did not reach the Arc tool"); +} + +#[test] +fn a_waiting_pointer_release_fails_when_the_key_before_it_is_discarded() { + a_release_after_a_discarded_key(true); +} + +#[test] +fn a_queued_pointer_release_fails_when_the_key_before_it_is_discarded() { + a_release_after_a_discarded_key(false); +} + #[test] fn a_drag_holds_its_modifiers_from_the_press_to_the_release() { let (mut app, _) = one_square(); diff --git a/crates/ui-egui/src/tests/tab_reorder.rs b/crates/ui-egui/src/tests/tab_reorder.rs index 167addce0a..c1070fbc70 100644 --- a/crates/ui-egui/src/tests/tab_reorder.rs +++ b/crates/ui-egui/src/tests/tab_reorder.rs @@ -136,6 +136,40 @@ fn views_follow_a_move_made_by_the_engine_command() { assert_eq!(app.views.iter().map(|v| v.zoom).collect::>(), [4.0, 2.0, 3.0]); } +/// One batch that closes documents and moves others (a script, a recording) leaves every view with +/// its own document; the views are put right once, after the whole batch. +#[test] +fn views_follow_closes_and_moves_made_in_one_batch() { + let (mut app, _ctx) = app(); + let zooms = |app: &VectorcraftApp| app.views.iter().map(|v| v.zoom).collect::>(); + for (k, v) in app.views.iter_mut().enumerate() { + v.zoom = 1.0 + k as f64; + } + // A close alone, in the middle: the documents after it keep their own views. + app.run("command.batch", json!({"commands": [{"command": "file.close", "params": {"index": 1}}]})).unwrap(); + assert_eq!(order(&app), ["Alpha", "Charlie", "Delta"]); + assert_eq!(zooms(&app), [1.0, 3.0, 4.0], "Charlie and Delta keep theirs, not Bravo's and Charlie's"); + // A close and a move together. + app.run( + "command.batch", + json!({"commands": [ + {"command": "file.close", "params": {"index": 0}}, + {"command": "document.move", "params": {"from": 1, "to": 0}}, + ]}), + ) + .unwrap(); + assert_eq!(order(&app), ["Delta", "Charlie"]); + assert_eq!(zooms(&app), [4.0, 3.0], "Delta does not take the closed Alpha's view"); + // Closing by index made the document in the closed one's place current (Charlie); it shows its own view. + assert_eq!((current(&app), app.view().map(|v| v.zoom)), ("Charlie".into(), Some(3.0))); + // A document opened afterwards starts with a view of its own. + app.run("file.new", json!({"width": 100, "height": 100, "name": "Echo"})).unwrap(); + app.sync_views(); + assert_eq!(order(&app), ["Delta", "Charlie", "Echo"]); + assert_eq!(app.views.len(), 3); + assert_eq!(&zooms(&app)[..2], [4.0, 3.0]); +} + #[test] fn a_tab_dragged_off_the_strip_still_floats_and_moves_nothing() { let (mut app, ctx) = app(); diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index c754cd786d..7a04484dc2 100644 --- a/crates/ui-egui/src/thumb_worker.rs +++ b/crates/ui-egui/src/thumb_worker.rs @@ -9,6 +9,7 @@ use std::collections::VecDeque; use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; +use std::sync::{Arc, Mutex}; use vectorcraft_render::{Rendered, Renderer}; @@ -32,9 +33,12 @@ struct Job { run: JobFn, } -/// Which slots' jobs [`ThumbWorker::discard`] drops. +/// Which slots' jobs [`ThumbWorker::discard`] or [`ThumbWorker::forget`] drops. type SlotTest = Box bool + Send>; +/// The slots [`ThumbWorker::forget`] picked since the worker was last idle. +type Forgotten = Arc>>>; + /// What a panel sends its worker: a job, or the slots whose jobs not started yet are dropped. enum Msg { Job(Job), @@ -47,6 +51,7 @@ enum Msg { pub struct ThumbWorker { tx: Sender>, rx: Receiver>, + forgotten: Forgotten, } impl ThumbWorker { @@ -64,6 +69,8 @@ impl ThumbWorker { pub(crate) fn start(ctx: &egui::Context, name: &str) -> Option { let (tx, jobs) = channel::>(); let (done_tx, rx) = channel::>(); + let forgotten: Forgotten = Arc::default(); + let gone = forgotten.clone(); let ctx = ctx.clone(); std::thread::Builder::new() .name(format!("vectorcraft-{name}")) @@ -79,24 +86,55 @@ impl ThumbWorker { }; loop { if queue.is_empty() { - // The panel is gone (its sender dropped): end the thread. - let Ok(job) = jobs.recv() else { break }; - add(&mut queue, job); + // With no job here or on its way (checked under the lock, since a panel + // sends a job before it forgets that job's slot), what `forget` picked + // has no job left to drop. + let waiting = match gone.lock() { + Ok(mut f) => match jobs.try_recv() { + Ok(msg) => Some(msg), + Err(_) => { + f.clear(); + None + } + }, + Err(_) => break, + }; + let msg = match waiting { + Some(msg) => msg, + // The panel is gone (its sender dropped): end the thread. + None => match jobs.recv() { + Ok(msg) => msg, + Err(_) => break, + }, + }; + add(&mut queue, msg); } while let Ok(job) = jobs.try_recv() { add(&mut queue, job); } let Some(job) = queue.pop_front() else { continue }; + let Ok(skip) = gone.lock().map(|f| f.iter().any(|which| which(&job.slot))) else { break }; + if skip { + continue; + } let t0 = crate::now_ms(); let img = (job.run)(&mut r); - if done_tx.send(Done { key: job.key, img, ms: crate::now_ms() - t0 }).is_err() { + let done = Done { key: job.key, img, ms: crate::now_ms() - t0 }; + // Sent under the lock, so a `forget` either drops it here or comes after it + // and finds it in the next `poll`. + let Ok(f) = gone.lock() else { break }; + if f.iter().any(|which| which(&job.slot)) { + continue; + } + if done_tx.send(done).is_err() { break; } + drop(f); ctx.request_repaint(); } }) .ok()?; - Some(Self { tx, rx }) + Some(Self { tx, rx, forgotten }) } /// Queue `run` for `slot` (replacing a job for the slot that hasn't started). False when the @@ -114,6 +152,15 @@ impl ThumbWorker { self.tx.send(Msg::Discard(Box::new(which))).is_ok() } + /// Drop the jobs whose slot `which` picks, queued or running: their images never come back + /// from [`ThumbWorker::poll`], except those finished before this call, which the next poll + /// returns. The panel must not submit jobs for those slots again. + pub fn forget(&self, which: impl Fn(&S) -> bool + Send + 'static) { + if let Ok(mut f) = self.forgotten.lock() { + f.push(Box::new(which)); + } + } + /// The jobs finished since the last call, oldest first; None when the thread is gone (the /// jobs it had will never finish). pub fn poll(&self) -> Option>> { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 94054a0d46..2280853e13 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -426,6 +426,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result Result Ok(json!({ "pending": KIND })) } -/// Close document `i` through the engine command, keeping `views` aligned with the documents. +/// Close document `i` through the engine command; [`VectorcraftApp::sync_views`] drops its view. fn close_now(app: &mut VectorcraftApp, i: usize) -> Result { let r = app.session.execute("file.close", &json!({ "index": i })).map_err(|e| e.to_string())?; - if i < app.views.len() { - app.views.remove(i); - } app.sync_views(); if app.session.tool_id() == "artboard" && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b5bc1991bd..5c8a701dd0 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -49,7 +49,7 @@ pub use dropdowns::{ panel_scroll, popover, set_menu_floor, strip_scroll, }; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; -pub(crate) use labels::{label_field, take_previous_label}; +pub(crate) use labels::{label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_within, num_field_within_empty, opt_field, diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index a71a0ec6a5..8c04de54b9 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -1,5 +1,11 @@ use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, icons, pos2, scrub, theme, vec2}; +/// The width `text` takes on one line, as a label or link in `ui` draws it: its galley, which has +/// no padding around it. +pub(crate) fn text_width(ui: &Ui, text: egui::RichText) -> f32 { + egui::WidgetText::from(text).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x +} + /// Bold section header (Properties panel). pub fn section_header(ui: &mut Ui, text: &str) { let t = Tokens::get(ui.ctx()); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2ccf281a1e..488743f443 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (PDF import: DeviceN gradients of a spot ink over process plates, #3235) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (`.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -18,7 +18,7 @@ from the public specifications, and users' own `.ai` files are used locally only | | Illustrator | VectorCraft | Notes | |---|---:|---:|---| | Formats opened or placed | ~30 | 29 | missing: FreeHand, CorelDRAW, DWG, HEIC/HEIF, PICT, PS | -| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | +| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) | | Formats exported | ~16 | 17 | missing: DWG, 3D (OBJ/USDA/glTF); extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD | | **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting | @@ -64,10 +64,20 @@ private editing data. VectorCraft: their fills and strokes (a compound path as one path of all its subpaths), process, spot and global colors, swatches and color groups, guides, hidden and locked objects, object names, every artboard with its name, the transparency of objects and layers (opacity, blending mode, isolation, knockout and knockout shape), objects' opacity masks, and clipping groups and - clipping layers clipped by a path or compound path. Type, gradients, patterns, images, symbols, other clipping - objects and live objects are written as plain filled and stroked paths, each with a warning; the opacity and - blending mode of single fills and strokes, opacity masks on layers and effects other than geometry effects are - left out. + clipping layers clipped by a path or compound path, linear and radial gradients on fills and strokes (with their + stops' opacity, midpoints and spot colors, elliptical radials and focal points) and gradient swatches, and + patterns whose tiles make a grid and hold their art within the tile, with no pattern fill in that art, as + pattern definitions with their fills, strokes and swatches. Embedded images are written with their pixels (gray, + RGB or CMYK ink amounts, and their alpha channel) and linked images as placed files with their path, their folder + relative to the document's and a preview; images that can't be decoded or have more than 33,554,432 pixels are + written as their outlines filled mid gray, images of 16 bits a channel at 8 bits, and linked images in opacity + masks and pattern tiles as embedded images, each with a warning. Type, other patterns, symbols, other clipping + objects and live objects (placed documents included) are written as plain filled and stroked paths, and freeform gradients, gradients along + or across a stroke and gradients without stops, with more than 256 stops or without extent as their average + color, each with a warning. Gradients that dither or mix their colors perceptually are written as classic + gradients, and gradient stops linked to global process colors as their colors, each with a warning. The opacity + and blending mode of single fills and strokes, opacity masks on layers, the placement of pattern swatches that + move, turn or scale their pattern, and effects other than geometry effects are left out. - **Writes** a legacy `.ai` of version 7 (Save As › `ai` › Version: Legacy (version 7), `aiVersion: "7"`): the PostScript form, from the published *Adobe Illustrator File Format Specification* version 7.0 ([PRONOM fmt/423](https://www.nationalarchives.gov.uk/PRONOM/fmt/423)), which apps reading `.ai` open with its @@ -94,34 +104,54 @@ private editing data. VectorCraft: opens a file with that prolog from its program, as the format. - **Known failures in users' files:** layer structure flattened or multiplied (#951: 109 layers instead of 14; #868: round trip with Illustrator 2018 loses layers and groups), some files 4× slower to open since the - editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; - pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type - (`To` … `TO`) since #868; guides open as ruler guides and guide paths since #5057 (#779). + editing data is read whole (#758), live effects and brushes come in as their drawn look (#637; + pattern fills are read since #1025, and symbols and their instances open live); legacy `.ai` without the + prolog opens since #1027, its legacy type (`To` … `TO`) since #868; guides open as ruler guides and guide paths since #5057 (#779). 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), unmapped live - effects, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` + effects and brushes come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects - that are not read or have settings that are not read, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` + that are not read or have settings that are not read, and brushes come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. - lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects, - brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` + lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects + and brushes come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, and its placed EPS files in the version 7 form (`` ` `` … `~` with no `%AI5_BeginPlace`) are read like other placed files without a preview: as the page's art in their box. without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. Graphs (`%_Gs` … `%_GS`) come in as their drawn art, as plain groups, paths and type, without their data or settings, with a note. without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter - and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). Its patterns in + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). Its type in a font + re-encoded with encoding pairs of its own (`TZ`) is decoded with those pairs, and with the file's encoding + (`TE`) for the codes they leave out unless the `TZ` sets `useDefault` to 0. Its patterns in + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`); its tab definitions + (`Xb` … `XB`) set its paragraphs' tab stops; its special characters (`TS`) join the story, and end render + (`Te`) and pop text matrix (`TM`) are read and ignored. Its patterns in the version 7 form (a list of `@` and `&` layers, `_ &` for the tile's background) open as pattern swatches, with a fill's offset, scale, rotation, reflection and shear applied before its matrix. + Its area type with several linked areas opens as threaded frames, one for each area with its own matrix, + and the story flows through them. + Legacy `.ai` type set in rendering modes 4 to 7 (`Tr`, text used as a mask) is a clipping path of its + clipping group, as a `W` path is, and the mode lasts into later text objects. Type in linked areas, in + wraparound text or in a compound path doesn't clip, with a warning. A `Tr` operand that is not a whole number + from 0 to 9 leaves the mode as it was. + with a fill's offset, scale, rotation, reflection and shear applied before its matrix. Its linked images in + the version 7 form (`(path) modified XG`, then `XF` with no samples) come in as linked images of their files, + showing a placeholder where the image goes until the file is relinked in the Links panel. A path stored in + the classic Mac OS form (`Disk:Folder:file.tif`, with a colon and no `/` or `\`) is named by its last part, and + relinking looks for that name. + A 1-bit gray image whose `XI` or `XF` has ImageMask 1 comes in colorized by the fill color set before it, + or by black when that fill is not a solid color. VectorCraft's own rule is that the pixels that open black + with ImageMask 0 take the color and the others are transparent. - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), dashes aligned to corners, a brush other than a Calligraphic one, or a Calligraphic brush with settings of its own or an angle that follows the path comes in as its drawn look (a group named after it). A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372). A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing) or Pucker & Bloat at 0 comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way on an unstroked path or compound path whose segments are all straight. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), dashes aligned to corners, a brush other than a Calligraphic one, or a Calligraphic brush with settings of its own or an angle that follows the path comes in as its drawn look (a group named after it). A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372). A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format @@ -169,7 +199,9 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | `.ai` import (#372): a path with a Calligraphic brush comes in as the path with the brush on its stroke (its weight scales the brush) when its art style's brush settings are the brush's own and its angle is on the page, else as its drawn look; a Calligraphic brush's Tilt, Bearing and Rotation codes come in as those channels instead of Random. Checked against a user's file of 6D Art Pen strokes (used locally, not committed); synthetic tests in `import::ai::tests` | | 2026-11-05 | minor | PDF import: the stops of an axial or radial shading in a DeviceN space of one spot ink and process plates link to the ink's swatch and keep the plates (`GradientStop.plates` in the native format); PDF and EPS export write them in a DeviceN space again (#3235) | +| 2026-11-04 | minor | Raster/PSD export uses document resolution unless ppi or scale is supplied; CLI run/convert accept --ppi. Synthetic engine, CLI and MCP regressions cover dimensions and override precedence; scores and hours unchanged. | | 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. | | 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out | | 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) | diff --git a/docs/gaps.md b/docs/gaps.md index 7b458a347e..5a8de15d61 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,17 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. + +**PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. + +Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. + +**PR #3272 revision — 2026-11-04:** Group Selection component drags defer ancestor selection until a completed click, using current Direct Selection release handling; original Outline Stroke fills and newer selection behavior retained. Scores and estimates unchanged. + Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. The closed font-family fields in Character, Properties and Control now accept the @@ -28,6 +36,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G9, G14: `.ai` paths with a Calligraphic brush open brushed (the brush on the stroke, at its weight) where the object's settings are the brush's own, and the brush's Tilt, Bearing and Rotation codes come in as those channels; Windows reads the pen's tilt and barrel rotation from Windows Ink (#372). Checked against a user's file of 6D Art Pen strokes, used locally; not tried with a pen. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour add-on (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `addon.contour.set` is the command behind it. It is a built-in add-on: Object › Plug-ins › Contour, and its own heading in All Tools, with no default shortcut or toolbar slot. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-04 | minor | Contour tool (beyond Illustrator): drag away from a selected shape's edge to grow a live copy of it, or toward the inside to shrink it; the copy carries a live Offset Path effect, so it stays editable until Bake (Expand Appearance), a second drag changes the same Contour instead of nesting one, and a floating bar sets the distance and the Sharp, Round or Square corners. `object.contour` is the command behind it. A VectorCraft design built on Offset Path; no other application was inspected. Scores and estimates unchanged. | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | @@ -174,8 +183,14 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (2026-10-16):** EPS legacy mesh corners and vector opacity masks retained; winding-declared compound member groups keep shared paint. Raster print-page minification no longer causes a false editing-data fallback; comparison limits remain unchanged. Synthetic regressions cover damage and missing artwork. This narrows G9; scores and estimates unchanged. +- **Done (2026-11-05):** paths with a Calligraphic brush open as paths with the brush on their stroke, at their + weight, where the object's brush settings are the brush's own and its angle is on the page (#372, from a + user's file of 6D Art Pen strokes: all 455 of its brushed styles), and a Calligraphic brush's Tilt, Bearing and + Rotation (codes 4, 5 and 6) come in as those channels instead of Random. Others keep their drawn look. + - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead - of 14), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope + of 14), open speed on large files (#758), live effects, Scatter, Art, Pattern and Bristle brushes on paths, a + path's own Calligraphic brush settings, and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and @@ -480,7 +495,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall pointer, and a right-click offers Bring to Front, Bring Forward, Send Backward and Send to Back for it in that area (`object.intertwine.arrange` with `order` front, forward, backward or back; ). - The group renders, saves and exports through its live expansion. Still missing: adding objects to the group by + The group renders, saves and exports through its live expansion; an object brought over another shows no hairline + of the one below along that object's edges (#5337). Still missing: adding objects to the group by dragging them in the Layers panel is untested. - **Done (from users' reports):** Object › Create Gradient Mesh on an embedded image turns it into a mesh over its rectangle, with the image's transform kept; each point takes the average colour and opacity of the picture around it @@ -540,9 +556,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall The pen's eraser end on Windows with Windows Ink, read from the pen's pointer messages; not yet tried with a pen. On Linux under X11 and XWayland and on macOS, the Paintbrush records a pen's tilt, bearing and barrel rotation, and Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac with a tablet). + On Windows with Windows Ink, the pen's tilt and barrel rotation where the pen reports them (#372; not yet + tried with a pen). - **Missing:** pen pressure on native Wayland (#491, #764) — winit 0.30 reports none there; tilt, bearing and - barrel rotation on Windows, native Wayland and the web, and for Art, Pattern and Bristle brushes (6D Art Pen, - #372); the eraser end on native Wayland. + barrel rotation on native Wayland and the web, and for Art, Pattern and Bristle brushes (6D Art Pen, #372); + the eraser end on native Wayland. - **Estimate:** 4–10 h, partly waiting on winit 0.31; needs pen hardware to verify. ## G5 Brushes, symbols and libraries @@ -632,6 +650,16 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G15 Performance budgets and a GPU renderer +- **Improved (#4155):** an image zoomed in on has its colours separated, colorized or proofed only for the + 1,024-pixel tiles in view: zooming in to 100% on the file of #4155 went from 8.6 s to 0.05 s (measured in the app, + M3 Pro, one run). A CMYK image painting its own inks is still made whole. +- **Improved (#4155):** a document's first frame renders on the render worker, not the UI thread: opening the file + of #4155 kept the UI thread busy for 8.7 s at a stretch, now at most 64 ms, and a 50,000-path SVG 1.4 s, now + 62 ms (measured in the app, M3 Pro, one run each). A light document's frame, ready within 16 ms, still shows at once. +- **Improved (#4155):** the canvas shrinks a reduced image to the mip it draws before separating it into ink planes, + colorizing it or proofing it, so that work is done at the size the image shows, not at its own. On the + 141-megapixel image of #4155 the first frame went from 9.2 s to 1.6 s and the sharp frame after a pan from 3.9 s + to 8 ms (measured in the app, M3 Pro, one run each). - **Improved (2026-11-02):** the renderer keeps a compound path's assembled path with the node, as it keeps a plain path's, instead of assembling its members again in every frame; the path is assembled into a buffer sized up front. Unused geometry entries are dropped after a few frames however few there are (before, only past 1,024 entries), so @@ -742,6 +770,9 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | G15: an image zoomed in on is separated, colorized or proofed only for the tiles in view (#4155); 100% zoom on that file 8.6 s → 0.05 s. Estimate unchanged. | +| 2026-11-05 | minor | G15: a document's first frame renders on the render worker (#4155); the longest UI-thread stall opening that file went from 8.7 s to 64 ms. Estimate unchanged. | +| 2026-11-05 | minor | G15: a reduced image is shrunk before it is separated into ink planes (#4155); first frame 9.2 s → 1.6 s, sharp frame after a pan 3.9 s → 8 ms on that file. Estimate unchanged. | | 2026-11-05 | minor | G7: document tabs are dragged along the tab strip to reorder them (`document.move`, #5663). Estimate unchanged. | | 2026-11-02 | minor | G15: the renderer keeps a compound path's assembled path between frames and drops unused geometry entries after a few frames however few there are. Estimate unchanged. | | 2026-11-02 | minor | G15: hit testing culls paths and compound paths by their control points' box and tests a compound path's outline and fill against only its members near the click; the same objects are hit. Estimate unchanged. | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 0da3e279e3..5f6c87145e 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** patch (Linux: on a Wayland session with a pen attached, Automatic opens the window through XWayland, where the pen draws, #4967) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Windows: the pen's tilt and barrel rotation from Windows Ink, #372) · **Target:** Adobe Illustrator 2026 (30.x) What hardware Illustrator uses, per platform, against VectorCraft. Illustrator's side is from its public documentation (GPU Performance, touch workspace, pen pressure pages); ours from the code @@ -22,7 +22,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | | Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | -| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | no | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: Windows, native Wayland and the web read none, and Art, Pattern and Bristle brushes do not use them; 4–8 h after the input layer (#372) | +| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Art, Pattern and Bristle brushes do not use them; 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585) | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | | Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | @@ -35,6 +35,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Windows (#372): with Windows Ink, each pen pointer message's `POINTER_PEN_INFO` gives the pen's tilt (`tiltX`, `tiltY`) and barrel rotation where its pen mask says the pen reports them, written into the canvas's pen feed as on macOS and Linux, so a 6D Art Pen's barrel turns a Calligraphic brush's nib. Unit-tested (`windows_stylus::tests::a_pens_tilt_and_rotation_come_where_it_reports_them`); not yet tried with a pen, so the score is unchanged (estimated) | | 2026-11-01 | patch | Linux (#4967): on a Wayland session, Linux Display Server › Automatic opens the window through XWayland when a pen is attached as the app starts, as X11 (XWayland) When a Pen Is Attached does and as PhotoCraft does; on native Wayland winit 0.30 gets no tablet input and KWin 6.3+ and Mutter emulate no pointer, so the pen moved only the compositor's cursor. `VECTORCRAFT_NATIVE_WAYLAND=1` keeps Wayland. Unit-tested (`xwayland::tests`); not tried with a tablet; score unchanged (estimated) | | 2026-10-30 | patch | Touch (#4198): a second finger landing cancels the tool press the first finger began, also in the same frame (the Pencil's stroke and a Selection move are rolled back, nothing enters the undo history), and a finger landing while another is down presses nothing, so a pinch or two-finger pan only navigates. Headless canvas test `a_second_finger_cancels_the_tool_gesture_the_first_began`; not tried on a touch screen; score unchanged (estimated) | | 2026-10-24 | minor | macOS: an AppKit local event monitor reads each mouse and tablet event's pen pressure and the pen's end before the window gets it and writes them into the canvas's pen feed (#852): each pointer move of a stroke keeps its own pressure, mouse event coalescing is off, and the eraser end selects the Eraser tool. The mapping is unit-tested on every platform and the macOS code type-checks for `aarch64-apple-darwin`; not yet tried on a Mac with a tablet, so the score is unchanged (estimated) | diff --git a/docs/mcp.md b/docs/mcp.md index 0901a73065..b3c2b2a571 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -426,7 +426,8 @@ opens the picker through `run_command` with the remote backend. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. 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. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. | | `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`. `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. | @@ -708,6 +709,11 @@ SVG writes one file per artboard of a `range`); `useArtboards: false` exports th its effects paint, the effects of groups, type and images included. `artboard.fitToArt` measures the art the same way. +Raster exports default to the document's raster effects resolution. An explicit `scale` sets pixels per +point (72 times that value in ppi); `options.ppi` wins over either scale option. CLI `run --export` and +`convert` follow the same rule and accept `--ppi N` (which wins over `--scale N`). Documents at the +default 72 ppi still use 72 ppi; use `--ppi 300` for print output from those documents. + Raster exports take more options in `options`: `ppi` (72, 150, 300…; stored in the file, except in GIF, WebP and Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa` and `#rgba` are refused), `antiAlias` (`none`, `art`, `type`: text snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard @@ -2332,7 +2338,8 @@ its bounds. the styles unlinked from swatches, with their opacity, blend mode, isolate and knockout, and the patterns they paint with); without `path` it returns `{data}`, and `user: true` saves into the user library folder of the desktop app (category `user`, User Defined). `graphicStyle.loadLibrary {path? | data? | dataBase64?, name?}` loads a `.vcstyles` -file, or another document's graphic styles, as a library to add from; a file in the user library folder, or a file +file, or another document's graphic styles, as a library to add from (a `.ai` or EPS whose editing data holds graphic +styles and no layers gives the styles of its style list, in that order); a file in the user library folder, or a file with the same extension and bytes as one there, loads as that User Defined library. ## Symbol libraries @@ -4157,16 +4164,21 @@ comes back to the front, following the same preference. `links.check` reports ev another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. A PNG, JPEG, GIF or WebP file whose pixels can't be read is not shown: `links.relink` fails with "the image's pixels can't be read", and `links.update`, or `document.open` when it reads the file, lists it as missing, its images keeping what they -showed. Without a file system (the web), linked images show their previews. +showed. Without a file system (the web), linked images show their previews. A link whose path has a colon and no `/` +or `\` is read as a classic Mac OS path (`Disk:Folder:file.tif`), a form that older `.ai` files can hold. The link +keeps that path and is named by its last part. `links.info` gives that part as `fileName` and the rest as `location`, +and `links.relink {folder}`, the search of the document's folder and `links.findFiles` look for a file of that name. `links.findFiles {folder}` looks in an absolute folder and its subfolders, on separate threads, for the files of the active document's missing links, or of the images and placed documents `ids` whatever their status, and returns at once with an `id` and the search's `state` (`searching` while it runs). It finds the files with each linked file's name, in any letter case, and lists them best first as `{path, size, match, caseDiffers?}`: `same` when the file has the size and -hash saved with the link, `size` when it has the saved size and the link saved no hash (or the file is larger than 1 GB, +hash saved with the link, `size` when it has the saved size and the link saved no hash (or the file is larger than 1 GiB, which a search doesn't hash), else `name`. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that -differs, and a file with more matching names comes first; files that still tie are listed by path. `links.findFiles {}` +differs, and a file with more matching names comes first; files that still tie are listed by path. Before the +comparison, the saved path's parent-folder steps (`..`, or the empty components of a classic Mac `::` run) are resolved, +and `.` components in a slash path are skipped. `links.findFiles {}` returns the last search's state, and `{stop: true}` stops it. A search looks for at most 1,000 linked files, keeps the first 10 files of each one's name and up to 10 that are the same file, and ends once every linked file has its same file; it searches only the folders `text.findFontFiles` may search, with the same `maxSeconds`, depth and count limits. @@ -4981,7 +4993,8 @@ thread's first frame that holds text (which is selected when it was not) with th and Cut take. Typing, Delete and Cut replace the whole story as one undo step (`text.editRange` with `clear`, the other frames whose text goes), and a fill, stroke, `type.step` or Character or Paragraph panel change applies to the text of every frame (the Character panel sends `text.setRangeStyle {id, story: true}`, which styles every frame's text in one -undo step). A caret move or a click ends the story selection. +undo step). Remove Line Breaks, Remove Paragraph Breaks and Convert to Text also act on the text of every frame, as +one undo step. A caret move or a click ends the story selection. ```json {"name":"press_key","arguments":{"key":"A","mods":{"cmd":true}}} @@ -5428,6 +5441,10 @@ the type it changed, how many paragraphs were `converted`, and the characters `i `id`, the byte `at` which they went in (counted in the text before the change) and their `length` in bytes. While the Type tool edits, `text.convertListToText` ends its typing first and moves its anchor and caret past the characters inserted at or before them, whether the call comes from the menu, MCP or the control channel. +After Select All in a frame of threaded text, a call without `ids`, `id`, `start` or `end` converts every paragraph of +the story's frames that are neither locked nor hidden. While the story is selected, its locked and hidden frames are +not converted, even when `ids` names them, and neither is a paragraph whose text starts in one. When the call converts +all of its other frames, the whole story stays selected. In threaded type, when the caret's character moved to another frame, the Type tool edits that frame with the caret next to the same character, and that frame becomes the selection when it was not selected. @@ -6500,8 +6517,11 @@ glyph of its first character lands where it was drawn. line becomes a left-aligned paragraph whose leading is the distance from the baseline above, so the lines stay where they were. Character styles stay; the object takes the top-left piece's place and paint. Returns `{id, joined, lines}`. - `addon.cleanup.removeBreaks {kind, ids?}` removes the forced line breaks (`kind: "line"`) or paragraph returns - (`"paragraph"`) in the characters selected with a Type tool, else in all the text of the selected type. A break - between two words becomes a space; merged paragraphs take the first one's paragraph style. + (`"paragraph"`) in the characters selected with a Type tool, else in all the text of the selected type. After + Select All in a frame of threaded text, it removes them from the text of every frame of the story, as one undo step. + A break between two words becomes a space; merged paragraphs take the first one's paragraph style. The frames of a + threaded story, selected all together or through Select All, are read as one text, so a break at the end of one + frame before a word in the next one also becomes a space. - `addon.cleanup.splitText {}` works while a Type tool edits horizontal point or area type: the text before the selected characters, those characters and the text after them become point type objects (at a bare cursor, the text before and after it). Spaces at the ends of each piece go; a piece that starts inside a left-aligned line takes a @@ -6864,6 +6884,30 @@ The dialog lists every artboard with its number, name and size in the document's name; a click chooses one artboard, Shift-click adds a range and Cmd/Ctrl-click toggles one, and Select All / None act on the rows shown (rows hidden by the search stay chosen). It opens with the active artboard chosen and Overlapping. +`addon.select.byLinkStatus {status, ids?, add?, zoom?}` (Select Linked / Embedded / Missing / Modified and Select by +Link Status…, #5526) selects the image objects and placed documents whose link has a status, as `links.list` reports +it: `linked` (its file found unchanged; `links.list` says `ok`), `embedded`, `missing` or `modified` (its file changed +since it was read). `status` is one of them or a list of them (at least one; one listed twice counts once). `ids` picks +only among those objects (other objects among them are passed over); `add: true` adds them to the selection instead of +replacing it; `zoom: true` asks for Zoom to Selection afterwards, which the desktop app runs (`addon.arrange.zoomSelection`) +when something was selected, and which other callers get back as `zoom: true`. Objects that are hidden or locked, inside +a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the +isolated group or layer are left out and listed with the reason. Only the selection changes, so there is nothing to +undo. It returns `{count, selected: [ids] (bottom first), skipped: [{id, reason: hidden|locked|template|isolation}]}`. +A missing or unknown status, an id naming no object, or a value of the wrong type is an error, and the selection is left +as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.byLinkStatus","params":{"status":["missing","modified"],"zoom":true}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools and the Links panel menu have Select Linked, Select Embedded, +Select Missing and Select Modified, each off when no image has that status; with Shift held they add to the selection. +The status bar says what was selected and what was left out, e.g. "Selected 9 missing images; 3 more are hidden or +locked". Select by Link Status… lists every image and placed document with its name, status and format, searches by +name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select +selects the rows chosen, zooming to them when Zoom to Selection is on (the default). + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its @@ -7040,8 +7084,10 @@ image in `folder` (PNG, JPEG, TIFF, BMP, GIF, WebP, PSD; with `includeSubdirs`, `preset` (an `imageTrace.presets` name; Default by default; with `expand`, as Make and Expand), saves it into `destinationFolder` as `.` in `format` (`vectorcraft` by default; `svg`, `pdf`, `ai`, `eps`), with `-2`, `-3`… added when the name is taken so no file is replaced, and closes it again whether it traced or not; the active -document stays active. Images that can't be traced are listed in `failed` and the others are still traced. Up to 500 -images and 8 folder levels (a folder with more than 1,000 entries is refused); not on the web. The desktop app's Batch +document stays active. Images that can't be traced are listed in `failed` and the others are still traced. Optional +`format` and `preset` accept strings; `expand` and `includeSubdirs` accept true or false. Null and values of another +type return an error before any image is opened. Up to 500 images and 8 folder levels (a folder with more than 1,000 +entries is refused); not on the web. The desktop app's Batch Trace Folder asks for both folders (#4921). → `{traced: [{path, output}], failed: [{path, error}], format}` ```json diff --git a/docs/roadmap.md b/docs/roadmap.md index 6831863a9a..29ebd2df05 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,17 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Select by Artboards add-on selects by overlap, inside or outside several artboards; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence +Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. + +**PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. + +Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. + +**PR #3272 revision — 2026-11-04:** Group Selection component drags defer ancestor selection until a completed click, using current Direct Selection release handling; original Outline Stroke fills and newer selection behavior retained. Scores and estimates unchanged. + Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. **Feature evidence last updated:** 2026-11-03. @@ -28,8 +36,14 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | +| 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path (#5752); scores and estimates unchanged. | +| 2026-11-05 | minor | Layers panel: a layer whose Layer Options › Print is off shows its name italic, as the reference application shows non-printing layers, and keeps it while the row is dragged (#5739); scores and estimates unchanged. | | 2026-11-04 | minor | M7: Find Font's Replace With Font lists family and style rows with a search, and the list and the document's font list scroll on their own (#4972); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | +| 2026-11-04 | minor | M4: raster/PSD exports default to document resolution; CLI run/convert expose --ppi, matching the engine and MCP precedence. Scores and hours unchanged. | +| 2026-11-05 | minor | Panels: a floating panel window hides under a modal dialog and drops out of the top level under an open menu, so neither the Colour Picker or Recolor Artwork nor the menu bar is covered, and it comes back at its palette level after (#5238); scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset; Recent and Saved cards keep the units their document or preset was made in, and the built-in tabs still follow the chosen units (#2078). Scores and estimates unchanged. | | 2026-11-03 | minor | M1: Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot; estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 004188166e..0a0061b74e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,9 +1,17 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; Optical kerning spaces pairs by the font's own stem spacing instead of a fixed tight gap; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence +Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. + +**PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. + +Group Selection keeps an already selected component selected during a drag; a completed click still adds its next enclosing group. The current Direct Selection click/release machinery is shared, preserving compound-member picks, Shift deselection, isolation and masked-art dragging. Outline Stroke continues to preserve all original fills, including open contours; the change does not remove fills. Regressions: `group_selection_distinguishes_selected_leaf_drags_from_clicks` and `outline_fill_and_stroke_move_independently_with_group_selection` cover tool events, independent component movement and Undo/Redo. Scores and estimates unchanged. + +**PR #3272 revision — 2026-11-04:** Group Selection component drags defer ancestor selection until a completed click, using current Direct Selection release handling; original Outline Stroke fills and newer selection behavior retained. Scores and estimates unchanged. + Ligature caret stops use a font's GDEF contour-point positions in horizontal and vertical text. They use unhinted outlines at the default variation location; invalid point indices use the existing evenly divided fallback. Scores and estimates are unchanged. Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. @@ -23,6 +31,17 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Canvas: an image drawn larger than 1,024 pixels at the size it shows, with its colours made again (separated into ink planes, colorized or shown through Separations Preview), has them made only for the 1,024-pixel tiles in view, each kept for later frames (#4155). Zooming in to 50%, 100% and 200% on the file of #4155 went from 8.6–9.0 s to 0.78 s, 0.05 s and 0.05 s (measured, M3 Pro, one run each), with the same pixels. Scores and estimates unchanged. | +| 2026-11-05 | minor | Canvas: a document's first frame (opened, or its tab chosen) renders on the render worker instead of the UI thread; the window shows the document's paper and artboards until the art lands, and a frame ready within 16 ms shows at once. Opening the file of #4155 kept the UI thread busy for 8.7 s at a stretch, now at most 64 ms; a 50,000-path SVG 1.4 s, now 62 ms (measured, M3 Pro, one run each). Scores and estimates unchanged. | +| 2026-11-05 | minor | Canvas: an image drawn reduced in a CMYK document is shrunk to the size it shows before it is separated into ink planes, not separated at full size and then shrunk (#4155). On the 141-megapixel image of #4155 the first frame went from 9.2 s to 1.6 s, and the sharp frame after a pan from 3.9 s to 8 ms (measured, M3 Pro, one run each). The same pixels show within 5 levels; fine detail such as 1-pixel lines now shows its true average. Scores and estimates unchanged. | +| 2026-11-05 | minor | Effect dialogs: a hex colour parameter (Outer Glow's Color, Inner Glow's, Drop Shadow's) shows a swatch beside the field that follows typed hex values; a double-click opens the Color Picker over the dialog on that colour, and its OK fills the field while Cancel comes back unchanged (#5365); scores and estimates unchanged. | +| 2026-11-05 | minor | Libraries panel: a spot colour added to a library (from the selection or dragged from the Swatches panel) keeps its ink name, values and tint in the library file; used in any document, also a new one or after the original was closed, it links the paint to that document's spot swatch of the same name, adding it when the document has none of that colour, in one undo step (#5812). Test: `tests::library::a_spot_colour_stays_spot_in_another_document`. Scores and estimates unchanged. | +| 2026-11-05 | minor | Eyedropper colour sampling from a path or compound path with one visible stroke no longer rebuilds its path merely to choose among stroke layers. Multiple strokes still sample the topmost one that reaches the point; colours, scores and estimates are unchanged. | +| 2026-11-05 | minor | Adding a selected colour, gradient or pattern to a library measures the source object's geometry once rather than twice. Gradient placement, library contents, scores and estimates are unchanged. | +| 2026-11-05 | minor | Large drawings of solid-colour or pattern-filled paths and compound paths export to SVG faster when their unused geometric bounds are skipped. Gradients and outside-aligned stroke masks retain their placement; SVG output, scores and estimates are unchanged. | +| 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | +| 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path and a continued or redrawn path keeps the rest of the selection (#5752); scores and estimates unchanged. | +| 2026-11-05 | minor | Layers panel: a layer whose Layer Options › Print is off shows its name italic, as the reference application shows non-printing layers, and keeps it while the row is dragged (#5739); a printing layer's name is upright, and Print on again makes it upright again; scores and estimates unchanged. | | 2026-11-05 | minor | G12: Hyphenation › Default Language sets the language of new type unless Document Setup chose one, stored as a tag; each run hyphenates in its own language, English only so far, so 2 Preferences options stay unused (#394) | | 2026-11-05 | minor | Type Tools add-on: Release Type on a Path (a VectorCraft addition, #5532): evidence added; scores unchanged. | | 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `minAngle`/`maxAngle` round only the corners whose angle is in a range (#5545); evidence added; scores unchanged. | @@ -33,6 +52,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-05 | minor | Gradient panel: Delete Stop sits at the right end of the ramp, so it shows whenever the ramp does instead of under the stop fields, where a short panel hid it (#5403); scores and estimates unchanged | | 2026-11-04 | minor | Type core: a Type-range Copy or Cut publishes styled art alongside plain text, so canvas Paste keeps font family, size and color after editing ends (#5636); scores and estimates unchanged. | | 2026-11-04 | minor | Selection Tools add-on: Select by Artboards selects the objects overlapping, fully inside or fully outside several chosen artboards, from a dialog that lists, searches and multi-selects the artboards and fits one in the window on double-click (#5525, #5548, #5549, a VectorCraft addition); scores and estimates unchanged. | +| 2026-11-04 | minor | Raster/PSD defaults honor document resolution; CLI run/convert accept --ppi, matching MCP options.ppi precedence. Synthetic regressions added; scores and hours unchanged. | +| 2026-11-05 | minor | Floating panels keep out of the main window's way: hidden under a modal dialog, and out of the top level while a menu is open (#5238); scores and estimates unchanged. | | 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset, as the public page lists the pane's options for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units (#2078). Scores and estimates unchanged. | | 2026-11-04 | minor | Document Tools add-on (a VectorCraft addition): Batch Trace Folder under Object › Plug-ins (`addon.document.batchTraceFolder`, #4921); evidence added; scores unchanged. | | 2026-11-04 | minor | Object › Expand turns selected symbol instances into their art as Break Link places it, one level deep, with the Expand dialog's Fill and Stroke reaching that art. Scores and estimates unchanged. | @@ -183,7 +204,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, 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, in part); movements below the click threshold still select all; 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) | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, 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, in part); movements below the click threshold still select all; 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 | | 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** | | @@ -641,6 +662,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Tab does not stop on the regions that only the pointer uses: the custom title bar's background and the window's resize zones, the band at the top of a dialog that moves it, the Tools panel's grip, a flyout's and a floating strip's tear-off bar, the isolation bar's background, and the rulers and the box where they meet. - These dialog sliders, each beside a number field, respond to the keyboard: those of the effect, tool option, brush and transform dialogs, the Perspective Grid, the 3D dialogs, and the flattener options, which the Flattener Preview panel also shows. A click, or Tab, gives a slider the keyboard focus, and an outline shows it. Then → and ↑ step the field's number up to the next whole number and ← and ↓ step it down to the next whole number, Shift with an arrow and Page Up and Page Down step it by ten, and Home and End set the slider's first and last value; no step goes past either end. Screen readers' increment and decrement actions step the slider as → and ← do. The Color panel's, Swatch Options', the Navigator's and the Character panel's sliders, and the Color Picker's channel slider, respond only to the pointer. The keys follow the WAI-ARIA slider pattern (); the reference app's help does not describe keys on a dialog's slider, so the step sizes are VectorCraft's own. - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. + - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). @@ -705,6 +727,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. - The function key shortcuts for Brushes, Color, Layers, Info, Gradient, Stroke, Attributes, Graphic Styles, Appearance, Align, Transform, Pathfinder, Transparency, and Symbols activate a background tab on the first press, hide its expanded dock or floating group when that tab is in front, and restore the group with all its tabs together on the next press; in an icon column they open and close the flyout while keeping the icons. A reassigned chord keeps that behavior, and Window > a hidden sibling restores the group. - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). + - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`). - While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command. - On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut. - With the Artboard tool, Cmd/Ctrl+A after a click on a row of the Artboards panel selects every artboard, as the macOS menu bar's Select All does then; the active artboard stays active, and the art's selection does not change. After a press outside the panel's list, Cmd/Ctrl+A selects every object again. It used to select every object after a click in the panel too. Public reference: [Select artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/select-artboards.html). @@ -736,6 +759,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. While an opacity mask or a pattern is edited, a Shaper double-click on a Shaper Group in the mask or pattern art selects the original shape under the pointer without entering Construction mode, the Shaper Group's mode widget does not show, and a Shaper scribble, Release and Expand keep the editing layer isolated. @@ -830,7 +854,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live curve fitting in the Pencil Tool Options is on by default; while it is off, the path shown while a stroke is drawn joins the stroke's points with straight segments, and the release fits the curve, as [Pencil Tool Options](https://web.archive.org/web/20261002104400/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/pencil-tool-options.html) describes (`path.freehand` `fit`). In the Pencil and Paintbrush Tool Options, Edit selected paths within 0 px turns editing off, so a stroke that starts exactly on an end of a selected open path draws a new path; Close paths when ends are within 0 px turns closing off, so a stroke that ends exactly where it started stays open. Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). - Keep selected in the Pencil and Paintbrush Tool Options is on by default; while it is off, the path a stroke draws or continues is not selected afterwards and the rest of the selection stays as it was (`path.freehand` `keepSelected`). + Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). @@ -865,7 +889,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A bounding-box handle dragged with the Selection or Free Transform tool snaps what it moves as a dragged point snaps (#2054). With View › Snap to Grid on, it snaps to the nearest gridline, and with Snap to Pixel on, it snaps to whole pixels. With Smart Guides off and Snap to Point on, it snaps to the other objects' anchors and the ruler guides within the Snap to Point distance. With Smart Guides and Snap to Point both on, it lines up with the ruler guides as well as the other objects. Shift still keeps the proportions, and Alt still scales about the center. A user slice's edge or corner handle dragged with the Slice Selection tool snaps as the Slice tool's drag does. With View › Snap to Grid on, it snaps to the nearest gridline, and with Snap to Pixel on, it snaps to whole pixels. Otherwise, with Smart Guides on, it lands on or lines up with the anchors, centers and edges of the art and the artboards, and with Smart Guides off and Snap to Point on, it snaps to the art's anchors and the ruler guides within the Snap to Point distance. Then a ruler guide within 5 px, shown and unlocked, moves the side or corner onto it. Shift still keeps the proportions, and Alt still resizes about the center. View › Snap to Glyph: with Smart Guides on, a point drawn near a single line of live type lands on its glyphs' anchor points and lines up with its baseline, its x-height and the edges of each character's advance width (proximity guides), as well as the glyph bounds. In rotated type these guides run at the type's angle, and type of one glyph also has angular guides along its slanted straight segments. A paragraph shows glyph bounds only. - Snap to Glyph options (#4232, [Snap to Glyph options](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph-options.html)): the Character panel menu's Show Snap to Glyph Options (Hide Snap to Glyph Options) shows a Snap to Glyph section in the panel, with or without type selected, with a checkbox for each kind of guide: Baseline, x-height, Glyph Bounds, Proximity Guides (the edges of each character's width), Angular Guides and Anchor Point. Each off takes its guides away and leaves the others (`view.snapToGlyph.options`, the `glyphSnap` preference group, all on by default). Angular Guides covers a glyph's slanted strokes and every guide of rotated type, which runs at its angle; the boxes are dimmed while View › Snap to Glyph is off (VectorCraft choices; the page settles neither). Tested in `crates/tools/src/guides/tests.rs`, `crates/ui-egui/src/panels/character/tests.rs` and `crates/engine/src/tests/prefs.rs`. + Snap to Glyph options (#4232, [Snap to Glyph options](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph-options.html)): the Character panel menu's Show Snap to Glyph Options (Hide Snap to Glyph Options) shows a Snap to Glyph section in the panel, with or without type selected, with a checkbox for each kind of guide: Baseline, x-height, Glyph Bounds, Proximity Guides (the edges of each character's width), Angular Guides and Anchor Point. Each off takes its guides away and leaves the others (`view.snapToGlyph.options`, the `glyphSnap` preference group, all on by default). Angular Guides covers a glyph's slanted strokes and every guide of rotated type, which runs at its angle; the boxes are dimmed while View › Snap to Glyph is off, and the section starts with a Snap to Glyph checkbox for it (VectorCraft choices; the page settles neither). Showing the section scrolls the panel to it, since it comes after every character attribute (#5273). Tested in `crates/tools/src/guides/tests.rs`, `crates/ui-egui/src/panels/character/tests.rs` and `crates/engine/src/tests/prefs.rs`. - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). @@ -1059,6 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. + - **Colour swatches in effect dialogs (#5365):** a colour parameter of an effect dialog (Outer Glow's Color, Inner Glow's, Drop Shadow's) shows a swatch beside its hex field that follows the value typed in it; a double-click on the swatch opens the Color Picker over the dialog on that colour, whose OK fills the field and whose Cancel comes back unchanged, and the dialog previews the colour when it returns (`dialogs::effect` test `outer_glow_colour_swatch_opens_the_color_picker`). - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. @@ -1112,7 +1137,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Neutral wording:** labels, MCP tool text, docs and packaging use neutral names, and `cargo xtask brands` (part of `cargo xtask ci`) fails on vendor names. - **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize. - The Libraries panel holds gradients and patterns: its + button adds the selection's fill or stroke gradient or pattern, a gradient or pattern swatch dragged from the Swatches panel is added, and a click paints the selection through the active Fill/Stroke proxy, a pattern bringing its definition and swatch into the document. + The Libraries panel holds gradients and patterns: its + button adds the selection's fill or stroke gradient or pattern, a gradient or pattern swatch dragged from the Swatches panel is added, and a click paints the selection through the active Fill/Stroke proxy, a pattern bringing its definition and swatch into the document. A spot colour stays a spot colour: the library keeps its ink name and tint, and using it in any document links the paint to that document's spot swatch of that name, adding it when missing (#5812). Object › Lock › All Artwork Above and Object › Hide › All Artwork Above deselect the selected objects they lock or hide, the key object included. Object › Hide › Unselected Artwork (Cmd/Ctrl+Alt+Shift+3, `object.hide.unselected`) hides, in one undo step, every object Select All takes that is not selected and holds no selected object; the members of a group that holds a selected object are hidden one by one, and Object › Show All shows them again. In isolation mode it hides only unselected objects inside the isolated object. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Hide unselected artwork". Cmd/Ctrl+Alt+Shift+2 (`object.lock.unselected`) locks unselected artwork in one undo step and has no Object › Lock menu item. It locks unselected members of partly selected groups, clipping groups and compound paths, and unselected guides while Lock Guides is on. In ordinary isolation mode it locks only unselected art inside the isolated object. Object › Unlock All unlocks all locked art in the document, or inside the isolated object in isolation mode. The [public shortcut page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) calls the action "Lock all deselected artwork". @@ -1167,10 +1192,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import's style cascade, used for hidden objects, non-scaling strokes and type, tests each element only against the `