diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 07b3c6b7fe..bbb0b8d792 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,6 +82,7 @@ jobs: WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }} WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} diff --git a/ASSETS.md b/ASSETS.md index e4a17c7640..b6f5fa007f 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index ae8a3ee6c7..fcb4c1124a 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", diff --git a/ROADMAP.md b/ROADMAP.md index 16bd8b1dab..0088ac5a03 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,8 @@ # VectorCraft Roadmap +- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. +- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. + - Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. @@ -11,7 +14,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **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; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -131,6 +134,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). @@ -219,6 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | | 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | | 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | 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 59b30b7649..b9be306898 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -176,8 +176,7 @@ mod win { use clipboard_win::{formats, options::NoClear, raw}; use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, text_of, - windows_formats, + BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -211,8 +210,6 @@ mod win { pub struct Clipboard { /// The clipboard's sequence number right after our last write. seq: Option, - /// The text of our last write. - text: Option, } impl SystemClipboard for Clipboard { @@ -243,18 +240,17 @@ mod win { } } self.seq = raw::seq_num(); - self.text = text_of(flavours); result } fn holds_ours(&mut self) -> bool { - if self.seq.is_some() && raw::seq_num() == self.seq { - return true; - } - // A clipboard manager may have copied our data again as its own. - let Some(ours) = self.text.as_deref() else { return false }; - let Ok(_open) = clipboard_win::Clipboard::new_attempts(10) else { return false }; - read_one(TEXT).and_then(ClipboardRead::flavour).is_some_and(|f| f.data == ours.as_bytes()) + // The same text copied later by another app is a different clipboard entry. A + // clipboard manager that republishes our data is also a new entry. + self.seq.is_some() && raw::seq_num() == self.seq + } + + fn change_count(&mut self) -> Option { + raw::seq_num().map(|n| u64::from(n.get())) } fn read(&mut self, mimes: &[&'static str]) -> Option { @@ -982,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 { @@ -997,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. @@ -1036,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()); @@ -1044,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/control_server.rs b/apps/vectorcraft/src/control_server.rs index 508ab0daf2..1a44eba288 100644 --- a/apps/vectorcraft/src/control_server.rs +++ b/apps/vectorcraft/src/control_server.rs @@ -152,6 +152,7 @@ fn spawn_connection( fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl FnMut(String, Value) -> Option) { let Ok(read) = stream.try_clone() else { return }; + let closer = stream.try_clone().ok(); let read = DeadlineReader::new(read, timeouts.idle, timeouts.line); // Replies reach the writer in [`REPLY_CHUNK`] pieces ([`write_line`]), so checking the remaining // budget costs one socket option call per piece, not one per JSON token. @@ -166,6 +167,33 @@ fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl Fn }, DeadlineWriter::begin_reply, ); + if let Some(s) = closer { + close_gracefully(s); + } +} + +/// How long [`close_gracefully`] waits for the peer to close its side. +const CLOSE_DRAIN: Duration = Duration::from_secs(1); + +/// The most [`close_gracefully`] reads from a peer that keeps sending. +const MAX_DRAIN: usize = 1 << 20; + +/// Ends a connection: no more replies (the peer reads them all, then end of stream), then what the +/// peer still sends is read and dropped until it closes too, for at most [`CLOSE_DRAIN`] and +/// [`MAX_DRAIN`] bytes. On Windows, dropping a socket with unread input resets the connection, and +/// the reset can discard replies the peer has not read yet. +fn close_gracefully(mut s: TcpStream) { + // Each step is best effort: a peer that is already gone needs none of them. + let _ = s.shutdown(std::net::Shutdown::Write); + let _ = s.set_read_timeout(Some(CLOSE_DRAIN)); + let deadline = std::time::Instant::now() + CLOSE_DRAIN; + let (mut buf, mut left) = ([0u8; 4096], MAX_DRAIN); + while left > 0 && std::time::Instant::now() < deadline { + match s.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => left = left.saturating_sub(n), + } + } } /// One parsed line. diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs index d991fd6028..7aa290e01f 100644 --- a/apps/vectorcraft/src/control_server/tests.rs +++ b/apps/vectorcraft/src/control_server/tests.rs @@ -334,13 +334,12 @@ fn tcp_connection_is_closed_after_junk() { let addr = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { let (s, _) = listener.accept().unwrap(); - let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(json!({"ok": true}))); + serve_socket(s, ConnectionTimeouts::default(), |_, _| Some(json!({"ok": true}))); }); let mut c = TcpStream::connect(addr).unwrap(); c.set_read_timeout(Some(WAIT)).unwrap(); - // Nothing after the junk line: on Windows, closing a socket with unread input resets the - // connection, and the reset can discard the reply before the client reads it. + // The server closes gracefully ([`close_gracefully`]): the client reads both replies and then + // the end of the stream, not a reset. c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap(); let mut text = String::new(); c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection 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/assets/icons/dc-contour.svg b/assets/icons/dc-contour.svg new file mode 100644 index 0000000000..61c1f2ed82 --- /dev/null +++ b/assets/icons/dc-contour.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 179c0de516..a62dce9ec5 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -132,9 +132,10 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) { } /// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's -/// opacity (how far the art mixes towards it). `None` for an unstained instance. +/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one +/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links. pub fn stain(inst: &Node) -> Option<(Color, f32)> { - let f = inst.appearance.fill().filter(|f| f.visible)?; + let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?; Some((f.paint.color()?, f.opacity)) } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 7871b61af6..22aad6603c 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -764,6 +764,26 @@ fn stain_mixes_type_strokes_too() { assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); } +/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its +/// swatch links. +#[test] +fn a_fill_with_no_opacity_leaves_the_symbol_art_linked() { + let spot = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4), swatch: Some("Spot".into()), tint: 1.0 }; + let art = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(spot.clone(), Paint::None, 0.0)); + let mut inst = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + if let Some(f) = inst.appearance.fill_mut() { + f.opacity = 0.0; + } + assert_eq!(stain(&inst), None); + assert_eq!(instance_art(&art, &inst).appearance.fill_paint(), spot); + // Any opacity above 0 still stains. + if let Some(f) = inst.appearance.fill_mut() { + f.opacity = 0.01; + } + assert_ne!(instance_art(&art, &inst).appearance.fill_paint(), spot); +} + #[test] fn library_defaults_store_and_find() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 794f92aeea..8e947c1436 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -151,16 +151,23 @@ pub struct GradientStop { /// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint. #[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")] pub tint: f32, + /// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a + /// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix + /// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plates: Option<[f32; 4]>, } impl GradientStop { /// An opaque, unlinked stop of `color` at `offset` with a centred midpoint. pub fn new(offset: f32, color: Color) -> Self { - Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 } + Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None } } - /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked. + /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without + /// process plates. pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) { self.color = color; + self.plates = None; (self.swatch, self.tint) = match link { Some((n, t)) => (Some(n), t), None => (None, 1.0), 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/document_guides.rs b/crates/doc/src/document_guides.rs index 43e1c4c920..c24c18bc4d 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -6,9 +6,15 @@ impl Document { /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol /// instances measured by their art ([`Node::geometric_bounds_with`]). pub fn bounds_of(&self, ids: &[NodeId], visual: bool) -> Option { - let symbols = self.symbol_boxes(); + self.bounds_of_with(ids, visual, &self.symbol_boxes()) + } + + /// [`bounds_of`](Document::bounds_of) measuring symbol instances from `symbols`, a cache shared + /// across calls: measuring many instances one by one otherwise measures their art again for + /// each. + pub fn bounds_of_with(&self, ids: &[NodeId], visual: bool, symbols: &crate::SymbolBoxes) -> Option { ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| { - vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(&symbols) } else { n.geometric_bounds_with(&symbols) }) + vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(symbols) } else { n.geometric_bounds_with(symbols) }) }) } @@ -79,31 +85,77 @@ impl Document { /// by its clipping path where that paints). Guides (paths made into guides too) aren't artwork /// (Delete Empty Artboards). pub fn artboard_has_art(&self, rect: Rect) -> bool { + self.art_meets(&self.symbol_boxes(), rect, true) + } + + /// Is there a rect in `rects` (artboards) with no artwork on it, by [`Document::artboard_has_art`]? + /// The symbols are measured once for all of them. A first pass rules art out by a quick box + /// (paths and compound paths: their control points grown by the farthest their strokes reach), + /// so a rect away from every path is found without measuring along any; only when every rect + /// may hold art is each one measured. + pub fn any_artboard_without_art(&self, rects: impl IntoIterator) -> bool { + let rects: Vec = rects.into_iter().collect(); + let symbols = self.symbol_boxes(); + rects.iter().any(|r| !self.art_meets(&symbols, *r, false)) || rects.iter().any(|r| !self.art_meets(&symbols, *r, true)) + } + + /// [`Document::artboard_has_art`] of `rect` when `exact`. Otherwise whether art may lie on it: + /// paths and compound paths count when their quick box meets it, so a false answer is exact and + /// a true one may not be. + fn art_meets(&self, symbols: &SymbolBoxes, rect: Rect, exact: bool) -> bool { // As in `art_on_artboard`: a millionth of a point covers rounding at the edges. let rect = rect.inflate(1e-6, 1e-6); fn meets(b: Option, r: Rect) -> bool { b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1) } - fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool { + /// A box that holds the visual bounds of a path, or of a compound path of paths, found + /// without measuring along its shape: its control points' box grown by the farthest its + /// strokes reach ([`crate::Appearance::outset`], as in [`Node::reach_bounds`]), with a + /// margin for rounding. None for other objects, and when the reach is not finite. + fn quick_box(c: &Node) -> Option { + let b = match &c.kind { + NodeKind::Path { path, .. } => path.control_bounds()?, + NodeKind::Compound { children, .. } => children.iter().try_fold(None, |acc, m| { + let NodeKind::Path { path, .. } = &m.kind else { return None }; + Some(vectorcraft_geom::union_opt(acc, path.control_bounds())) + })??, + _ => return None, + }; + let o = c.appearance.outset(); + let o = o * (1.0 + 1e-9) + 1e-6; + o.is_finite().then(|| b.inflate(o, o)) + } + /// Does `c`'s visual box meet `rect`? Without `exact`, a quick box that meets it answers yes. + fn art_box_meets(c: &Node, s: &SymbolBoxes, rect: Rect, exact: bool) -> bool { + match quick_box(c).map(|b| meets(Some(b), rect)) { + Some(false) => false, + Some(true) if !exact => true, + _ => meets(c.visual_bounds_with(s), rect), + } + } + fn has(c: &Node, s: &SymbolBoxes, rect: Rect, exact: bool) -> bool { match &c.kind { NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { let Some((clip, rest)) = children.split_first() else { return false }; let paint = clip.clip_paint(); - if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) { + if (paint.fill.is_some() || paint.stroke.is_some()) && art_box_meets(clip, s, rect, exact) { return true; } + if !exact { + // The part of `rect` inside the clip's box lies inside `rect`. + return rest.iter().any(|m| has(m, s, rect, false)); + } // The members show only inside the clip's box. let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false }; let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1)); - rest.iter().any(|m| has(m, s, inside)) + rest.iter().any(|m| has(m, s, inside, true)) } - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect, exact)), NodeKind::Path { guide: true, .. } => false, - _ => meets(c.visual_bounds_with(s), rect), + _ => art_box_meets(c, s, rect, exact), } } - let symbols = self.symbol_boxes(); - self.layers.iter().any(|l| has(l, &symbols, rect)) + self.layers.iter().any(|l| has(l, symbols, rect, exact)) } /// The art that moves, scales or is cut with artboard `index`: [`Document::art_on_artboard`] diff --git a/crates/doc/src/halftone_radii.rs b/crates/doc/src/halftone_radii.rs new file mode 100644 index 0000000000..a96707c48e --- /dev/null +++ b/crates/doc/src/halftone_radii.rs @@ -0,0 +1,277 @@ +//! Color Halftone's Max Radius was a distance in points until documents of version 3; since then +//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it +//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and +//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::limits::FORMAT_VERSION; +use crate::{Appearance, Document, Effect, Node}; + +/// The first document version whose Color Halftone radii are in pixels. +const PIXEL_RADII_SINCE: u32 = 3; +const HALFTONE: &str = "pixelate.colorHalftone"; +const RADIUS: &str = "maxRadius"; +/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s +/// `DOC_KEY`), whose art can carry effects. +const BRUSHES: &str = "brushes"; +/// The radius (points) an older document's halftone without one drew with. +const OLD_DEFAULT: f64 = 8.0; +/// The range the radius was kept within in points, and is kept within in pixels. +const RANGE: std::ops::RangeInclusive = 4.0..=127.0; + +impl Document { + /// Saved before version 3: each Color Halftone's Max Radius in points becomes the pixels of + /// the document's raster effects resolution that draw the same dots, within the 4 to 127 px + /// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws + /// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and + /// graphic styles. + pub fn migrate_halftone_radii(&mut self) { + if self.version >= PIXEL_RADII_SINCE { + return; + } + self.version = FORMAT_VERSION; + let k = self.raster_ppi() / 72.0; + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// For a file saved for an app before version 3 (every native file version before today's): + /// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots, + /// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high + /// resolution, draws bigger dots there), and the document becomes version 2, so reopening the + /// file here converts them back. + pub fn halftone_radii_to_points(&mut self) { + if self.version < PIXEL_RADII_SINCE { + return; + } + self.version = PIXEL_RADII_SINCE - 1; + let k = 72.0 / self.raster_ppi(); + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// `fix` each effect in the art, symbols, patterns (and the one being edited as it was), graph + /// designs, opacity masks, Shaper edits, graphic styles and brush definitions that use a Color + /// Halftone. + fn each_halftone(&mut self, fix: &mut dyn FnMut(&mut Effect)) { + for l in &mut self.layers { + node(l, fix); + } + for s in &mut self.symbols { + node(&mut s.art, fix); + } + // Pattern editing is saved with the pattern as it was, which Cancel puts back. + for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) { + for a in &mut p.art { + node(a, fix); + } + } + for g in &mut self.graph_designs { + node(&mut g.art, fix); + } + if self.graphic_styles.iter().any(|s| has_halftone(&s.appearance)) { + for s in self.graphic_styles.iter_mut() { + appearance(&mut s.appearance, fix); + } + } + if let Some(b) = self.unknown.get_mut(BRUSHES) { + brushes(b, fix); + } + } +} + +/// `fix` each Color Halftone in JSON `v` (brush definitions): every object whose `id` is +/// [`HALFTONE`] is a serialized [`Effect`] (object ids are numbers). +fn brushes(v: &mut Value, fix: &mut dyn FnMut(&mut Effect)) { + match v { + Value::Object(m) if m.get("id").and_then(Value::as_str) == Some(HALFTONE) => { + let params = m.get("params").cloned().unwrap_or(Value::Null); + let mut e = Effect { id: HALFTONE.into(), params, visible: true }; + fix(&mut e); + m.insert("params".into(), e.params); + } + Value::Object(m) => m.values_mut().for_each(|v| brushes(v, fix)), + Value::Array(a) => a.iter_mut().for_each(|v| brushes(v, fix)), + _ => {} + } +} + +/// `e`'s radius times `k` (pixels a point, or points a pixel), within the effect's range, when it +/// is a Color Halftone. Its default is 8 in either unit. +fn rescale(e: &mut Effect, k: f64) { + if e.id != HALFTONE { + return; + } + let pt = e.params.get(RADIUS).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(OLD_DEFAULT); + let px = pt.clamp(*RANGE.start(), *RANGE.end()) * k; + if !e.params.is_object() { + e.params = Value::Object(Default::default()); + } + e.params[RADIUS] = json!(px.clamp(*RANGE.start(), *RANGE.end())); +} + +fn has_halftone(a: &Appearance) -> bool { + a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).any(|e| e.id == HALFTONE) +} + +fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) { + for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + fix(e); + } +} + +/// Fix the effects of `n`'s subtree, its opacity masks and its Shaper edits (copying only what +/// changes). +fn node(n: &mut Arc, fix: &mut dyn FnMut(&mut Effect)) { + let n = Arc::make_mut(n); + if has_halftone(&n.appearance) { + appearance(&mut n.appearance, fix); + } + if let Some(x) = n.extras_if_any() { + if let Some(m) = x.mask.as_mut() { + node(&mut m.art, fix); + } + // A Shaper Group's face and edge edits paint with appearances of their own. + if let Some(s) = x.shaper.as_mut() { + let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut()); + for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) { + appearance(p, fix); + } + } + } + if let Some(ch) = n.children_mut() { + for c in ch { + node(c, fix); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn halftone(radius: Option) -> Effect { + let params = radius.map_or_else(|| json!({"channel1": 108.0}), |r| json!({"maxRadius": r, "channel1": 108.0})); + Effect { id: HALFTONE.into(), params, visible: true } + } + + fn radius(e: &Effect) -> f64 { + e.params[RADIUS].as_f64().unwrap() + } + + #[test] + fn older_radii_become_the_pixels_that_draw_the_same_dots() { + for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] { + let mut e = halftone(Some(pt)); + rescale(&mut e, ppi / 72.0); + assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e)); + assert_eq!(e.params["channel1"], json!(108.0), "the angles stay"); + } + // A radius left out drew at the old default, 8 pt. + let mut e = halftone(None); + rescale(&mut e, 300.0 / 72.0); + assert!((radius(&e) - 33.333333333333336).abs() < 1e-9); + // Other effects keep their parameters. + let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true }; + rescale(&mut blur, 300.0 / 72.0); + assert_eq!(blur.params, json!({"radius": 8.0})); + } + + #[test] + fn only_documents_before_version_3_are_converted_once() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(8.0))); + d.graphic_styles.push(style); + let fresh = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, fresh, "a new document's radii are already pixels"); + d.version = 1; + d.migrate_halftone_radii(); + assert_eq!(d.version, FORMAT_VERSION); + let r = d.graphic_styles.last().map(|s| radius(&s.appearance.effects[0])).unwrap(); + assert!((r - 33.333333333333336).abs() < 1e-9, "{r}"); + let once = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, once, "converted documents are left alone"); + } + + #[test] + fn radii_go_back_to_points_for_an_older_app_and_return_unchanged() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(100.0))); + style.appearance.effects.push(halftone(Some(4.0))); + d.graphic_styles.push(style); + let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap(); + d.halftone_radii_to_points(); + assert_eq!(d.version, 2, "reopened here, it converts back"); + assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0)); + assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes"); + let points = d.clone(); + d.halftone_radii_to_points(); + assert_eq!(d, points, "already in points"); + d.migrate_halftone_radii(); + assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0)); + } + + /// Shaper face and edge edits paint with appearances of their own, and brush definitions keep + /// their art as JSON: their radii convert both ways too. + #[test] + fn shaper_edits_and_brushes_are_converted_both_ways() { + use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec}; + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + d.version = 1; + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let face = FaceEdit { + selector: FaceSelector { sources: vec![0], anchor: vectorcraft_geom::Point::ZERO }, + erase: false, + erase_edges: false, + paint_source: None, + merge: None, + paint: Some(look), + }; + let mut shaper = Node::group(d.alloc_id(), vec![]); + shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] })); + let l = d.layers[0].id; + d.insert(Some(l), 0, shaper).unwrap(); + let effect = serde_json::to_value(halftone(Some(8.0))).unwrap(); + d.unknown.insert(BRUSHES.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [effect]}}}])); + let radii = |d: &Document| { + let shaper = d.layers[0].children().and_then(|c| c.first()).cloned().unwrap(); + let paint = shaper.extras().shaper.as_ref().and_then(|s| s.faces[0].paint.clone()).unwrap(); + let brush = d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"][RADIUS].as_f64().unwrap(); + (radius(&paint.effects[0]), brush) + }; + d.migrate_halftone_radii(); + let (face, brush) = radii(&d); + assert!((face - 33.333333333333336).abs() < 1e-9, "the face edit: {face}"); + assert!((brush - 33.333333333333336).abs() < 1e-9, "the brush: {brush}"); + assert_eq!(d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"]["channel1"], json!(108.0)); + d.halftone_radii_to_points(); + let (face, brush) = radii(&d); + assert!((face - 8.0).abs() < 1e-9 && (brush - 8.0).abs() < 1e-9, "back in points: {face}, {brush}"); + } + + #[test] + fn the_pattern_being_edited_is_converted_as_it_was() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let id = d.alloc_id(); + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let tile = Arc::new(Node::path(id, square, look)); + let original = Some(crate::PatternDef::new("Tile", vec![tile])); + d.pattern_edit = Some(crate::PatternEdit { pattern: "Tile".into(), layer: crate::NodeId(0), original }); + d.version = 1; + d.migrate_halftone_radii(); + let art = &d.pattern_edit.as_ref().unwrap().original.as_ref().unwrap().art[0]; + assert!((radius(&art.appearance.effects[0]) - 33.333333333333336).abs() < 1e-9, "the tile Cancel puts back"); + } +} diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index cb972b94f8..8b498fd3d7 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -508,8 +508,9 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && let Some(isolated) = doc.node(scope) && let Some(mut chain) = doc.ancestry(scope) { - // Isolated before its artboard was locked: nothing in it hits. - if locks.holds_id(scope) { + // Isolated before its artboard, or its layer or a group around it, was locked or hidden: + // nothing in it hits (#5309). + if !doc.is_editable_with(&locks, scope) { return None; } if isolated.is_container() { @@ -893,6 +894,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh let mut out = Vec::new(); // `tops` pairs each object with the part of `r` in which the marquee can touch it. let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the + // marquee touches none of it, as clicks don't (#5309). + Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match (s.children(), marquee_in(s, r)) { (Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), (Some(_), None) => vec![], diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2a51b662b3..988df4c511 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ pub mod corners; pub mod depth; pub mod dimension; pub mod graph; +mod halftone_radii; pub mod hit; mod id_index; pub mod inks; @@ -324,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/limits.rs b/crates/doc/src/limits.rs index 86c2e802a7..240672cca7 100644 --- a/crates/doc/src/limits.rs +++ b/crates/doc/src/limits.rs @@ -14,8 +14,10 @@ pub enum DocError { } /// The document version new documents get. Version 2: a positive Twist angle turns clockwise -/// ([`crate::twist`]). -pub const FORMAT_VERSION: u32 = 2; +/// ([`crate::twist`]). Version 3: Color Halftone's Max Radius is in pixels of the raster effects +/// resolution (older documents are converted on opening, +/// [`crate::Document::migrate_halftone_radii`]). +pub const FORMAT_VERSION: u32 = 3; /// Node, slice and asset ids are handed out below this: no document gets near it by counting, so /// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). 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/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 1af9fb2500..f31f942ce9 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -606,6 +606,25 @@ impl Node { } } + /// The paint behind the Fill (or Stroke) proxy, the one [`Node::proxy_paint`] gives, without its + /// map and box: the object is not measured, so a long path costs no more than a short one. + pub fn proxy_paint_only(&self, stroke: bool, item: Option) -> Option<&vectorcraft_color::Paint> { + let item = self.appearance.item_of_kind(item, !stroke); + if item.is_none() + && !stroke + && let Some(c) = self.extras().colorize.as_deref() + { + return Some(c); + } + if item.is_none() + && let NodeKind::Text(t) = &self.kind + { + let st = &t.runs.first()?.style; + return Some(if stroke { &st.stroke } else { &st.fill }); + } + if stroke { self.appearance.stroke_at(item).map(|s| &s.paint) } else { self.appearance.fill_at(item).map(|f| &f.paint) } + } + /// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates /// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits. pub fn proxy_gradient(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> { diff --git a/crates/doc/src/orient.rs b/crates/doc/src/orient.rs index 114a152909..e524d6ca37 100644 --- a/crates/doc/src/orient.rs +++ b/crates/doc/src/orient.rs @@ -125,9 +125,19 @@ impl Document { if angle == 0.0 { return self.bounds_of(ids, visual).map(OrientedBox::aligned); } + self.oriented_bounds_with(ids, visual, &self.symbol_boxes()) + } + + /// [`oriented_bounds`](Document::oriented_bounds) measuring symbol instances from `symbols`, + /// a cache shared across calls: measuring many instances one by one otherwise measures their + /// art again for each. + pub fn oriented_bounds_with(&self, ids: &[NodeId], visual: bool, symbols: &crate::SymbolBoxes) -> Option { + let angle = self.bbox_angle(ids); + if angle == 0.0 { + return self.bounds_of_with(ids, visual, symbols).map(OrientedBox::aligned); + } let to_local = OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse(); - let symbols = self.symbol_boxes(); - let rect = ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| union_opt(acc, n.bounds_in(&symbols, to_local, visual)))?; + let rect = ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| union_opt(acc, n.bounds_in(symbols, to_local, visual)))?; Some(OrientedBox { angle, rect }) } } diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index 12965821bc..0c4ef497f3 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -2,7 +2,7 @@ //! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes //! up to the miter limit, projecting caps and arrowheads. -use vectorcraft_geom::bez::{CORNER_COS, kink, segments, subpaths, tangent, unit}; +use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit}; use vectorcraft_geom::hit::fill_contains; use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveNearest}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathSeg, Point, Rect, Shape, Vec2}; @@ -16,12 +16,7 @@ const ARCLEN_ACCURACY: f64 = 1e-3; /// The segments of a subpath that have length (zero-length ones, all of whose points coincide, /// have no direction). fn drawn(els: &[vectorcraft_geom::PathEl]) -> Vec { - let moves = |s: &PathSeg| match s { - PathSeg::Line(l) => l.p1 != l.p0, - PathSeg::Quad(q) => q.p1 != q.p0 || q.p2 != q.p0, - PathSeg::Cubic(c) => c.p1 != c.p0 || c.p2 != c.p0 || c.p3 != c.p0, - }; - segments(els).into_iter().filter(moves).collect() + segments(els).into_iter().filter(has_length).collect() } /// The open subpath ends of `segs`: (point, unit direction out of the path) at its start and end. @@ -166,6 +161,47 @@ impl StrokeLayer { out.union(bounds.inflate(side_max, side_max)) } + /// The tip of the miter spike this stroke paints where segment `b` follows segment `a` in a + /// subpath of its path (`closed`: a closed one), both with length ([`has_length`]), or `None` + /// when the join is not a miter, the path does not turn there or the miter limit bevels it. + pub fn miter_tip(&self, closed: bool, a: &PathSeg, b: &PathSeg) -> Option { + let side = self.side_reach(closed); + if self.join != LineJoin::Miter || side <= 0.0 { + return None; + } + miter(a.end(), tangent(a, 1.0), tangent(b, 0.0), side, self.miter_limit).map(|[_, tip, _]| tip) + } + + /// [`Self::bounds_on`] with the miter spikes' tips taken from `tips`, the box of the tips of + /// every joint of `bp` ([`Self::miter_tip`]) or `None` when there are none, instead of measured + /// along `bp`. It measures the projecting caps and arrowheads as [`Self::bounds_on`] does. + pub fn bounds_with_tips(&self, bp: &BezPath, bounds: Rect, tips: Option) -> Rect { + let els = bp.elements(); + let mut out = tips.map_or(bounds, |t| bounds.union(t)); + let mut side_max: f64 = 0.0; + // Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere. + let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed); + for (r, closed) in subpaths(bp) { + let side = self.side_reach(closed); + side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side }); + if side <= 0.0 { + continue; + } + if self.cap == LineCap::Square && !closed { + let segs = drawn(&els[r]); + for (at, dir) in ends(&segs).into_iter().flatten() { + let n = Vec2::new(-dir.y, dir.x) * side; + out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n); + } + } + } + for (at, _, end) in head_ends(self, bp) { + let r = self.head_reach(end); + out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r))); + } + out.union(bounds.inflate(side_max, side_max)) + } + /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and /// outside strokes of closed paths count on their own side only (and within `tol` of the /// path); a width profile counts at its width where `p` is nearest. @@ -271,13 +307,21 @@ impl Appearance { pub fn stroked_bounds(&self, bounds: Rect, bp: impl FnOnce() -> BezPath) -> Rect { let mut path = Some(bp); let mut shape = None; + self.stroked_bounds_by(bounds, |s| { + let bp: &BezPath = shape.get_or_insert_with(|| path.take().map(|f| f()).unwrap_or_default()); + s.bounds_on(bp, bounds) + }) + } + + /// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape + /// (miter spikes, projecting caps, arrowheads or an alignment) given by `shaped`. + pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect { self.painted_strokes().fold(bounds, |acc, s| { if !s.needs_shape() { let o = s.side_reach(false); return acc.union(bounds.inflate(o, o)); } - let bp: &BezPath = shape.get_or_insert_with(|| path.take().map(|f| f()).unwrap_or_default()); - acc.union(s.bounds_on(bp, bounds)) + acc.union(shaped(s)) }) } diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 731480fed0..67ccb60a44 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -143,8 +143,11 @@ pub struct CharStyle { pub no_break: bool, /// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these /// characters are shaped in, so that the font uses that language's forms (OpenType `locl`). - /// `None`: the default language, English: USA, shaped without a language. New type takes the - /// document's language (Document Setup). Saved only when set. + /// `None`: the default language, English: USA, shaped without a language, which is what text + /// saved without one reads as. A tag the list doesn't have, from a file, is kept and has no + /// hyphenation. New type takes the document's language (Document Setup), else the default + /// language of Preferences › Hyphenation. Saved only when set. Each run hyphenates in its own + /// language (`vectorcraft_text::hyphen`). #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option, /// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index bab9ee6ed1..d1560ec7ca 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -43,13 +43,25 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool { } /// The range in points that distance parameter `key` of effect `id` is kept within, as its -/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none. +/// parameter documentation gives it (`{edgeWidth: pt 1..14 (2), …}`); `None` when it gives none. pub fn length_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "pt") +} + +/// The range of parameter `key` of effect `id` when it is a size in pixels of the Document Raster +/// Effects resolution (`{maxRadius: px 4..127 (8), …}`), which no unit setting changes and which +/// stays in pixels when the resolution does; `None` for other parameters. +pub fn raster_px_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "px") +} + +/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). +fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; - rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt ")) + rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ') })?; let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?; let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches(',').parse::().ok()?); @@ -81,7 +93,6 @@ fn lengths_of(id: &str) -> Lengths { "brushStrokes.spatter" => always(&["sprayRadius"]), "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), "brushStrokes.sumiE" => always(&["strokeWidth"]), - "pixelate.colorHalftone" => always(&["maxRadius"]), "pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]), "texture.craquelure" => always(&["crackSpacing"]), "texture.mosaicTiles" => always(&["tileSize"]), @@ -633,7 +644,7 @@ pub fn effect_catalog() -> Vec { "pixelate.colorHalftone", "Color Halftone…", PIXELATE, - "{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), ), r( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index fbbf3b0a90..8835d769f7 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -79,8 +79,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects}; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, - needs_outline, outline_art, outline_text, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options, + image_paint, needs_outline, outline_art, outline_text, reshape, }; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ @@ -95,7 +95,7 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects}; +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; #[cfg(test)] diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index c8cea82590..fbf22ff6b4 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -95,13 +95,16 @@ pub fn new_effect(id: &str, params: &Value) -> Option { } /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see -/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the -/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent. +/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which +/// keep their share of the object so. A distance left at its default is written out scaled; one +/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. pub fn scale_effect(e: &mut Effect, s: f64) { let Some(info) = catalog_index().get(e.id.as_str()) else { return }; let merged = merged_params(&e.id, &e.params); let relative = util::flag(&merged, "relative", false); - for k in info.lengths.keys(relative) { + let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); + keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); + for k in keys { let v = util::num(&merged, k, f64::NAN); if v.is_finite() { if !e.params.is_object() { diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 8885c9def4..2a122bb664 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -254,7 +254,8 @@ pub enum PixelFx { /// Stylize › Glowing Edges: bright coloured Sobel outlines on black. GlowingEdges { width: f64, brightness: f64, smoothness: f64 }, /// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels - /// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength. + /// 1 to 4) into dots of up to `max_radius` pixels of the Document Raster Effects resolution + /// ([`PixelSpace::line`] each), whose area follows the channel's strength. ColorHalftone { max_radius: f64, angles: [f64; 4] }, /// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart. Crystallize { cell: f64 }, @@ -668,9 +669,10 @@ impl PixelFx { } } - /// How far (document units) from a pixel the content that decides it lies; `None` when that - /// is anywhere in the object (Radial Blur). - pub fn reach(&self) -> Option { + /// How far (document units) from a pixel the content that decides it lies, with lines of the + /// raster grid `line` apart ([`PixelSpace::line`]); `None` when that is anywhere in the object + /// (Radial Blur). + pub fn reach(&self, line: f64) -> Option { match *self { PixelFx::RadialBlur { .. } => None, PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius), @@ -703,7 +705,10 @@ impl PixelFx { PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)), PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)), // The cells around the pixel's, and the cells around theirs. - PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius), + // (Without a usable grid there are no dots: see `pixelate::color_halftone`.) + PixelFx::ColorHalftone { max_radius, .. } => { + Some(3.0 * std::f64::consts::SQRT_2 * max_radius * line).filter(|d| d.is_finite()).or(Some(0.0)) + } PixelFx::Crystallize { cell } => Some(1.5 * cell), PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)), PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH), diff --git a/crates/effects/src/pixel/pixelate.rs b/crates/effects/src/pixel/pixelate.rs index e9997b0cf3..0318eb5f45 100644 --- a/crates/effects/src/pixel/pixelate.rs +++ b/crates/effects/src/pixel/pixelate.rs @@ -436,11 +436,12 @@ impl Screen { } /// Color Halftone: each channel screened at its angle in square cells sized so that a dot of -/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean -/// there (white stays white, black black). Coverage stays as it is. +/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's +/// dot covers the share of it that is the channel's mean there (white stays white, black black). +/// Coverage stays as it is. pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) { let Some(place) = Place::new(space, w, h) else { return }; - let side = max_radius * std::f64::consts::SQRT_2; + let side = max_radius * space.line * std::f64::consts::SQRT_2; // Cells under 3 pixels can't show their dots: on average a screen is the image itself. if !(side.is_finite() && side / place.px >= 3.0) { return; diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index ef4d9d7abf..8261d408a1 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -80,7 +80,7 @@ fn film_grain_parameters_are_bounded_and_neutral_settings_preserve_the_art() { neutral.apply(&mut out, w, h, &space(w, h)); assert_eq!(out, src); assert_eq!(neutral.outset(Rect::new(0.0, 0.0, w as f64, h as f64)), 0.0); - assert_eq!(neutral.reach(), Some(0.0)); + assert_eq!(neutral.reach(1.0), Some(0.0)); } #[test] @@ -520,12 +520,12 @@ fn outsets_follow_the_object() { assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9); assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far); assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0); - assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(), Some(4.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0)); // The edge modes also read the copy blurred over a wide radius's samples. - assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(), Some(5.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(1.0), Some(5.0)); assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0); - assert_eq!(spin.reach(), None); - assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0)); + assert_eq!(spin.reach(1.0), None); + assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(1.0), Some(6.0)); } #[test] @@ -962,7 +962,7 @@ fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0); - assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0)); + assert_eq!(fx("pixelate.mezzotint", json!({})).reach(1.0), Some(0.0)); } /// Fraction of `d`'s pixels for which `f` holds. @@ -1002,6 +1002,25 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() { assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40)); } +#[test] +fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() { + // Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a + // point apart) are the 8 px of 72 ppi, and draw the same dots. + let (w, h) = (64, 64); + let src = image(w, h, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]); + let run = |radius: f64, line: f64| { + let mut d = src.clone(); + fx("pixelate.colorHalftone", json!({"maxRadius": radius})).apply(&mut d, w, h, &PixelSpace { line, ..space(w, h) }); + d + }; + assert_eq!(run(16.0, 0.5), run(8.0, 1.0)); + assert_ne!(run(8.0, 0.5), run(8.0, 1.0), "the same radius at a finer resolution draws finer dots"); + // It looks as far around a pixel as its cells reach, in document units. + let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8})); + assert_eq!(halftone.reach(0.5), Some(3.0 * std::f64::consts::SQRT_2 * 4.0)); + assert_eq!(halftone.reach(f64::NAN), Some(0.0), "no grid, no dots"); +} + #[test] fn color_halftone_screens_inks_in_cmyk_documents() { let (w, h) = (64, 64); @@ -1241,8 +1260,8 @@ fn texture_params_take_defaults_and_stay_in_range() { for id in ["texture.craquelure", "texture.grain", "texture.mosaicTiles", "texture.texturizer"] { assert_eq!(fx(id, json!({})).outset(b), 0.0, "{id}"); } - assert_eq!(fx("texture.grain", json!({})).reach(), Some(0.0)); - assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(), Some(6.0)); + assert_eq!(fx("texture.grain", json!({})).reach(1.0), Some(0.0)); + assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(1.0), Some(6.0)); } /// The pixels of `d` (`w` wide) in the square `lo..hi` on both axes. @@ -1509,9 +1528,9 @@ fn distort_params_take_defaults_and_stay_in_range() { // Shifted content reaches past the bounds by the longest shift, and comes from as far. let b = Rect::new(0.0, 0.0, 100.0, 50.0); let glass = fx("distort.glass", json!({"distortion": 20})); - assert_eq!((glass.outset(b), glass.reach()), (10.0, Some(10.0))); + assert_eq!((glass.outset(b), glass.reach(1.0)), (10.0, Some(10.0))); let ripple = fx("distort.oceanRipple", json!({})); - assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach() == Some(ripple.outset(b))); + assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach(1.0) == Some(ripple.outset(b))); assert_eq!(fx("distort.diffuseGlow", json!({})).outset(b), 0.0); } @@ -1621,7 +1640,7 @@ fn ocean_ripple_moves_content_no_farther_than_its_magnitude() { fx("distort.oceanRipple", json!({"rippleMagnitude": 0})).apply(&mut d, w, h, &space(w, h)); assert_eq!(d, src, "no magnitude, no ripples"); let f = fx("distort.oceanRipple", json!({"rippleSize": 6, "rippleMagnitude": 20})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let mut d = src.clone(); f.apply(&mut d, w, h, &space(w, h)); assert_ne!(d, src); @@ -1765,19 +1784,19 @@ fn brush_strokes_outsets() { let reach = brushstrokes::stroke_reach; assert!((reach(20.0) - (0.75 * 20.0 + 1.5 / 15.0 * 20.0 + 1.0)).abs() < 1e-9); assert_eq!(fx("brushStrokes.accentedEdges", json!({})).outset(b), 0.0); - assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); + assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(1.0), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); assert_eq!(fx("brushStrokes.angledStrokes", json!({})).outset(b), reach(15.0)); assert_eq!(fx("brushStrokes.crosshatch", json!({})).outset(b), reach(9.0) + 0.9); assert_eq!(fx("brushStrokes.darkStrokes", json!({})).outset(b), reach(9.0)); assert_eq!(fx("brushStrokes.inkOutlines", json!({"strokeLength": 50})).outset(b), reach(50.0)); let spatter = fx("brushStrokes.spatter", json!({})); - assert_eq!((spatter.outset(b), spatter.reach()), (4.0, Some(4.0))); + assert_eq!((spatter.outset(b), spatter.reach(1.0)), (4.0, Some(4.0))); assert_eq!(fx("brushStrokes.spatter", json!({"sprayRadius": 0})).outset(b), 0.0); assert_eq!(fx("brushStrokes.sprayedStrokes", json!({})).outset(b), reach(12.0) + 0.3 * 7.0); assert_eq!(fx("brushStrokes.sumiE", json!({})).outset(b), 0.0); for id in brush_strokes() { let f = fx(id, json!({})); - assert!(f.reach().is_some_and(|r| r >= f.outset(b)), "{id}"); + assert!(f.reach(1.0).is_some_and(|r| r >= f.outset(b)), "{id}"); } } @@ -1961,7 +1980,7 @@ fn spatter_scatters_content_no_farther_than_its_radius() { let src = image(w, h, |x, _| if x < 32 { grey(255) } else { [0; 4] }); assert_eq!(run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 0})), src, "no radius, no spatter"); let f = fx("brushStrokes.spatter", json!({"sprayRadius": 15})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let d = run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 15})); assert_ne!(d, src); let inside = |v: usize, n: usize| (v as f64 + 0.5).min(n as f64 - v as f64 - 0.5) > most + 1.0; @@ -1990,7 +2009,7 @@ fn brush_strokes_look_no_farther_than_their_reach() { ("brushStrokes.sumiE", json!({"strokeWidth": 15})), ]); for (id, p) in cases { - let reach = fx(id, p.clone()).reach().unwrap(); + let reach = fx(id, p.clone()).reach(1.0).unwrap(); // Everything from `cut` on differs; the pixels left of 20 can't tell. let cut = 20 + reach.ceil() as usize + 1; assert!(cut < w, "{id}"); @@ -2047,7 +2066,7 @@ fn chalk_charcoal_params_take_defaults_and_stay_in_range() { assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}"); let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert!(f.reach().unwrap() > 0.0); + assert!(f.reach(1.0).unwrap() > 0.0); } #[test] @@ -2108,7 +2127,7 @@ fn graphic_pen_params_take_defaults_and_stay_in_range() { assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.graphicPen", json!({"strokeLength": 15})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0)); - assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); + assert_eq!(f.reach(1.0), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); assert_eq!( fx("sketch.graphicPen", json!({"strokeLength": 99})), PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal } @@ -2148,7 +2167,7 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() { assert!(HALFTONE_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.halftonePattern", json!({"size": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2162,7 +2181,7 @@ fn note_paper_params_take_defaults_and_stay_in_range() { assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}"); let f = fx("sketch.notePaper", json!({"relief": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } /// Note Paper embosses a horizontal gradient and graininess adds fibre. @@ -2198,7 +2217,7 @@ fn water_paper_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.waterPaper", json!({"fiberLength": 40})); assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0); - assert!(f.reach().unwrap_or(0.0) > 0.0); + assert!(f.reach(1.0).unwrap_or(0.0) > 0.0); let doc = crate::effect_info("sketch.waterPaper").unwrap().params; assert!(doc.contains("unverified"), "{doc}"); } @@ -2281,7 +2300,7 @@ fn plaster_params_take_defaults_and_stay_in_range() { let doc = crate::effect_info("sketch.plaster").unwrap().params; assert!(doc.contains("\"bottomRight\""), "{doc}"); let f = fx("sketch.plaster", json!({"smoothness": 24})); - assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0))); + assert_eq!(f.reach(1.0), Some(super::sketch::plaster_reach(15.0))); } /// Plaster changes the image and different light directions give different results. @@ -2356,8 +2375,8 @@ fn chrome_params_take_defaults_and_stay_in_range() { assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}"); let f = fx("sketch.chrome", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0))); - assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0))); + assert_eq!(f.reach(1.0), Some(sketch::chrome_reach(4.0))); + assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(1.0), Some(sketch::chrome_reach(10.0))); } /// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern. @@ -2389,7 +2408,7 @@ fn reticulation_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.reticulation", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2431,7 +2450,7 @@ fn torn_edges_params_take_defaults_and_stay_in_range() { for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] { assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({}))); } - assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None); + assert_eq!(fx("sketch.tornEdges", json!({})).reach(1.0), None); } #[test] @@ -2496,7 +2515,7 @@ fn artistic_params_take_defaults_and_stay_in_range() { fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})), PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 } ); - assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0))); + assert_eq!(fx("artistic.coloredPencil", json!({})).reach(1.0), Some(artistic::colored_pencil_reach(5.0))); assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }); assert_eq!( fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})), @@ -2860,7 +2879,7 @@ fn dry_brush_repaints_and_preserves_coverage() { let before = clear.clone(); fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h)); assert_eq!(clear, before); - let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(); + let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(1.0); assert!(reach.is_some_and(|r| r > 0.0)); } diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index 2f463f52f6..fd467a23ca 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -176,7 +176,7 @@ fn sketch_filters_reach_beyond_nothing_they_do_not_paint() { for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] { let f = fx(id, json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage"); - assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); + assert!(f.reach(1.0).is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); } } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index fa77c5702e..38d79c125e 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -39,8 +39,13 @@ pub fn needs_outline(n: &Node) -> bool { /// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy /// paints its gradient by itself ([`copy_leaf`]), as a group's copies do. pub fn has_gradient_copies(n: &Node) -> bool { + (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && has_transform_copies(n) +} + +/// Is `n` a path or compound path with a visible Transform effect that makes copies? Expand +/// Appearance makes each copy an object of its own ([`expand_outlined`]). +pub fn has_transform_copies(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) - && (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && geometry_effects(n) .iter() .any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0) @@ -249,11 +254,20 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default()) + outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false) } -/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]). -fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { +/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with +/// `apart`, also a path or compound path whose Transform effect makes copies +/// ([`has_transform_copies`]), as the one piece the copies are made from. +fn outline_art_with( + doc: Option<&Document>, + n: &Node, + symbol_art: Option<&Node>, + outline: OutlineHook, + nodes: &SymbolNodes, + apart: bool, +) -> Option { let mut art = match &n.kind { NodeKind::Text(_) => outline_text(n)?, NodeKind::SymbolInstance { symbol, xf } => { @@ -268,7 +282,7 @@ fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, Node::group(n.id, vec![Arc::new(a)]) } // The object as the one piece the copies of its Transform effect are made from. - _ if has_transform_art(n) => { + _ if has_transform_art(n) || (apart && has_transform_copies(n)) => { let mut one = n.clone(); one.opacity = 1.0; one.blend = Default::default(); @@ -429,10 +443,12 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O /// geometry effects, else type with fills or strokes of its own outlined, or an image with fills /// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its - // patterns: each copy an object of its own. - if has_transform_art(n) { - return as_art(doc, n, symbol_art); + // A path whose Transform effect copies it, or scales its strokes or moves its patterns: each + // copy an object of its own with the path's fills and strokes, the copies of each Transform + // effect in a group of their own (copies of copies nest), as the reference app expands them + // (#5612). + if has_transform_art(n) || has_transform_copies(n) { + return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true); } let own_paint = match n.kind { NodeKind::Text(_) => !n.appearance.items.is_empty(), @@ -451,6 +467,12 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node> /// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]). pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { + as_art_opts(doc, n, symbol_art, outline, nodes, false) +} + +/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an +/// object of its own ([`copy_leaf`]) rather than one path of every copy. +fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option { let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { @@ -478,9 +500,12 @@ pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<& Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect()) } } - _ => outline_art_with(doc, n, symbol_art, outline, nodes)?, + _ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?, }; - reshape_leaves(&mut art, &fx); + reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart); + if apart { + hoist_copies(&mut art); + } transform_items(&mut art); // Type and symbols in perspective: the art projected onto their plane. if let Some(h) = n.projection() { @@ -546,6 +571,28 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) { /// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost. pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) { + reshape_leaves_apart(art, fx, budget, false); +} + +/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding +/// the group of its copies ([`copy_leaf`]) as its only member: the copies become its members, so +/// the expanded path is one group of its copies rather than a group in a group. +fn hoist_copies(art: &mut Node) { + let id = art.id; + let Some(children) = art.children_mut() else { return }; + let [only] = children.as_slice() else { return }; + if only.id != id || !matches!(only.kind, NodeKind::Group { clip: false, .. }) { + return; + } + let copies = only.children().cloned().unwrap_or_default(); + if !copies.is_empty() { + *children = copies; + } +} + +/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects +/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. +fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) { if fx.is_empty() { return; } @@ -588,14 +635,14 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg if let Some((m, copies, options, map)) = transform { // Transform Patterns and Scale Strokes & Effects change each copy's fills and // strokes; a gradient paints each copy by itself, not the one piece the copies - // make together. - let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); + // make together; and Expand Appearance (`apart`) makes each copy an object. + let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); if options.reach_appearance() { let made = transform_leaf(leaf, &path, map, copies, options, room); used = used.minus(before).plus(made); return; } - if gradient { + if separate { let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room); used = used.minus(before).plus(made); return; diff --git a/crates/effects/src/stroke.rs b/crates/effects/src/stroke.rs index 0760c38a24..2ae452ed51 100644 --- a/crates/effects/src/stroke.rs +++ b/crates/effects/src/stroke.rs @@ -24,7 +24,7 @@ use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer}; pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit}; pub use arrow::Arrow; -pub use dash::{Dashed, Dot, dash, dot_outline}; +pub use dash::{Dashed, Dot, dash, dash_kept, dot_outline}; pub use gradient::{Slice, WrittenSlices, gradient_meshes, gradient_slices, written_slices}; pub use outline::{OUTLINE_TOL, Written, WrittenShape, for_writer, is_plain, outline_region}; pub use width::width_outline; @@ -111,11 +111,7 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B } out } - (None, Some(d)) => { - let mut out = kurbo::stroke(d.path.iter(), &style(st, width), &kurbo::StrokeOpts::default(), tol); - out.extend(dot_outline(&d.dots, width, st.cap, tol).iter()); - out - } + (None, Some(d)) => dashed_outline(&d, st, width, tol), (None, None) => { let mut out = plain_outline(line, &style(st, width), tol); out.extend(dot_outline(&point_dots(line), width, st.cap, tol).iter()); @@ -124,6 +120,28 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B } } +/// [`line_outline`] of a dashed line without a width profile, made of only the dashes and dots on +/// the segments of `line` that `keep` accepts ([`dash_kept`]). `None` when `st` has no dash +/// pattern or has a width profile, or when its pattern draws the line solid. +pub fn dashed_line_outline_kept(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, keep: &dyn Fn(&PathSeg) -> bool) -> Option { + if st.profile.is_some() { + return None; + } + let d = dash_kept(line, st.dash.as_ref()?, keep)?; + if width <= 0.0 || !width.is_finite() { + return Some(BezPath::new()); + } + Some(dashed_outline(&d, st, width, tol.max(1e-4))) +} + +/// The filled outline of the dashes and dots `d` of a stroke `st` without a width profile, at +/// `width` and flattened/fitted to `tol`. +fn dashed_outline(d: &Dashed, st: &StrokeLayer, width: f64, tol: f64) -> BezPath { + let mut out = kurbo::stroke(d.path.iter(), &style(st, width), &kurbo::StrokeOpts::default(), tol); + out.extend(dot_outline(&d.dots, width, st.cap, tol).iter()); + out +} + /// The subpaths of `line` that never leave their first point (`m` then `L` to the same point, as /// `.ai` files write dots, #1613), as dots: kurbo strokes nothing for them, where PDF and SVG /// viewers paint the cap. They lie along the x axis, which a projecting cap's square follows diff --git a/crates/effects/src/stroke/dash.rs b/crates/effects/src/stroke/dash.rs index 689c88dae1..f660a6c8f7 100644 --- a/crates/effects/src/stroke/dash.rs +++ b/crates/effects/src/stroke/dash.rs @@ -45,6 +45,14 @@ pub struct Dashed { /// entry, as in SVG and PDF) or has no positive length (the line is solid), or is too fine to draw /// (then the line is drawn solid too). pub fn dash(bp: &BezPath, d: &Dash) -> Option { + dash_kept(bp, d, &|_| true) +} + +/// [`dash`] with only the dashes and dots on the segments of `bp` that `keep` accepts. The pattern +/// runs along every segment as in [`dash`], so a kept dash lies where [`dash`] puts it: a dash +/// running onto a segment left out ends where that segment starts and goes on from where the next +/// kept segment starts. Segments left out still count toward the limit on the number of dashes. +pub fn dash_kept(bp: &BezPath, d: &Dash, keep: &dyn Fn(&PathSeg) -> bool) -> Option { if d.pattern.iter().any(|v| !v.is_finite() || *v < 0.0) || !d.offset.is_finite() { return None; } @@ -82,7 +90,7 @@ pub fn dash(bp: &BezPath, d: &Dash) -> Option { let phase = Phase { ix: ix0, rem: pat[ix0] - off, on: ix0 % 2 == 0 }; let mut out = Dashed::default(); for plan in &plans { - dash_subpath(&mut out, plan, &pat, phase); + dash_subpath(&mut out, plan, &pat, phase, keep); } Some(out) } @@ -175,7 +183,7 @@ impl Piece { } } -fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) { +fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase, keep: &dyn Fn(&PathSeg) -> bool) { let first_dot = out.dots.len(); let total: f64 = plan.lens.iter().sum(); // Fraction of the subpath's length at `x` along the plan. @@ -188,7 +196,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) { }; let mut dashes: Vec = vec![]; let mut cur = Piece::default(); - let (mut cuts, mut acc, mut starts_on) = (0, 0.0, false); + let (mut cuts, mut acc, mut starts_on, mut left_out) = (0, 0.0, false, false); for (i, (seg, &len)) in plan.segs.iter().zip(&plan.lens).enumerate() { let k = plan.scale[i]; if plan.restart[i] { @@ -199,21 +207,30 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) { } ph = Phase { ix: 0, rem: pat[0] * k / 2.0, on: true }; } + // A segment left out ends the dash running onto it; the pattern still advances along it. + let kept = keep(seg); + if !kept { + left_out = true; + if !cur.segs.is_empty() { + cur.end = acc; + dashes.push(std::mem::take(&mut cur)); + } + } if i == 0 { - starts_on = ph.on && ph.rem > 0.0; + starts_on = kept && ph.on && ph.rem > 0.0; } let mut s = 0.0; loop { let left = len - s; if ph.rem > left + EPS { - if ph.on && left > EPS { + if kept && ph.on && left > EPS { cur.push(sub(seg, len, s, len), acc + s); } ph.rem -= left; break; } let end = (s + ph.rem).min(len); - if ph.on { + if kept && ph.on { if pat[ph.ix] > 0.0 { if end > s { cur.push(sub(seg, len, s, end), acc + s); @@ -240,6 +257,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) { && plan.restart[0] && pat[0] <= 0.0 && let Some(seg) = plan.segs.last() + && keep(seg) { push_dot(out, first_dot, Dot { at: seg.end(), dir: tangent(seg, 1.0), t: 1.0 }); } @@ -249,7 +267,7 @@ fn dash_subpath(out: &mut Dashed, plan: &Plan, pat: &[f64], mut ph: Phase) { dashes.push(cur); } if plan.closed { - if cuts == 0 && ends_on { + if cuts == 0 && ends_on && !left_out { // One dash all the way round: keep it closed so the start gets a join, not caps. let d = dashes.pop().unwrap_or_default(); write(&mut out.path, &d.segs); diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 1da14b334e..a79b8e0f78 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -110,6 +110,80 @@ fn dashes_follow_arc_length_and_join_across_the_start_of_closed_paths() { assert!(dash(&line(0.0, 1e6), &dashed(&[0.001, 0.001], 0.0)).is_none()); } +/// The dashes of `d` as (start x, end x), for dashes along the x axis. +fn spans_x(d: &Dashed) -> Vec<(f64, f64)> { + let mut out = vec![]; + for el in d.path.elements() { + match el { + PathEl::MoveTo(p) => out.push((p.x, p.x)), + PathEl::LineTo(p) => { + if let Some(last) = out.last_mut() { + last.1 = p.x; + } + } + _ => {} + } + } + out +} + +/// Ten segments of 10 pt along the x axis from 0 to 100. +fn steps() -> BezPath { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=10 { + b.line_to((f64::from(i) * 10.0, 0.0)); + } + b +} + +/// Whether a segment lies outside x 30..60. +fn outside(s: &PathSeg) -> bool { + s.start().x >= 60.0 || s.end().x <= 30.0 +} + +#[test] +fn dashes_kept_on_some_segments_keep_the_phase_of_the_whole_line() { + // A period of 7 starting 2 into it: dashes at -2..2, 5..9, 12..16, … + let pattern = dashed(&[4.0, 3.0], 2.0); + let all = dash(&steps(), &pattern).unwrap(); + let kept = dash_kept(&steps(), &pattern, &|s| outside(s)).unwrap(); + // The dashes of the whole line, cut at x 30 and 60. + let cut: Vec<(f64, f64)> = + spans_x(&all).into_iter().flat_map(|(a, b)| [(a, b.min(30.0)), (a.max(60.0), b)]).filter(|(a, b)| b - a > 1e-9).collect(); + let got = spans_x(&kept); + assert_eq!(got.len(), cut.len(), "{got:?} against {cut:?}"); + for ((a, b), (c, d)) in got.iter().zip(&cut) { + assert!(near(*a, *c, 1e-9) && near(*b, *d, 1e-9), "{got:?} against {cut:?}"); + } + // The dash after the gap starts where the whole line's does, at 61, not at 60. + assert!(got.iter().any(|(a, _)| near(*a, 61.0, 1e-9)), "{got:?}"); + // Dots on segments left out are left out (the dot at 60 ends a segment left out). + let dots = dash_kept(&steps(), &dashed(&[0.0, 5.0], 0.0), &|s| outside(s)).unwrap(); + let xs: Vec = dots.dots.iter().map(|d| d.at.x).collect(); + let want = [0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0]; + assert!(xs.len() == want.len() && xs.iter().zip(want).all(|(x, w)| near(*x, w, 1e-9)), "{xs:?}"); + // Keeping every segment is the whole line's dashing, and keeping none leaves nothing. + assert_eq!(dash_kept(&steps(), &pattern, &|_| true).unwrap().path, all.path); + let none = dash_kept(&steps(), &pattern, &|_| false).unwrap(); + assert!(none.path.elements().is_empty() && none.dots.is_empty()); + // A pattern too fine for the whole line draws it solid, however few segments are kept. + assert!(dash_kept(&line(0.0, 1e6), &dashed(&[0.001, 0.001], 0.0), &|s| s.start().x < 1.0).is_none()); +} + +#[test] +fn a_closed_path_with_segments_left_out_is_dashed_in_open_pieces() { + // One dash all the way round: with the right side left out it is no longer closed. + let keep_left = |s: &PathSeg| s.start().x < 5.0 || s.end().x < 5.0; + let whole = dash_kept(&square(10.0), &dashed(&[100.0, 1.0], 0.0), &keep_left).unwrap(); + assert!(!is_closed(&whole.path), "{:?}", whole.path.to_svg()); + // The bottom side left out: of the 10 dashes, the one through the start point stays one dash, + // the one into the bottom side is cut and the two on it are left out. + let kept = dash_kept(&square(100.0), &dashed(&[20.0, 20.0], 10.0), &|s| s.start().y < 50.0 || s.end().y < 50.0).unwrap(); + assert_eq!(moves(&kept.path), 8, "{}", kept.path.to_svg()); + assert!(!kept.path.elements().iter().any(|e| matches!(e, PathEl::MoveTo(p) if p.distance(Point::ZERO) < 1e-9)), "{}", kept.path.to_svg()); +} + #[test] fn dot_outlines_take_the_cap_shape_and_wind_like_stroked_dashes() { let dots = [Dot { at: Point::new(10.0, 0.0), dir: Vec2::new(1.0, 0.0), t: 0.0 }]; @@ -427,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/effects/src/tests.rs b/crates/effects/src/tests.rs index 611909b964..ea3843f0ee 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1231,14 +1231,29 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { #[test] fn a_distance_parameters_range_comes_from_its_documentation() { - assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0)); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None); + assert_eq!(length_range("no.such", "edgeWidth"), None); +} + +#[test] +fn color_halftones_radius_is_in_raster_pixels_not_a_distance() { + // Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260): + // no unit setting changes it, so it isn't a distance in points. + assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert!(!is_length("pixelate.colorHalftone", "maxRadius", false)); + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None); + assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None); // The effect applies the range's floor to a radius below it. assert_eq!( crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) ); - // A distance documented without a range, and unknown effects and parameters, have none. - assert_eq!(length_range("path.offsetPath", "offset"), None); - assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None); - assert_eq!(length_range("no.such", "maxRadius"), None); + // Scale Strokes & Effects scales it with the object, as it does distances. + let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap(); + crate::scale_effect(&mut e, 2.0); + assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0))); } diff --git a/crates/engine/examples/anchor_bench.rs b/crates/engine/examples/anchor_bench.rs index 877526b109..281464c0b7 100644 --- a/crates/engine/examples/anchor_bench.rs +++ b/crates/engine/examples/anchor_bench.rs @@ -1,6 +1,7 @@ //! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the -//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of -//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors. +//! engine steps of editing anchors with Direct Selection, on four synthetic documents: one closed path of +//! 50,000 anchors, 2,000 closed paths of 50 anchors each, one open path of 200,000 anchors, and the closed +//! path of 50,000 anchors filled and with a dashed stroke. //! `ITERS` sets the runs per step (default 7); each row is the median in ms. // Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -10,7 +11,7 @@ use std::time::Instant; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Node, NodeId}; use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; use vectorcraft_engine::{Session, ViewInfo}; use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2}; @@ -70,6 +71,20 @@ fn one_outline() -> Shape { } } +/// [`one_outline`] filled, with a 1 pt stroke of 6 pt dashes and 4 pt gaps. +fn dashed_outline() -> Shape { + let mut shape = one_outline(); + let mut look = Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.2)), Paint::solid(Color::BLACK), 1.0); + for item in &mut look.items { + if let AppearanceItem::Stroke(st) = item { + st.dash = Some(Dash { pattern: vec![6.0, 4.0], offset: 0.0, align_corners: false }); + } + } + shape.doc.node_mut(shape.ids[0]).unwrap().appearance = look.into(); + shape.name = "one closed path, 50,000 anchors, filled, dashed stroke"; + shape +} + fn many_paths() -> Shape { let mut doc = Document::new(1600.0, 1200.0); let ids: Vec = @@ -317,4 +332,5 @@ fn main() { bench(one_outline()); bench(many_paths()); bench(long_open_path()); + bench(dashed_outline()); } 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 ac9597cbd8..324d7bde58 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -4,10 +4,12 @@ mod arrange; mod cleanup; mod color; +mod contour; mod document; mod pathtools; mod pen; mod select; +mod shapes; mod typetools; use super::CommandSpec; @@ -17,10 +19,12 @@ pub fn specs() -> Vec { let mut v = arrange::specs(); v.extend(cleanup::specs()); v.extend(color::specs()); + v.extend(contour::specs()); v.extend(document::specs()); 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/contour.rs b/crates/engine/src/cmd/addons/contour.rs new file mode 100644 index 0000000000..46df381edc --- /dev/null +++ b/crates/engine/src/cmd/addons/contour.rs @@ -0,0 +1,85 @@ +//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that +//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its +//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The +//! original stays where it is. Running the command on an object that already carries an Offset +//! Path effect (a Contour made earlier) changes that effect instead of nesting another one. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_render::effects; + +use super::super::edit::{copy_above, selected_roots}; +use super::super::pathops::{len_param, num_param}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; + +const C: &str = "addon.contour.set"; +/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest offset, in points; Offset Path takes the same. +const MAX_OFFSET: f64 = 1e5; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.contour.set", + "Contour", + [], + None, + "{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}", + has_selection, + contour + )] +} + +/// The Offset Path join a Contour corner style stands for. +fn joins_for(corners: Option<&str>) -> Result<&'static str> { + match corners.map(str::to_ascii_lowercase).as_deref() { + None | Some("sharp") => Ok("miter"), + Some("round") => Ok("round"), + Some("square") => Ok("bevel"), + Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))), + } +} + +fn contour(s: &mut Session, p: &Value) -> Result { + let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + if offset.abs() > MAX_OFFSET { + return Err(bad(C, "offset out of range")); + } + let joins = joins_for(str_param(p, "corners"))?; + let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) + .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; + let roots = selected_roots(s)?; + let (updated, created) = s.edit("Contour", |d, sel| { + // A shape that already carries Offset Path is a Contour: change it. Any other path or + // shape gets a Contour copy above it. Type, images and the rest are left alone. + let (mut again, mut fresh) = (vec![], vec![]); + for id in roots { + let Some(n) = d.node(id) else { continue }; + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + continue; + } + if n.appearance.effects.iter().any(|e| e.id == EFFECT) { + again.push(id); + } else { + fresh.push(id); + } + } + if again.is_empty() && fresh.is_empty() { + return Err(EngineError::Other("Contour: select paths or shapes".into())); + } + for id in &again { + if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) { + e.params = effect.params.clone(); + } + } + let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?; + sel.set(again.iter().chain(made.iter()).copied()); + Ok((again, made)) + })?; + let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::>(); + Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) })) +} diff --git a/crates/engine/src/cmd/addons/contour/tests.rs b/crates/engine/src/cmd/addons/contour/tests.rs new file mode 100644 index 0000000000..900d110d58 --- /dev/null +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -0,0 +1,371 @@ +//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::Rect; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect() +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> { + node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn node_count(s: &Session) -> usize { + s.doc().unwrap().doc.node_count() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +#[test] +fn contour_is_a_live_copy_above_the_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let before = bounds(&s, a); + let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(); + let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated")); + assert_eq!((made.len(), updated.len()), (1, 0)); + // The original is untouched, the copy is above it and selected, and nothing is baked: the + // copy's own path is still the original's, with the effect on top. + assert!(effects_of(&s, a).is_empty()); + assert_eq!(bounds(&s, a), before); + assert_eq!(s.doc().unwrap().selection.objects, made); + let d = &s.doc().unwrap().doc; + assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap()); + assert_eq!(bounds(&s, made[0]), before); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0].0, "path.offsetPath"); + assert_eq!(fx[0].1["offset"], json!(10.0)); + assert_eq!(fx[0].1["joins"], json!("miter")); +} + +#[test] +fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] { + select(&mut s, &[a]); + s.execute("addon.contour.set", &json!({"offset": offset})).unwrap(); + let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids"); + let b = bounds(&s, baked[0]); + // The default stroke widens the baked art by its weight; compare the fill's edges. + let fill = baked_fill_bounds(&s, baked[0]); + assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})"); + } +} + +/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the +/// object itself when it is one path. +fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect { + match &node(s, id).kind { + NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(), + _ => bounds(s, id), + } +} + +#[test] +fn a_second_drag_changes_the_contour_instead_of_nesting_one() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created"); + let count = node_count(&s); + // The Contour is selected: the next call edits it. + let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap(); + assert_eq!(ids_of(&r, "updated"), made); + assert!(ids_of(&r, "created").is_empty()); + assert_eq!(node_count(&s), count, "no new object"); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1, "one Offset Path, not two"); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round"))); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn corner_styles_choose_the_join() { + for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); + assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}"); + } +} + +#[test] +fn contour_keeps_the_color_and_stroke_editable_on_the_copy() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created"); + let original = node(&s, a).appearance.items.clone(); + assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint"); + // Recolouring the Contour (it is the selection) changes its fill only: the live effect stays + // and the original keeps its paint. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill"); + assert_eq!(node(&s, a).appearance.items, original, "the original is untouched"); + assert_eq!(effects_of(&s, made[0]).len(), 1); +} + +#[test] +fn contour_is_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(); + assert_eq!(node_count(&s), count + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), count); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn contour_refuses_what_it_cannot_offset() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] { + assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}"); + } + // Nothing was added by the refused calls. + assert_eq!(node_count(&s), count); + // Type is not a path to offset. + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap(); + let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string(); + assert!(err.contains("select paths or shapes"), "{err}"); +} + +/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then +/// the gap taken out of the border with Minus Front, leaves a ring between the two. +#[test] +fn border_with_a_gap_from_two_contours_and_minus_front() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + // Strip the default stroke so the areas are plain. + s.execute("paint.setStroke", &json!({"none": true})).ok(); + // The gap first (+8), then the border (+20) from the same shape: both land directly above it, + // the later one lower, so the gap ends up in front of the border. + select(&mut s, &[a]); + let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0]; + select(&mut s, &[a]); + let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0]; + let d = &s.doc().unwrap().doc; + assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border"); + select(&mut s, &[border, gap]); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let both: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(both.len(), 2); + let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids"); + assert_eq!(ring.len(), 1); + // 90 x 80 outer minus 66 x 56 inner, with sharp corners. + let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1); + assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}"); +} + +fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) { + match &node(s, id).kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule) + } + NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(), + _ => panic!("not a path"), + } +} + +mod tool { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + use super::*; + use crate::tooling::ViewInfo; + + fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..Default::default() } + } + + fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap(); + } + + fn undo_depth(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active. + fn ready() -> (Session, NodeId) { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[a]); + s.select_tool("contour", view()).unwrap(); + (s, a) + } + + fn offset_of(s: &Session, id: NodeId) -> f64 { + effects_of(s, id)[0].1["offset"].as_f64().unwrap() + } + + #[test] + fn dragging_out_previews_live_and_commits_one_undo_step() { + let (mut s, a) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + // Press on the right edge and pull 10 pt away from the shape. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + assert!(s.in_interaction(), "the Contour is previewed while the button is down"); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!(undo_depth(&s), before + 1); + assert_eq!(node_count(&s), nodes + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set")); + let made = s.doc().unwrap().selection.objects.clone(); + assert_eq!(made.len(), 1); + assert_ne!(made[0], a); + assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0])); + assert!(effects_of(&s, a).is_empty(), "the original is kept as it was"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), nodes); + } + + #[test] + fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() { + let (mut s, _) = ready(); + // From inside, 5 pt toward the middle of the right edge's neighbourhood. + at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default()); + let contour = s.doc().unwrap().selection.objects[0]; + assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6); + // The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5. + let nodes = node_count(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default()); + assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested"); + assert_eq!(s.doc().unwrap().selection.objects, vec![contour]); + assert_eq!(effects_of(&s, contour).len(), 1); + assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + } + + #[test] + fn escape_and_a_plain_click_change_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + // A click with no movement. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + } + + #[test] + fn shift_rounds_to_whole_points_and_the_corner_option_is_used() { + let (mut s, _) = ready(); + s.set_tool_option("corners", &json!("round")); + let shift = Mods { shift: true, ..Mods::default() }; + at(&mut s, PointerKind::Down, 150.0, 120.0, shift); + at(&mut s, PointerKind::Drag, 160.4, 120.0, shift); + at(&mut s, PointerKind::Up, 160.4, 120.0, shift); + let contour = s.doc().unwrap().selection.objects[0]; + assert_eq!(offset_of(&s, contour), 10.0); + assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round")); + } + + /// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the + /// tool's options are by then (they said Sharp when the Contour was made Square). + #[test] + fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() { + let (mut s, _) = ready(); + s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); + let contour = s.doc().unwrap().selection.objects[0]; + s.set_tool_option("corners", &json!("sharp")); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default()); + let fx = effects_of(&s, contour); + assert_eq!(fx.len(), 1); + assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1); + assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1); + } + + /// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift) + /// leaves no unchanged copy and no undo step. + #[test] + fn a_drag_along_the_edge_changes_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + let shift = Mods { shift: true, ..Mods::default() }; + for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] { + at(&mut s, PointerKind::Down, 150.0, 120.0, mods); + at(&mut s, PointerKind::Drag, to.0, to.1, mods); + at(&mut s, PointerKind::Up, to.0, to.1, mods); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}"); + assert!(!s.in_interaction()); + } + } + + /// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads + /// over any fill); a shape that is not a Contour yet has none. + #[test] + fn a_selected_contour_shows_the_outline_it_was_made_from() { + use vectorcraft_tools::Overlay; + let (mut s, _) = ready(); + let paths = |s: &mut Session| -> Vec<(bool, f32)> { + s.overlays(view()) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, width, .. } => Some((dashed, width)), + _ => None, + }) + .collect() + }; + assert!(paths(&mut s).is_empty(), "a plain shape has no guide"); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + // The solid halo first, the dashes on top of it. + assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]); + } + + #[test] + fn nothing_selected_does_nothing() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("contour", view()).unwrap(); + let before = undo_depth(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert_eq!(undo_depth(&s), before); + } +} 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/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs index 464fa032ba..2f035d8ad4 100644 --- a/crates/engine/src/cmd/addons/pathtools/corners.rs +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec { "Set Corners", [], None, - "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", has_doc, corner_set ), @@ -50,8 +50,108 @@ fn anchors_param(p: &Value, cmd: &str) -> Result>> { .map(Some) } -/// The corners a request names: each path with the corners (anchor indices of its uncut outline). -fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result)>> { +/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline +/// (the first anchor is number 1). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Every { + All, + /// The 1st, 3rd, 5th… anchors: indices 0, 2, 4…. + Odd, + /// The 2nd, 4th, 6th… anchors: indices 1, 3, 5…. + Even, +} + +impl Every { + /// The `every` of `p` (default: all). + fn of(p: &Value, cmd: &str) -> Result { + match p.get("every").filter(|v| !v.is_null()) { + None => Ok(Self::All), + Some(v) => match v.as_str() { + Some("all") => Ok(Self::All), + Some("odd") => Ok(Self::Odd), + Some("even") => Ok(Self::Even), + _ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))), + }, + } + } + + /// Does it take the anchor at `index`? Anchors that take no corner still count. + fn takes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::Odd => index.is_multiple_of(2), + Self::Even => !index.is_multiple_of(2), + } + } + + /// Where the corners it takes are, for an error: "" for all of them. + fn at(self) -> &'static str { + match self { + Self::All => "", + Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)", + Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)", + } + } +} + +/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90 +/// takes a rectangle's corners whatever the rounding. +const ANGLE_SLACK: f64 = 1e-6; +/// The error when no anchor named is a corner at all. +const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner"; + +/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their +/// sides meet at (`minAngle`..`maxAngle`, degrees). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Pick { + every: Every, + min_angle: f64, + max_angle: f64, +} + +impl Pick { + /// Every chosen corner. + const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 }; + + /// The `every`, `minAngle` and `maxAngle` of `p`. + fn of(p: &Value, cmd: &str) -> Result { + let every = Every::of(p, cmd)?; + let angle = |key: &str, default: f64| -> Result { + let a = number_or(p, key, default, cmd)?; + if !(a.is_finite() && (0.0..=180.0).contains(&a)) { + return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}"))); + } + Ok(a) + }; + let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?); + if min_angle > max_angle { + return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)"))); + } + Ok(Self { every, min_angle, max_angle }) + } + + /// Does it take corner `index` of `lc`? + fn takes(&self, lc: &LiveCorners, index: usize) -> bool { + self.every.takes(index) + && lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg())) + } + + /// The error when it takes none of the chosen corners. + fn none(&self) -> String { + let at = self.every.at(); + if self.min_angle > 0.0 || self.max_angle < 180.0 { + format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle) + } else if at.is_empty() { + NO_CORNER.into() + } else { + format!("none of the chosen corners is{at}") + } + } +} + +/// The corners a request names: each path with the corners (anchor indices of its uncut outline) +/// that `pick` takes. +fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result)>> { let shared = anchors_param(p, cmd)?; // Each path with its own `anchors`, or sharing the request's. let mut own: Vec>> = vec![]; @@ -71,10 +171,10 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) { Some(given) => { let n = lc.base.anchor_count(); if let Some(past) = given.iter().find(|k| **k >= n) { @@ -84,12 +184,14 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), }; + chosen |= !corners.is_empty(); + let corners: BTreeSet = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect(); if !corners.is_empty() { out.push((*id, corners)); } } if out.is_empty() { - return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner")); + return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() })); } Ok(out) } @@ -134,11 +236,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result { .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) }) .transpose()?; - let corners = named_corners(s, p, C)?; + let pick = Pick::of(p, C)?; + let corners = named_corners(s, p, C, pick)?; edit_corners(s, "Set Corners", corners, radius, kind) } fn corner_remove(s: &mut Session, p: &Value) -> Result { - let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?; + let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?; edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 32bcc0c3b3..e31aadf56e 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -567,6 +567,170 @@ fn corner_commands_refuse_bad_params() { } } +/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd +/// numbers counting from 1), its inner corners at the odd ones. +fn star_path(s: &mut Session) -> NodeId { + let pts: Vec<(f64, f64)> = (0..10) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0); + (200.0 + r * a.sin(), 150.0 - r * a.cos()) + }) + .collect(); + line(s, &pts, true) +} + +/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn. +fn cut(s: &Session, id: NodeId) -> Vec { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() +} + +#[test] +fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() { + let mut s = session(); + let star = star_path(&mut s); + // An open zig-zag: its ends (1st and 5th) take no corner but still count. + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false); + select(&mut s, &[star, zig]); + let n = steps(&s); + // Odd: the 1st, 3rd, 5th… of each path, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n)); + // Even: the 2nd, 4th, 6th…. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3])); + // "all" (and no `every`) is every chosen corner, as before. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap(); + assert_eq!(cut(&s, zig), vec![1, 2, 3]); +} + +#[test] +fn corner_set_every_filters_the_named_and_direct_selected_anchors() { + let mut s = session(); + let star = star_path(&mut s); + // Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's. + let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap(); + assert_eq!(r["corners"], json!(2)); + assert_eq!(cut(&s, star), vec![1, 3]); + // Per path through `items`. + s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 6]); + // Of the direct-selected anchors. + s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap(); + select_anchors(&mut s, star, &[7, 8, 9]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![8]); +} + +#[test] +fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() { + let mut s = session(); + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false); + select(&mut s, &[zig]); + let i = zig.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "every": "third"}), + json!({"ids": [i], "radius": 5, "every": "Odd"}), + json!({"ids": [i], "radius": 5, "every": 2}), + json!({"ids": [i], "radius": 5, "every": true}), + json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}), + json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}), + ], + ); + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string(); + assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}"); + // The 2nd anchor is a corner, but not an odd-numbered one. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("odd-numbered"), "{e}"); + // An open end is no corner at all, whatever `every` says. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("two sides meet"), "{e}"); +} + +/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°. +fn house(s: &mut Session) -> NodeId { + line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true) +} + +#[test] +fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() { + let mut s = session(); + // The star's points meet at about 38°, its inner corners at about 110°. + let (star, home) = (star_path(&mut s), house(&mut s)); + select(&mut s, &[star, home]); + let n = steps(&s); + // The sharp spikes only: the house has none, the star five, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap(); + assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), steps(&s)), (vec![], n)); + // Exactly 90°: the house's square corners. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3])); + // 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap(); + assert_eq!(r["corners"], json!(7)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4])); + assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0)); + // On top of the named anchors and of `every`. + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(cut(&s, home), vec![1, 3]); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]); +} + +#[test] +fn corner_set_angle_range_on_a_three_anchor_path() { + let mut s = session(); + // An open pen path of three anchors: one corner, of 90°. + let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false); + select(&mut s, &[id]); + let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string(); + assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}"); + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(r["corners"], json!(1)); + assert_eq!(cut(&s, id), vec![1]); +} + +#[test] +fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() { + let mut s = session(); + let star = star_path(&mut s); + select(&mut s, &[star]); + let i = star.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "minAngle": -1}), + json!({"ids": [i], "radius": 5, "maxAngle": 181}), + json!({"ids": [i], "radius": 5, "minAngle": 1e308}), + json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}), + json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}), + json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}), + json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}), + ], + ); + let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string(); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200})); + assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60})); + assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100})); + assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100})); + assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}"); +} + #[test] fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { let mut s = session(); 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/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index a478b8c00b..bc1d4e4f25 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -2,22 +2,27 @@ //! the selected characters letter by letter, from a start value to an end value along a shape //! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as //! the Character panel sets them (`text.setRangeStyle`), in its units and ranges -//! (). Its submenu -//! (Object › Plug-ins › Type Tools) and dialog are the UI's. +//! (). Release Type on a Path +//! splits type on a path into point type holding the same text and the plain path it was set on +//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no +//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. #[cfg(test)] mod tests; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, TextRun}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, ArcPath, Point}; use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; use super::super::typecmd::refresh_bounds; -use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use super::super::typemenu::text_ids; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; /// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its @@ -41,17 +46,33 @@ pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; const MAX_CHARS: usize = 100_000; pub fn specs() -> Vec { - vec![cmd!( - "addon.type.textTweaker", - "Text Tweaker", - ["Object", "Plug-ins", "Type Tools"], - None, - "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", - has_selection, - text_tweaker - )] + vec![ + cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + ), + cmd!( + "addon.type.releasePath", + "Release Type on a Path…", + ["Object", "Plug-ins", "Type Tools"], + None, + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + has_selection, + release_path + ), + ] } +/// Release Type on a Path's command (the id in [`specs`]). +pub const RELEASE: &str = "addon.type.releasePath"; +/// What Release Type on a Path keeps: both, the path only, or the text only. +pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"]; + /// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the /// random shape. fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { @@ -187,3 +208,143 @@ fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { edit::normalize(&mut out); out } + +/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking +/// order. An id that names no object is an error. +fn path_types(s: &Session, p: &Value) -> Result> { + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. })); + Ok(text_ids(d, &ids).into_iter().filter(on_path).collect()) +} + +/// Where the first character laid out in `lay` starts its baseline: the pen position of the first +/// glyph in text order (a list marker, which has no characters, before the character it leads). +/// None without a glyph. +fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { + lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin) +} + +/// `t`, type on a path, as point type on one straight line: the same runs and character and +/// paragraph attributes, its baseline starting where its first character sat on the path (in the +/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for +/// other type, or when it can't be placed. +fn released_text(t: &TextObject) -> Option { + let TextKind::OnPath { path, .. } = &t.kind else { return None }; + let db = vectorcraft_text::FontDb::global(); + // Where the first character sat. Text that didn't fit on the path has no glyph there: it + // starts at the start bracket. + let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| { + let ap = ArcPath::new(path); + let (from, _) = t.kind.path_span()?; + let (p, _) = ap.at(from * ap.len()); + (p.x.is_finite() && p.y.is_finite()).then_some(p) + })?; + let mut out = t.clone(); + out.kind = TextKind::Point; + out.path_effect = Default::default(); + out.path_align = Default::default(); + out.path_spacing = 0.0; + // Point type is in no thread: its first paragraph starts in it. + out.first_para_continues = false; + // Where the point type puts its own first character; the origin moves so it lands at `at`, + // whatever the paragraph's alignment and direction. + let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO); + let shift = at - own; + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + out.xf *= Affine::translate(shift); + refresh_bounds(&mut out); + Some(out) +} + +/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no +/// stroke: type paths carry no paint of their own. None for other type. +fn released_path(id: NodeId, t: &TextObject) -> Option { + Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0))) +} + +fn release_path(s: &mut Session, p: &Value) -> Result { + const C: &str = RELEASE; + let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both"); + let keep = switch_or(p, "keepOriginal", false, C)?; + let want_path = mode != "text"; + let ids = path_types(s, p)?; + if ids.is_empty() { + return Ok(json!({ "ids": [], "paths": [], "texts": [] })); + } + // The point type, worked out before the edit: one object that can't be placed fails the run. + let mut plans: Vec<(NodeId, Option)> = Vec::with_capacity(ids.len()); + { + let d = &s.doc()?.doc; + for id in ids { + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue }; + let text = match mode { + "path" => None, + _ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?), + }; + plans.push((id, text)); + } + } + let (paths, texts) = s.edit("Release Type on a Path", |d, sel| { + let (mut paths, mut texts) = (vec![], vec![]); + for (id, text) in plans { + let (path, text) = release_one(d, id, text, want_path, keep)?; + paths.extend(path); + texts.extend(text); + } + sel.set(paths.iter().chain(&texts).copied()); + Ok((paths, texts)) + })?; + // Bottom to top. + let d = &s.doc()?.doc; + let mut all: Vec<(Vec, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect(); + all.sort(); + let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::>(); + let all: Vec = all.into_iter().map(|(_, id)| id).collect(); + Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) })) +} + +/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it +/// when the original stays (`keep`), then the point type `text` (None: no text) above that. +/// Without `keep` the original goes, and released text takes its place as the same object, so a +/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's +/// does. The released (path, text). +fn release_one(d: &mut Document, id: NodeId, text: Option, want_path: bool, keep: bool) -> Result<(Option, Option)> { + let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) }; + let path = + if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None }; + if !keep && text.is_none() { + d.remove(id)?; + } + // Where the next released object goes: above the original when it stays, else in its place. + let mut at = if keep { idx + 1 } else { idx }; + let path = match path { + Some(n) => { + at += 1; + Some(d.insert(parent, at - 1, n)?) + } + None => None, + }; + let text = match text { + None => None, + Some(text) if keep => { + let mut n = original.clone(); + n.id = d.alloc_id(); + n.kind = NodeKind::Text(Box::new(text)); + Some(d.insert(parent, at, n)?) + } + Some(text) => { + // The original, now just above the path. + d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text)); + Some(id) + } + }; + Ok((path, text)) +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 7f05cb823a..e597525c97 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -1,5 +1,5 @@ //! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo -//! step, and bad params refused without a change. +//! step, and bad params refused without a change. Release Type on a Path ([`release`]). use serde_json::json; use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; @@ -221,3 +221,386 @@ fn it_needs_a_selection() { select(&mut s, &[]); assert!(s.execute(C, &json!({})).is_err()); } + +/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed, +/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text, +/// undo and redo, the preview a dialog shows, and bad params. +mod release { + use serde_json::{Value, json}; + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::{PathData, Point}; + + use crate::Session; + + const C: &str = "addon.type.releasePath"; + + fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s + } + + fn new_id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) + } + + /// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest + /// `at`, selected. + fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId { + let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap()); + select(s, &[id]); + id + } + + fn rect(s: &mut Session, x: f64) -> NodeId { + new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap()) + } + + fn point_type(s: &mut Session) -> NodeId { + new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap()) + } + + fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); + } + + fn doc(s: &Session) -> Document { + (*s.doc().unwrap().doc).clone() + } + + fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() + } + + fn text(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } + } + + fn path(s: &Session, id: NodeId) -> PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path.clone(), + k => panic!("not a path: {k:?}"), + } + } + + /// (parent, index) of `id`. + fn place(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, idx) + } + + /// Each glyph's pen position in the document and its baseline angle, in text order. + fn pens(t: &TextObject) -> Vec<(Point, f64)> { + let mut g: Vec<_> = + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect(); + g.sort_by_key(|g| g.0); + g.into_iter().map(|(_, p, a)| (p, a)).collect() + } + + /// How many path objects the document has. + fn paths_in(s: &Session) -> usize { + let mut n = 0; + for l in &s.doc().unwrap().doc.layers { + l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. }))); + } + n + } + + fn close(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-4 + } + + fn ids(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() + } + + /// `after`, released from `before`: point type with the same text and attributes, on one + /// straight line whose first character starts where `before`'s did on its path, with no Type + /// on a Path Options left. + fn assert_released(before: &TextObject, after: &TextObject) { + assert_eq!(after.kind, TextKind::Point); + assert_eq!(after.runs, before.runs, "the same text and character attributes"); + assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes"); + assert_eq!(after.plain_text(), before.plain_text()); + assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped"); + let (was, now) = (pens(before), pens(after)); + assert!(!now.is_empty()); + if let Some((first, _)) = was.first() { + assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0); + } + assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline"); + // On one line through the first pen, along the object's own x axis. + let [a, b, ..] = after.xf.as_coeffs(); + let axis = vectorcraft_geom::Vec2::new(a, b); + for (p, _) in &now { + let off = *p - now[0].0; + assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line"); + } + } + + #[test] + fn both_gives_point_type_and_the_path_in_the_types_place() { + let mut s = session(); + let below = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line"); + let above = rect(&mut s, 50.0); + select(&mut s, &[id]); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let (start, n) = (doc(&s), steps(&s)); + + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts")); + assert_eq!((paths.len(), texts.len()), (1, 1)); + let (p, t) = (paths[0], texts[0]); + assert_eq!(ids(&out, "ids"), [p, t], "bottom to top"); + assert_eq!(selected(&s), [p, t], "the released objects are selected"); + + // The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was. + assert_eq!(path(&s, p), before.type_path().unwrap()); + assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0)); + assert_eq!( + (place(&s, below), place(&s, p), place(&s, t), place(&s, above)), + ((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2)) + ); + // The text replaces the type on a path. + assert_released(&before, &text(&s, t)); + assert_eq!(t, id, "the same type object, now point type"); + + let released = doc(&s); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start, "undone"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s), released, "redone"); + } + + #[test] + fn path_only_and_text_only() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line"); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let out = s.execute(C, &json!({"mode": "path"})).unwrap(); + let p = ids(&out, "paths")[0]; + assert!(ids(&out, "texts").is_empty()); + assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone"); + assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx))); + assert_eq!(selected(&s), [p]); + + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text"})).unwrap(); + assert!(ids(&out, "paths").is_empty()); + assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place"); + assert_released(&before, &text(&s, id)); + assert_eq!(paths_in(&s), 0, "no path made"); + } + + #[test] + fn keep_original_adds_the_released_objects_above_it() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep"); + let (before, (layer, idx)) = (text(&s, id), place(&s, id)); + let original = s.doc().unwrap().doc.node(id).cloned().unwrap(); + let out = s.execute(C, &json!({"keepOriginal": true})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is"); + assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2))); + assert_ne!(t, id); + assert_eq!(selected(&s), [p, t], "only the released objects are selected"); + assert_released(&before, &text(&s, t)); + + // Text only, kept: the copy goes just above. + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap(); + let t2 = ids(&out, "texts")[0]; + assert_eq!(place(&s, t2), (layer, idx + 1)); + assert_released(&before, &text(&s, t2)); + } + + #[test] + fn other_objects_are_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One"); + let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two"); + let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()); + select(&mut s, &[r, pt, a, b]); + let n = steps(&s); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for the whole selection"); + assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b])); + assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others); + assert_eq!(selected(&s).len(), 4, "the two paths and the two texts"); + assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt)); + + // `ids` picks the objects instead of the selection. + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[r]); + let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap(); + assert_eq!(ids(&out, "texts"), [b]); + assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. })); + } + + #[test] + fn nothing_to_release_changes_nothing() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + select(&mut s, &[r, pt]); + let (before, n, sel) = (doc(&s), steps(&s), selected(&s)); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []})); + assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step"); + } + + #[test] + fn closed_and_open_paths_keep_their_shape() { + for (d, closed) in [ + ("M200 200 L400 200 L400 400 L200 400 Z", true), + ("M100 300 C150 100 250 500 300 300 S450 100 500 300", false), + ("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true), + ] { + let mut s = session(); + let id = path_type(&mut s, d, [200.0, 200.0], "Round and round"); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + let p = path(&s, ids(&out, "paths")[0]); + assert_eq!(p, before.type_path().unwrap(), "{d}"); + assert_eq!(p.is_closed(), closed, "{d}"); + assert_released(&before, &text(&s, ids(&out, "texts")[0])); + } + } + + #[test] + fn flipped_type_releases_its_path_as_it_runs() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped"); + s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap()); + assert_released(&before, &text(&s, id)); + } + + #[test] + fn transformed_type_keeps_its_transform() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned"); + s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path"); + let after = text(&s, id); + assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was"); + assert_released(&before, &after); + } + + #[test] + fn grouped_type_releases_inside_its_group() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped"); + select(&mut s, &[r, id]); + s.execute("object.group", &json!({})).unwrap(); + let g = place(&s, id).0.unwrap(); + assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. })); + select(&mut s, &[g]); + let out = s.execute(C, &json!({})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g))); + } + + #[test] + fn styles_and_unicode_text_survive() { + let mut s = session(); + let words = "Größe ✓ 日本語 éa"; + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words); + // "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ "). + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap(); + // A centred paragraph: the first character still starts where it sat. + s.edit("centre", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.justify = Justify::Center; + } + Ok(()) + }) + .unwrap(); + let before = text(&s, id); + assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs); + let out = s.execute(C, &json!({})).unwrap(); + let after = text(&s, ids(&out, "texts")[0]); + assert_eq!(after.plain_text(), words); + assert_released(&before, &after); + } + + #[test] + fn empty_type_starts_at_its_start_bracket() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], ""); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(ids(&out, "texts"), [id]); + let t = text(&s, id); + assert_eq!(t.kind, TextKind::Point); + assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO); + } + + /// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with + /// no step of history, and OK keeps the preview as one step. + #[test] + fn previews_cancel_and_commit() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview"); + let (start, n, sel) = (doc(&s), steps(&s), selected(&s)); + let count = paths_in; + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point)); + s.preview(C, &json!({"mode": "text"})).unwrap(); + assert_eq!(count(&s), 0, "the next preview replaces the last"); + s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap(); + assert_eq!(count(&s), 1); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + s.cancel_interaction().unwrap(); + assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step"); + + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(steps(&s), n + 1, "OK: one step"); + assert_eq!(text(&s, id).kind, TextKind::Point); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start); + } + + #[test] + fn bad_params_are_refused_without_a_change() { + let mut s = session(); + path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad"); + let (before, n) = (doc(&s), steps(&s)); + for p in [ + json!({"mode": "all"}), + json!({"mode": 1}), + json!({"keepOriginal": "yes"}), + json!({"ids": [999_999]}), + json!({"ids": "1"}), + json!({"id": -1}), + json!({"colour": "red"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}"); + } + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 8fb5734efd..6507001c71 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -276,22 +276,24 @@ impl ItemTarget { /// This target for each of `ids` (in their order): an aligned item (a row of the first /// target's stack, or for the active item of the first selected object's, see /// [`ItemTarget::anchor`]) is, in each other target, the item equal to it there (see - /// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the - /// targets don't share, and any other target, stands for itself in every target. + /// [`SharedStack`]), each target matched against that stack on its own, whatever the other + /// targets have. In a target without an equal item, and for any other target, the row stands + /// for itself. Every entry is `Some`. pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec> { let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; let k = self.anchor(s, ids); - let mut order = ids.to_vec(); - order.swap(0, k); - let Some(shared) = shared_stack(&st.doc, &order) else { return vec![Some(self); ids.len()] }; - if !shared.has_item(index) { - return vec![Some(self); ids.len()]; - } - let mut per: Vec> = - (0..order.len()).map(|j| shared.item_in(index, j).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect(); - per.swap(0, k); - per + let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] }; + ids.iter() + .enumerate() + .map(|(j, id)| match st.doc.node(*id) { + Some(n) if j != k => { + let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1); + Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true })) + } + _ => Some(self), + }) + .collect() } /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 77a61c58a4..6ab7acad0b 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -347,10 +347,8 @@ fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; let sym = d.symbols.iter().find(|s| &s.name == symbol)?; let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() }; - if let Some(f) = inst.appearance.fill() - && let Some(c) = f.paint.color() - { - brush::tint_node(&mut art, &c, f.opacity); + if let Some((color, amount)) = brush::stain(inst) { + brush::tint_node(&mut art, &color, amount); } let art = d.place_symbol_art(symbol, &art, *xf)?; let mut art = d.reid(&art); 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/create.rs b/crates/engine/src/cmd/create.rs index 00ea88ea64..ab3dc966ce 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -833,7 +833,10 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), }; - // In the document's language (Document Setup), none for the default. - style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string); + // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none + // for the default. Type already in a document keeps its own. + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); style } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 4a063d1ebb..fc459d5550 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 way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does", + "{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), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), 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 way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 0e67b7c57a..7820e378e2 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -12,7 +12,7 @@ use super::{ /// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay /// corners) and simplify it to `tol`. fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { - let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3); + let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3); let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) }; let mut kept: Vec = vec![p0]; for &p in pts.iter().skip(1) { @@ -382,12 +382,15 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } let pen = PenRecord::of_samples(&samples); let mut pts: Vec = samples.into_iter().map(|s| s.pt).collect(); - let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0); + let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0); // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; let brush = str_param(p, "style") == Some("brush"); let keep_selected = switch_or(p, "keepSelected", true, C)?; + // The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the + // selection as it is: the path being redrawn stays selected until the release redraws it. + let leave_selection = switch_or(p, "leaveSelection", false, C)?; let filled = switch_or(p, "fill", false, C)?; if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?; @@ -570,7 +573,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 && !leave_selection { + // 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/edit.rs b/crates/engine/src/cmd/edit.rs index 41276c2326..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; @@ -29,6 +29,15 @@ pub fn specs() -> Vec { ), cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close), cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate), + cmd!( + "document.move", + "Move Document", + [], + None, + "{from?: index (default: the current document), to: index (0 = the first tab; past the last document = the last tab)} → {index}: moves the document to tab `to`, as dragging its tab along the tab strip does; the documents between shift by one, the order Window › Next/Previous Document steps through follows, and the current document stays the current one", + has_doc, + doc_move + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -222,6 +231,23 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_move(s: &mut Session, p: &Value) -> Result { + let n = s.documents().len(); + let from = match p.get("from") { + None | Some(Value::Null) => s.active_index().ok_or(EngineError::NoDocument)?, + Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`from` must be a non-negative integer"))?, + }; + if from >= n { + return Err(bad("document.move", "no such document")); + } + let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?; + let to = to.min(n.saturating_sub(1)); + if !s.move_document(from, to) { + return Err(bad("document.move", "no such document")); + } + Ok(json!({ "index": to })) +} + fn doc_node(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?; let mut opts = slice_opts(p, "document.node")?; @@ -600,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` @@ -611,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). @@ -632,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()), } }) @@ -663,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. @@ -678,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() @@ -703,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). @@ -730,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. @@ -743,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() @@ -777,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() { @@ -848,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. @@ -881,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 }; @@ -949,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()); @@ -990,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/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 54d0176a3e..1fcd4602ed 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -8,11 +8,12 @@ use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_doc::appearance::SharedStack; use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData}; use vectorcraft_render::effects; -use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at, shared_stack}; +use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at}; use super::expand::has_seeded; use super::rasterfx; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param}; @@ -105,24 +106,23 @@ fn ids_json(ids: &[NodeId]) -> Value { /// Each target of an effect edit aimed at `item` and effect `index`: the object, the item whose /// effects it edits (`None`: the object's own) and the effect's index there. With `aligned` (see /// [`ItemTarget::per_target`]) `item` and `index` are the first target's, and each other target -/// edits its equal item, or its equal object-level effect; a target without them is left out. +/// edits its equal item, or its equal object-level effect, each target matched on its own whatever +/// the other targets have; in a target without them, `item` and `index` stand for themselves. pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result, usize)>> { let roots = appearance_targets(s, p)?; let d = &s.doc()?.doc; let per = item.per_target(s, &roots); - let shared = if aligned(p) { shared_stack(d, &roots) } else { None }; + let first = roots.first().and_then(|f| d.node(*f)); + // Whether `item` names an item in the stack it is a row of (else the edit is object-level there). + let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a)); + let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten(); let mut out = Vec::with_capacity(roots.len()); - for (k, (id, item)) in roots.iter().zip(per).enumerate() { + for (id, item) in roots.iter().zip(per) { let (Some(item), Some(n)) = (item, d.node(*id)) else { continue }; let at = item.effects_item(&n.appearance, cmd)?; - // An object-level effect the targets share is, in each, where it is there. - let first = roots.first().and_then(|f| d.node(*f)); - let first_level = first.map(|f| item.effects_item(&f.appearance, cmd)).transpose()?.flatten(); - let index = match (&shared, at, first_level) { - (Some(sh), None, None) if sh.has_effect(index) => match sh.effect_in(index, k) { - Some(i) => i, - None => continue, - }, + // An object-level effect this target shares with the first is where it is in this target. + let index = match (first.filter(|_| aligned(p)), at, anchor_level) { + (Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index), _ => index, }; out.push((*id, at, index)); @@ -758,14 +758,18 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); m }) - } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) { + } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && !effects::has_transform_art(&v) + && !effects::has_transform_copies(&v) + { effects::expand_leaf(d, &v, &mut stroke_art) } else { // Type, images, symbol instances, live objects (and paths whose Transform effect copies - // them with a gradient or changes their fills and strokes): through their outlines. + // them, each copy an object of its own, or changes their fills and strokes): through + // their outlines. let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { - d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, &n)) + d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n)) } _ => None, }; diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 7e44e07726..ce8f511834 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -366,14 +366,16 @@ fn expand_appearance_bakes_geometry() { assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); } +/// Each copy is an object of its own (#5612). #[test] -fn expand_transform_copies_makes_compound() { +fn expand_transform_copies_makes_a_group_of_the_copies() { let (mut s, id) = session_with_rect(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap(); s.execute("effect.expandAppearance", &json!({})).unwrap(); let n = node(&s, id); - assert!(matches!(n.kind, NodeKind::Compound { .. })); + assert!(matches!(n.kind, NodeKind::Group { .. }), "{}", n.kind_label()); + assert_eq!(n.children().map(|c| c.len()), Some(2)); let b = n.geometric_bounds().unwrap(); assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}"); } @@ -474,6 +476,53 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() { assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient"); } +/// Expand Appearance on a solid-filled path whose Transform effect makes copies gives a group of +/// one path per copy, each with the path's fill, not one compound path (#5612); a second Transform +/// effect's copies of those copies nest, a group per copy of the first. +#[test] +fn expand_appearance_makes_each_copy_of_a_transform_an_object() { + use vectorcraft_color::{Color, Paint}; + let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint().color(); + let (mut s, id) = session_with_rect(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "{}", n.kind_label()); + assert!(n.appearance.effects.is_empty()); + let copies = n.children().unwrap(); + assert_eq!(copies.len(), 3, "the path and its two copies"); + let xs: Vec = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect(); + assert_eq!(xs, vec![100.0, 250.0, 400.0]); + for c in copies { + assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label()); + assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!((c.geometric_bounds().unwrap().width() - 100.0).abs() < 1e-9); + } + let mut ids: Vec = vec![]; + n.walk(&mut |c| ids.push(c.id)); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), 4, "the group and each copy have ids of their own"); + // Two Transform effects: three columns, each a group of the column's two copies. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":1,"params":{"moveV":150,"copies":1},"ids":[id.0],"item":null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let columns = node(&s, id).children().unwrap().to_vec(); + assert_eq!(columns.len(), 3); + for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) { + let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label())); + let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect(); + assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]); + assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. }))); + } +} + /// The object's own effect ids, in order. fn object_effects(s: &Session, id: NodeId) -> Vec { node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect() 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 ae7c66aa8b..b87ec3ee2e 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -404,6 +404,35 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } +/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document +/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from +/// before that opens with the radius converted, drawing the same dots; one saved since opens as +/// it was. +#[test] +fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() { + let halftone = |old: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0); + s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap(); + if old { + // As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1; + } + let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap()); + let opened = open(&mut s, "halftone.pdf", &pdf); + assert_eq!(opened["restored"], json!(true), "{opened}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION); + let n = d.node(vectorcraft_doc::NodeId(r)).unwrap(); + n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap() + }; + // 8 pt at 300 ppi are 33⅓ px. + assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true)); + assert_eq!(halftone(false), 8.0); +} + /// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded. fn outline(doc: &vectorcraft_doc::Document) -> Vec { fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { @@ -623,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/fileio/tests_svgedit.rs b/crates/engine/src/cmd/fileio/tests_svgedit.rs index 06f9888469..4b0998c643 100644 --- a/crates/engine/src/cmd/fileio/tests_svgedit.rs +++ b/crates/engine/src/cmd/fileio/tests_svgedit.rs @@ -12,7 +12,7 @@ fn new_id(v: &Value) -> u64 { v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}")) } -fn rect(s: &mut Session, x: f64, y: f64) -> u64 { +pub(super) fn rect(s: &mut Session, x: f64, y: f64) -> u64 { new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()) } 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/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index b958f51c16..2b0e214cc0 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -262,7 +262,59 @@ impl Form { /// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists /// images, text, masks and links as unsupported). fn supported(n: &Node) -> bool { - n.extras().mask.is_none() && Form::of(n).is_some() + n.extras().mask.is_none() && has_form(n) +} + +/// Does [`Form::of`] give `n` a form? The same walk and the same box, without collecting the +/// points or placing them in a unit box. +fn has_form(n: &Node) -> bool { + let mut b = None; + form_box(n, 0, &mut b).is_some() + && b.is_some_and(|b: Rect| { + let side = b.width().max(b.height()); + side.is_finite() && side > 1e-9 + }) +} + +/// [`Form::add`] without the form: `b` grows by each point it would add; `None` when `n` isn't +/// supported. +fn form_box(n: &Node, depth: usize, b: &mut Option) -> Option<()> { + match &n.kind { + NodeKind::Path { path, clipping, guide: false, .. } if !*clipping || depth > 0 => grow_by_path(b, path), + NodeKind::Compound { children, .. } => { + for c in children { + grow_by_path(b, c.path_data()?); + } + } + NodeKind::SymbolInstance { xf, .. } => { + for p in [*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)] { + grow(b, p); + } + } + NodeKind::Group { children, .. } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => { + for c in children { + if c.extras().mask.is_some() { + return None; + } + form_box(c, depth + 1, b)?; + } + } + _ => return None, + } + Some(()) +} + +fn grow_by_path(b: &mut Option, path: &PathData) { + for a in path.subpaths.iter().flat_map(|sp| &sp.anchors) { + for p in [a.p, a.h_in, a.h_out] { + grow(b, p); + } + } +} + +/// `b` grown to take in `p`, as [`Form::of`] measures its points. +fn grow(b: &mut Option, p: Point) { + *b = Some(b.unwrap_or(Rect::from_points(p, p)).union_pt(p)); } /// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension, @@ -374,8 +426,9 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> { let [id] = st.selection.objects.as_slice() else { return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into()); }; - // A group's contents are checked when Global Edit starts: building its shape here would walk - // every object in it each time the menu or the Properties panel asks. + // A group's contents are checked when Global Edit starts: measuring them here would walk + // every object in it each time the menu or the Properties panel asks. Other objects are + // measured ([`supported`]), not reduced to their form: the Control bar asks every frame. match st.doc.node(*id) { Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()), Some(n) if supported(n) => Ok(()), @@ -750,3 +803,195 @@ pub fn highlights(s: &Session) -> Outlines { *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use vectorcraft_doc::OpacityMask; + use vectorcraft_geom::{Anchor, SubPath}; + + /// Global Edit's support as it was decided by building the form. + fn by_form(n: &Node) -> bool { + n.extras().mask.is_none() && Form::of(n).is_some() + } + + /// A small seeded generator (xorshift64*), so that a failure repeats. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + /// A spread for the points of one object: none, below and around the smallest size a form + /// takes, ordinary, or past every bound. + fn spread(&mut self) -> f64 { + [0.0, 1e-10, 5e-10, 1e-9, 2e-9, 1.0, 1.0, 100.0, 100.0, 100.0, f64::INFINITY, f64::NAN][self.below(12) as usize] + } + fn point(&mut self, base: Point, spread: f64) -> Point { + let mut c = |b: f64| match self.below(400) { + 0 => f64::NAN, + 1 => f64::INFINITY, + 2 => f64::NEG_INFINITY, + _ => b + (self.unit() - 0.5) * spread, + }; + Point::new(c(base.x), c(base.y)) + } + } + + fn path_data(r: &mut Rng) -> PathData { + let (base, spread) = (Point::new(r.unit() * 200.0, r.unit() * 200.0), r.spread()); + let subpaths = (0..r.below(3)) + .map(|_| { + let anchors = (0..r.below(4)) + .map(|_| Anchor { p: r.point(base, spread), h_in: r.point(base, spread), h_out: r.point(base, spread), ..Anchor::corner(base) }) + .collect(); + SubPath::new(anchors, r.below(2) == 0) + }) + .collect(); + PathData::new(subpaths) + } + + /// A random object: paths (clipping paths and guides too), compound paths, symbol instances, + /// groups (clip groups, live art, members with an opacity mask), type, blends and intertwined + /// objects, any of them with an opacity mask. + fn object(r: &mut Rng, d: &mut Document, text: &Node, depth: usize) -> Node { + let leaf = depth >= 3; + let mut n = match r.below(if leaf { 4 } else { 8 }) { + 0 | 1 => { + let mut n = Node::path(d.alloc_id(), path_data(r), Appearance::default()); + if let NodeKind::Path { clipping, guide, .. } = &mut n.kind { + *clipping = r.below(6) == 0; + *guide = r.below(8) == 0; + } + n + } + 2 => { + let xf = match r.below(4) { + 0 => Affine::scale(0.0), + 1 => Affine::scale(1e-10), + _ => Affine::translate((r.unit() * 100.0, r.unit() * 100.0)) * Affine::scale(r.spread()), + }; + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf }) + } + 3 => { + let mut t = text.clone(); + t.id = d.alloc_id(); + t + } + 4 => { + let children = (0..r.below(4)) + .map(|_| match r.below(5) { + 0 => Arc::new(object(r, d, text, depth + 1)), + _ => Arc::new(Node::path(d.alloc_id(), path_data(r), Appearance::default())), + }) + .collect(); + Node::new(d.alloc_id(), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::NonZero }) + } + 5 => { + let children = (0..r.below(3)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::default() }) + } + _ => { + let children = (0..r.below(4)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children, clip: r.below(3) == 0 }); + if r.below(8) == 0 { + g.extras_mut().trace = Some(Box::new(Value::Null)); + } + g + } + }; + if r.below(10) == 0 { + n.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), path_data(r), Appearance::default()), true))); + } + n + } + + /// `n` and every object in it. + fn every(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |c| out.push(c.clone())); + out + } + + #[test] + fn support_is_decided_as_building_the_form_decides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let text = s.doc().unwrap().doc.node(t).unwrap().clone(); + let layer = s.doc().unwrap().doc.layers[0].id; + let (mut checked, mut taken, mut asked) = (0, 0, 0); + for seed in 1..=400u64 { + let mut r = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1); + let n = object(&mut r, Arc::make_mut(&mut s.doc_mut().unwrap().doc), &text, 0); + for c in every(&n) { + assert_eq!(supported(&c), by_form(&c), "seed {seed}: {c:?}"); + checked += 1; + taken += usize::from(by_form(&c)); + } + // The enabled check of Start Global Edit on it, and Start Global Edit itself. + let id = Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, n.clone()).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + if s.doc().unwrap().selection.objects != [id] { + continue; + } + asked += 1; + let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n); + assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}"); + match s.execute(C, &json!({})) { + Ok(_) => { + assert!(by_form(&n), "seed {seed}"); + s.execute(C, &json!({})).unwrap(); + } + Err(e) => assert_eq!(e.to_string().contains(UNSUPPORTED), !by_form(&n), "seed {seed}: {e}"), + } + } + // Both answers came up often, and most objects could be selected alone. + assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected"); + } + + #[test] + fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() { + let mut d = Document::new(800.0, 600.0); + let corner = |x: f64, y: f64| Anchor::corner(Point::new(x, y)); + let path = |d: &mut Document, subpaths: Vec| Node::path(d.alloc_id(), PathData::new(subpaths), Appearance::default()); + let mut cases = vec![ + path(&mut d, vec![]), + path(&mut d, vec![SubPath::new(vec![], true)]), + path(&mut d, vec![SubPath::new(vec![corner(5.0, 5.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 1e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 2e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(f64::INFINITY, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, 0.0), corner(10.0, 0.0), corner(0.0, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, f64::NAN)], false)]), + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![], rule: Default::default() }), + Node::group(d.alloc_id(), vec![]), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::scale(0.0) }), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }), + ]; + // A group as deep as the walk goes, and one level deeper. + let mut deep = path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(10.0, 10.0)], false)]); + for _ in 0..=vectorcraft_doc::MAX_DEPTH { + deep = Node::group(d.alloc_id(), vec![Arc::new(deep)]); + cases.push(deep.clone()); + } + let expected = [false, false, false, false, true, false, true, false, false, false, false, true]; + for (i, n) in cases.iter().enumerate() { + assert_eq!(supported(n), by_form(n), "case {i}: {n:?}"); + if let Some(e) = expected.get(i) { + assert_eq!(supported(n), *e, "case {i}"); + } + } + assert!(supported(&cases[cases.len() - 2]) && !supported(&cases[cases.len() - 1])); + } +} diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 2fddbe9635..47989a29c0 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (a CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), @@ -197,7 +197,8 @@ pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColo /// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid /// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the /// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with -/// [`link_stops`]). The result is sorted by offset. +/// [`link_stops`]), and `plates` (C, M, Y, K, 0..1) the process inks a linked stop prints with its +/// spot ink. The result is sorted by offset. pub(crate) fn parse_stops(v: &Value) -> Parsed> { let arr = v.as_array().ok_or("`stops` must be an array")?; if arr.len() < 2 { @@ -213,6 +214,10 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0); let swatch = str_param(st, "swatch").map(str::to_string); let tint = num("tint")?.filter(|_| swatch.is_some()).map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32); + let plates = match st.get("plates").filter(|_| swatch.is_some()) { + None | Some(Value::Null) => None, + Some(p) => Some(plates_param(p).ok_or_else(|| format!("stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K)"))?), + }; Ok(GradientStop { offset: offset.clamp(0.0, 1.0) as f32, color, @@ -220,6 +225,7 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32, swatch, tint, + plates, }) }) .collect::>>()?; @@ -227,6 +233,17 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { Ok(out) } +/// A stop's `plates` param: the process inks (C, M, Y, K, 0..1) printed with its spot swatch. +fn plates_param(v: &Value) -> Option<[f32; 4]> { + let a = v.as_array().filter(|a| a.len() == 4)?; + let mut out = [0.0f32; 4]; + for (o, x) in out.iter_mut().zip(a) { + let x = x.as_f64().filter(|x| x.is_finite())?; + *o = x.clamp(0.0, 1.0) as f32; + } + Some(out) +} + /// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything /// `vectorcraft_tools::params::gradient_params` writes. pub(crate) fn parse_gradient(g: &Value) -> Parsed { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 6b21673af6..97293f36c0 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -945,9 +945,17 @@ pub(crate) fn empty_artboards(d: &Document) -> Vec { empty } +/// Is [`empty_artboards`] of `d` not empty? A document with one artboard keeps it, so there is +/// nothing to delete; with two or more, any unlocked artboard without art settles it (when every +/// artboard is empty, all but artboard 1 go). [`Document::any_artboard_without_art`] finds an +/// artboard away from every path without measuring along the paths. +fn any_empty_artboards(d: &Document) -> bool { + d.artboards.len() > 1 && d.any_artboard_without_art(d.artboards.iter().filter(|a| !a.locked).map(|a| a.rect)) +} + fn has_empty_artboards(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; - if empty_artboards(&st.doc).is_empty() { Err("no empty artboards to delete".into()) } else { Ok(()) } + if any_empty_artboards(&st.doc) { Ok(()) } else { Err("no empty artboards to delete".into()) } } fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result { @@ -1164,3 +1172,151 @@ fn artboard_fit_sel(s: &mut Session, p: &Value) -> Result { let b = st.doc.bounds_of(&st.selection.objects, true).ok_or_else(|| EngineError::Other("no selection bounds".into()))?; s.execute("artboard.setProps", &json!({"index": i, "x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()})) } + +#[cfg(test)] +mod tests { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, StrokeAlign, StrokeLayer, SymbolBoxes}; + + use super::*; + + /// Does art lie on `rect`, measuring every object's visual bounds: the rule of + /// [`Document::artboard_has_art`] with no quick box in front of it. + fn measured_has_art(d: &Document, rect: Rect) -> bool { + let rect = rect.inflate(1e-6, 1e-6); + fn meets(b: Option, r: Rect) -> bool { + b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1) + } + fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool { + match &c.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + let Some((clip, rest)) = children.split_first() else { return false }; + let paint = clip.clip_paint(); + if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) { + return true; + } + let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false }; + let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1)); + rest.iter().any(|m| has(m, s, inside)) + } + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)), + NodeKind::Path { guide: true, .. } => false, + _ => meets(c.visual_bounds_with(s), rect), + } + } + let symbols = d.symbol_boxes(); + d.layers.iter().any(|l| has(l, &symbols, rect)) + } + + /// Would Delete Empty Artboards delete something, by [`measured_has_art`] of each artboard: + /// the unlocked artboards without art, less artboard 1 when that is every artboard. + fn measured_any_empty(d: &Document) -> bool { + let mut empty: Vec = + d.artboards.iter().enumerate().filter(|(_, a)| !a.locked && !measured_has_art(d, a.rect)).map(|(i, _)| i).collect(); + if empty.len() == d.artboards.len() { + empty.retain(|&i| i != 0); + } + !empty.is_empty() + } + + /// On documents made from a fixed seed (one to five artboards placed anywhere, overlapping + /// some of the time, some locked; rectangles, long curved paths and symbol instances, some + /// with wide strokes reaching past their shape, some grouped or clipped), the menu's check + /// [`any_empty_artboards`] gives the same answer as `!empty_artboards(d).is_empty()` and as + /// measuring every object against every artboard, and both answers come up. + #[test] + fn the_empty_artboard_check_matches_measuring_every_artboard() { + let mut seed: u64 = 0x0a2d_5eed_e4b7; + let mut next = |n: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + let (mut enabled, mut disabled_with_art) = (0, 0); + for _ in 0..120 { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); + for _ in 0..next(5) { + let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0); + s.execute("artboard.new", &json!({"x": x, "y": y, "width": 20 + next(300), "height": 20 + next(200)})).unwrap(); + } + let artboards = s.doc().unwrap().doc.artboards.len(); + for i in 0..artboards { + if next(5) == 0 { + s.execute("artboard.setProps", &json!({"index": i, "locked": true})).unwrap(); + } + } + let mut symbol = false; + let mut ids = vec![]; + for _ in 0..next(6) { + let id = match next(4) { + 0 => { + let (segments, span) = (20 + next(80), 10 + next(700)); + let (x, y) = (next(1400) as i64 - 100, next(800) as i64 - 100); + let mut pt = || format!("{} {}", x + next(span) as i64, y + next(span) as i64); + let mut d = format!("M {}", pt()); + for _ in 0..segments { + d += &format!(" C {} {} {}", pt(), pt(), pt()); + } + s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap() + } + 1 => { + let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0); + if !symbol { + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5 + next(60), "height": 5 + next(60)})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [r["id"]]})).unwrap(); + s.execute("object.delete", &json!({"ids": [r["id"]]})).ok(); + symbol = true; + } + s.execute("symbol.place", &json!({"name": "Mark", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap() + } + _ => { + let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0); + let r = json!({"x": x, "y": y, "width": 1 + next(150), "height": 1 + next(150)}); + s.execute("shape.rectangle", &r).unwrap()["id"].as_u64().unwrap() + } + }; + if next(2) == 0 { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 1.0 + next(120) as f64); + st.join = [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel][next(3) as usize]; + st.cap = [LineCap::Butt, LineCap::Round, LineCap::Square][next(3) as usize]; + st.align = [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside][next(3) as usize]; + st.miter_limit = 1.0 + next(20) as f64; + let look = Appearance { items: vec![AppearanceItem::Stroke(st)], ..Appearance::default() }; + s.edit("Strokes", |d, _| { + d.node_mut(NodeId(id)).unwrap().appearance = look.into(); + Ok(()) + }) + .unwrap(); + } + ids.push(id); + } + if ids.len() > 1 { + match next(3) { + 0 => { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + 1 => { + let (x, y) = (next(1400) as f64 - 100.0, next(800) as f64 - 100.0); + let clip = json!({"x": x, "y": y, "width": 1 + next(400), "height": 1 + next(300)}); + let clip = s.execute("shape.rectangle", &clip).unwrap()["id"].as_u64().unwrap(); + let members: Vec = ids.iter().copied().chain([clip]).collect(); + s.execute("select.set", &json!({"ids": members})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + } + _ => {} + } + } + let d = &s.doc().unwrap().doc; + let measured = measured_any_empty(d); + let at = || d.artboards.iter().map(|a| (a.rect, a.locked)).collect::>(); + assert_eq!(any_empty_artboards(d), measured, "{:?}", at()); + assert_eq!(!empty_artboards(d).is_empty(), measured, "{:?}", at()); + enabled += usize::from(measured); + let several = d.artboards.len() > 1 && !ids.is_empty(); + disabled_with_art += usize::from(several && !measured); + } + assert!(enabled > 15 && enabled < 105, "both answers come up: {enabled} of 120 enabled"); + assert!(disabled_with_art > 3, "documents with several artboards and art come up disabled: {disabled_with_art}"); + } +} 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/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index e608bb43c2..95f8c3e8fd 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -97,7 +97,7 @@ pub fn specs() -> Vec { "Transform Each…", ["Object", "Transform"], Some("Cmd+Alt+Shift+D"), - "{scaleH?: % (100), scaleV?: % (100), moveH?: pt, moveV?: pt (down = +), rotate?: deg (counter-clockwise), reflectX?: bool (flip left-right, as Reflect X in the Transform Each dialog), reflectY?: bool (flip top-bottom, as Reflect Y), random?: bool, seed?: n, reference?: 0..8 (9-point grid, 4 = centre), copy?: bool, strokes?: bool (Scale Strokes & Effects), corners?: bool (Scale Corners; both default to the preferences), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns; default: prefs transformPatternTiles)} transform every selected object about its own reference point → {ids}", + "{scaleH?: % (100), scaleV?: % (100), relative?: bool (true: scaleH and scaleV are percentages of each object's size, as the dialog's Relative; false: Absolute, scaleH and scaleV are the width and height in pt each object becomes, measured on its own bounds, and a side left out keeps its size), moveH?: pt, moveV?: pt (down = +), rotate?: deg (counter-clockwise), reflectX?: bool (flip left-right, as Reflect X in the Transform Each dialog), reflectY?: bool (flip top-bottom, as Reflect Y), random?: bool, seed?: n, reference?: 0..8 (9-point grid, 4 = centre), copy?: bool, strokes?: bool (Scale Strokes & Effects), corners?: bool (Scale Corners; both default to the preferences), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns; default: prefs transformPatternTiles)} transform every selected object about the reference point of its own box, along its own axes → {ids}", has_selection, transform_each ), @@ -454,6 +454,30 @@ fn about(o: Point, a: Affine) -> Affine { Affine::translate(o.to_vec2()) * a * Affine::translate(-o.to_vec2()) } +/// The largest width or height (pt) an Absolute Transform Each takes, so coordinates stay finite. +const MAX_ABSOLUTE: f64 = 1.0e7; + +/// The box a symbol instance or any other object has of its own, rotated with it, as the Transform +/// panel and the Control bar show it: Absolute Transform Each measures its targets on this, with +/// `symbols` shared so many instances of one symbol measure its art once. +fn own_box(doc: &vectorcraft_doc::Document, id: NodeId, symbols: &vectorcraft_doc::SymbolBoxes) -> Option { + doc.oriented_bounds_with(&[id], false, symbols).map(|b| b.rect) +} + +/// Whether Absolute scaling by `target` leaves a side of `current` as it is, to within a millionth +/// of the size: a square turned 45° measures 100.00000000000001 in its own box, and the size it +/// shows must not scale it. +fn keeps_size(target: f64, current: f64) -> bool { + (scale_factor(target, current) - 1.0).abs() <= 1.0e-9 +} + +/// The factor that takes `current` to `target` (Absolute Transform Each). A side of 0 (a line) +/// keeps its factor 1, since no factor gives it another size, and the factor is bounded as the +/// moves are, so a hairline side can't throw coordinates past what a document can hold. +fn scale_factor(target: f64, current: f64) -> f64 { + if current.abs() > 1.0e-9 { (target / current).clamp(-1.0e7, 1.0e7) } else { 1.0 } +} + fn transform_each(s: &mut Session, p: &Value) -> Result { transform_each_as(s, p, "Transform Each") } @@ -470,9 +494,17 @@ pub(crate) fn transform_each_again(s: &mut Session, p: &Value) -> Result fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result { let roots = selected_roots(s)?; check_numbers(p, &["scaleH", "scaleV", "moveH", "moveV", "rotate"], "object.transformEach")?; + // Relative (the default) scales each object by a percentage of its own size; Absolute + // (`relative: false`, the dialog's Absolute) takes each object to the width and height given, + // a side left out staying as it is. + let relative = switch_or(p, "relative", true, "object.transformEach")?; // Bounded so coordinates stay finite (and the document stays serializable). - let sh = f64_or(p, "scaleH", 100.0).clamp(-100_000.0, 100_000.0); - let sv = f64_or(p, "scaleV", 100.0).clamp(-100_000.0, 100_000.0); + let given = |key: &str| p.get(key).filter(|v| !v.is_null()).and_then(Value::as_f64).map(|v| v.clamp(-MAX_ABSOLUTE, MAX_ABSOLUTE)); + let (sh, sv) = if relative { + (Some(f64_or(p, "scaleH", 100.0).clamp(-100_000.0, 100_000.0)), Some(f64_or(p, "scaleV", 100.0).clamp(-100_000.0, 100_000.0))) + } else { + (given("scaleH"), given("scaleV")) + }; let mh = f64_or(p, "moveH", 0.0).clamp(-1.0e7, 1.0e7); let mv = f64_or(p, "moveV", 0.0).clamp(-1.0e7, 1.0e7); let rot = f64_or(p, "rotate", 0.0); @@ -483,16 +515,26 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result { let copy = switch_or(p, "copy", false, "object.transformEach")?; check_switches(p, &["strokes", "corners", "objects", "patterns"], "object.transformEach")?; let objects = super::object::transforms_objects(p); - if sh == 0.0 || sv == 0.0 { + if sh == Some(0.0) || sv == Some(0.0) { return Err(bad("object.transformEach", "scale must be non-zero")); } let mut rng = Rng(whole_or(p, "seed", 0x9E37_79B9_7F4A_7C15, "object.transformEach")?.max(1)); - let mut sc = if sh != 100.0 || sv != 100.0 { super::object::scaling(s, p) } else { Default::default() }; + let mut sc = if !relative || sh != Some(100.0) || sv != Some(100.0) { super::object::scaling(s, p) } else { Default::default() }; sc.patterns = super::object::transform_patterns(s, p, &roots)?; - // With no object to transform, or without a copy when both scales are 100% and there is no - // move, rotation or reflection (with or without Random), the document and its undo history - // stay as they are. - if roots.is_empty() || (!copy && sh == 100.0 && sv == 100.0 && mh == 0.0 && mv == 0.0 && rot == 0.0 && !rx && !ry) { + // With no object to transform, or without a copy when nothing would change (both scales 100% + // or, with Absolute, the size each object already has, and no move, rotation or reflection, + // with or without Random), the document and its undo history stay as they are. + let scales_change = if relative { + sh != Some(100.0) || sv != Some(100.0) + } else { + let doc = &s.doc()?.doc; + let symbols = doc.symbol_boxes(); + roots.iter().any(|id| { + own_box(doc, *id, &symbols) + .is_some_and(|b| sh.is_some_and(|v| !keeps_size(v, b.width())) || sv.is_some_and(|v| !keeps_size(v, b.height()))) + }) + }; + if roots.is_empty() || (!copy && !scales_change && mh == 0.0 && mv == 0.0 && rot == 0.0 && !rx && !ry) { return Ok(ids_json(&roots)); } let ids = s.edit(label, |d, sel| { @@ -500,22 +542,39 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result { // Measure each object's geometric bounds first, with symbol instances measured by their art. let symbols = d.symbol_boxes(); let boxes: Vec> = targets.iter().map(|id| d.node(*id).and_then(|n| n.geometric_bounds_with(&symbols))).collect(); - for (id, b) in targets.iter().zip(boxes) { + let own: Vec> = targets.iter().map(|id| own_box(d, *id, &symbols)).collect(); + for ((id, b), own) in targets.iter().zip(boxes).zip(own) { let Some(b) = b else { continue }; - let (mut k_sh, mut k_sv, mut k_mh, mut k_mv, mut k_rot) = (sh, sv, mh, mv, rot); + let own = own.unwrap_or(b); + // Relative scales by a percentage of the object's size; Absolute takes it to the size + // given, measured on the object's own box, rotated with it, as the dialog shows it (so + // objects of different sizes come out alike, and a rotated shape keeps its size). + let (own_w, own_h) = (own.width(), own.height()); + let (mut k_sh, mut k_sv) = ( + sh.map(|v| if relative { v / 100.0 } else { scale_factor(v, own_w) }), + sv.map(|v| if relative { v / 100.0 } else { scale_factor(v, own_h) }), + ); + let (mut k_mh, mut k_mv, mut k_rot) = (mh, mv, rot); if random { - k_sh = 100.0 + (sh - 100.0) * rng.next(); - k_sv = 100.0 + (sv - 100.0) * rng.next(); - k_mh = mh * (rng.next() * 2.0 - 1.0); - k_mv = mv * (rng.next() * 2.0 - 1.0); - k_rot = rot * (rng.next() * 2.0 - 1.0); + // Five draws whatever the scales are, so a seed gives the moves and the rotation + // the same values whether a side is scaled or not. + let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()]; + k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh); + k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv); + k_mh = mh * (r_mh * 2.0 - 1.0); + k_mv = mv * (r_mv * 2.0 - 1.0); + k_rot = rot * (r_rot * 2.0 - 1.0); } - let o = vectorcraft_geom::reference_point(b, refi); + // The object's own box, turned with it, as the Transform panel and the dialog show it: + // the scales act along its axes, about that box's reference point, so a turned square + // keeps its shape and the size the dialog shows is the one it takes. + let frame = vectorcraft_doc::OrientedBox { angle: d.bbox_angle(&[*id]), rect: own }; + let o = frame.reference_point(refi); // Reflect X / Reflect Y match Object › Transform › Transform Each and Effect › Distort › Transform: // Reflect X flips left-right (negate x), Reflect Y flips top-bottom (negate y). let refl = Affine::scale_non_uniform(if rx { -1.0 } else { 1.0 }, if ry { -1.0 } else { 1.0 }); - let m = Affine::translate((k_mh, k_mv)) - * about(o, Affine::rotate(-k_rot.to_radians()) * refl * Affine::scale_non_uniform(k_sh / 100.0, k_sv / 100.0)); + let scale = Affine::rotate(-k_rot.to_radians()) * refl * Affine::scale_non_uniform(k_sh.unwrap_or(1.0), k_sv.unwrap_or(1.0)); + let m = Affine::translate((k_mh, k_mv)) * about(o, frame.conjugate(scale)); if let Some(n) = d.node_mut(*id) { super::object::transform_node(n, m, sc, objects); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 0772bf5b14..390f6ef499 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -206,11 +206,11 @@ impl Session { } } -/// The fill or stroke a proxy shows for `n` ([`Node::proxy_paint`]: fill or stroke `item` when it -/// is of that kind, type's first run, else the topmost one). +/// The fill or stroke a proxy shows for `n` ([`Node::proxy_paint_only`]: fill or stroke `item` when +/// it is of that kind, type's first run, else the topmost one). pub(crate) fn proxy_paint(n: &Node, stroke: bool, item: Option) -> Paint { - match n.proxy_paint(stroke, item) { - Some((p, ..)) => p.clone(), + match n.proxy_paint_only(stroke, item) { + Some(p) => p.clone(), // Type without runs shows the default character style. None if matches!(n.kind, NodeKind::Text(_)) => { let st = CharStyle::default(); @@ -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/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ad24afacbc..029f3608f6 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -260,14 +260,40 @@ pub const PREF_SPECS: &[PrefSpec] = &[ "", "Default Language", choice(&[ - ("English: USA", "English: USA"), - ("English: UK", "English: UK"), - ("French", "French"), - ("German", "German"), - ("Spanish", "Spanish"), - ("Italian", "Italian"), - ("Dutch", "Dutch"), - ("Portuguese", "Portuguese") + ("en-US", "English: USA"), + ("en-GB", "English: UK"), + ("de", "German"), + ("de-CH", "German: Swiss"), + ("fr", "French"), + ("it", "Italian"), + ("es", "Spanish"), + ("ca", "Catalan"), + ("pt", "Portuguese"), + ("nl", "Dutch"), + ("da", "Danish"), + ("sv", "Swedish"), + ("fi", "Finnish"), + ("nb", "Norwegian"), + ("pl", "Polish"), + ("cs", "Czech"), + ("ru", "Russian"), + ("sr-Cyrl", "Serbian: Cyrillic"), + ("sr-Latn", "Serbian: Latin"), + ("hr", "Croatian"), + ("tr", "Turkish"), + ("ja", "Japanese"), + ("zh", "Chinese"), + ("hi", "Hindi"), + ("mr", "Marathi"), + ("gu", "Gujarati"), + ("bn", "Bengali"), + ("pa", "Punjabi"), + ("ta", "Tamil"), + ("te", "Telugu"), + ("kn", "Kannada"), + ("ml", "Malayalam"), + ("or", "Odia"), + ("ur", "Urdu") ]) ), p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 465e02b459..33fa1a5142 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1149,6 +1149,99 @@ fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::R Err(bad(c, format!("no character at byte {start}"))) } +/// The glyph of `face` that `lay` draws for the character `ch` at `bytes` of `plain`, the laid-out +/// text; `None` when the character is not laid out (overflowing text). A character that starts a +/// longer grapheme (a letter and its combining marks) is drawn in the grapheme's cluster. Of a +/// cluster of several glyphs (a mark, a vowel sign drawn before the letter), the character's glyph +/// is the first in cluster order that is its default glyph or one of its alternates and not the +/// default glyph of another character of the grapheme; else the first that is its default glyph or +/// one of its alternates; else the first glyph that is not the default glyph or an alternate of +/// another character of the grapheme (a ligature of the letter and a mark). `Some(None)` when the +/// cluster holds none of these. +fn own_glyph( + plain: &str, + lay: &vectorcraft_text::TextLayout, + ch: char, + bytes: &std::ops::Range, + face: &vectorcraft_text::FontFace, +) -> Option> { + lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len))?; + let grapheme = edit::next_cluster(plain, bytes.start).max(bytes.end) - bytes.start; + let cluster: Vec = lay + .glyphs + .iter() + .filter(|g| g.byte == bytes.start && [bytes.len(), grapheme].contains(&g.len) && g.font_id == face.id()) + .map(|g| g.gid) + .collect(); + Some(match cluster[..] { + [one] => Some(one), + _ => { + // The glyphs of each character are looked up once: a grapheme can repeat a mark. + let glyphs_of = |c: char| face.alternates(c).iter().map(|a| a.gid).chain([face.glyph_for(c)]).collect::>(); + // In cluster order: a conjunct's half form comes before the default glyph of its + // second consonant, which can be the same character. A glyph drawn for another + // character (a vowel sign drawn first) is skipped even when the font lists it as an + // alternate of this one. + let own = glyphs_of(ch); + let mut others: Vec = plain.get(bytes.end..bytes.start + grapheme).unwrap_or_default().chars().filter(|&c| c != ch).collect(); + others.sort_unstable(); + others.dedup(); + let their_defaults: Vec = others.iter().map(|&c| face.glyph_for(c)).collect(); + cluster + .iter() + .copied() + .find(|g| own.contains(g) && !their_defaults.contains(g)) + .or_else(|| cluster.iter().copied().find(|g| own.contains(g))) + .or_else(|| { + let theirs: Vec = others.iter().flat_map(|&c| glyphs_of(c)).collect(); + cluster.iter().copied().find(|g| !theirs.contains(g)) + }) + } + }) +} + +/// The glyph of `face` drawn for the character `ch` at `bytes` of `t` when the character is shaped +/// alone in the writing direction of `t` and the direction its paragraph sets it in, with the rest +/// of its grapheme in the grapheme's own styles: the glyph of a character that is not laid out +/// (overflowing text). Also the glyph drawn for the character in whatever face draws it +/// ([`drawn_glyph`]). +fn shaped_alone(t: &TextObject, ch: char, bytes: &std::ops::Range, face: &vectorcraft_text::FontFace) -> (Option, Option) { + use vectorcraft_doc::ParaDirection; + let plain = t.plain_text(); + let end = edit::next_cluster(&plain, bytes.start).max(bytes.end); + let mut single = TextObject::point(Point::ZERO, "", CharStyle::default()); + single.runs = edit::slice_runs(&t.runs, bytes.start, end); + single.vertical = t.vertical; + // The bidi level of the character in its paragraph (a parenthesis is mirrored at an odd one). + let before = plain.get(..bytes.start).unwrap_or_default(); + let (paragraph, start) = (before.matches('\n').count(), before.rfind('\n').map_or(0, |i| i + 1)); + let stop = plain.get(bytes.start..).and_then(|after| after.find('\n')).map_or(plain.len(), |i| bytes.start + i); + let rtl = vectorcraft_text::char_is_rtl(plain.get(start..stop).unwrap_or_default(), t.para_at(paragraph).direction, bytes.start - start); + single.para.direction = Some(if rtl { ParaDirection::RightToLeft } else { ParaDirection::LeftToRight }); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &single); + let (alone, at) = (single.plain_text(), 0..bytes.len()); + (own_glyph(&alone, &lay, ch, &at, face).flatten(), drawn_glyph(&alone, &lay, ch, &at, face)) +} + +/// The glyph `lay` draws for the character `ch` at `bytes` of `plain` in whatever face draws it: +/// the glyph of `face` ([`own_glyph`]); else, when a fallback face draws the character, that face's +/// glyph for it by the same rule (its vowel sign drawn first is not reported); else the first glyph +/// drawn for the character. `None` when the character is not laid out. +fn drawn_glyph( + plain: &str, + lay: &vectorcraft_text::TextLayout, + ch: char, + bytes: &std::ops::Range, + face: &vectorcraft_text::FontFace, +) -> Option { + if let Some(own) = own_glyph(plain, lay, ch, bytes, face).flatten() { + return Some(own); + } + let first = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len))?; + let fallback = (first.font_id != face.id()).then(|| vectorcraft_text::FontDb::global().face_by_id(first.font_id)).flatten(); + fallback.and_then(|f| own_glyph(plain, lay, ch, bytes, &f).flatten()).or(Some(first.gid)) +} + fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { const C: &str = "text.setGlyphAlternate"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; @@ -1174,43 +1267,15 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { // The glyph the character is drawn with when it holds no choice, drawn alone in its face: a // feature of its style (`salt`, a stylistic set) can draw another glyph than the default one. // The default glyph is then kept as a choice, so that it is drawn. A character that is not laid - // out (overflowing text) is shaped alone in its style and writing direction. A character that starts a longer - // grapheme (a letter and its combining marks) is drawn in the grapheme's cluster, and is shaped - // with the grapheme. Of a cluster of several glyphs (a mark, a vowel sign drawn before the - // letter), the character's glyph is its default glyph or one of its alternates. + // out (overflowing text) is shaped alone in its writing direction, with the rest of its grapheme + // in the grapheme's own styles. let plain = t.plain_text(); - let grapheme = plain.get(bytes.start..edit::next_cluster(&plain, bytes.start).max(bytes.end)).map_or_else(|| ch.to_string(), str::to_owned); - let listed = face.alternates(ch); - let own_glyph = |lay: &vectorcraft_text::TextLayout, at: usize| { - let cluster: Vec = lay - .glyphs - .iter() - .filter(|g| g.byte == at && [bytes.len(), grapheme.len()].contains(&g.len) && g.font_id == face.id()) - .map(|g| g.gid) - .collect(); - match cluster[..] { - [one] => Some(one), - _ => cluster.into_iter().find(|&g| g == default || listed.iter().any(|a| a.gid == g)), - } - }; - let alone_in_face = |lay: &vectorcraft_text::TextLayout| { - let found = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)); - found.map(|_| own_glyph(lay, bytes.start)) - }; - let unchosen = match holder.as_ref().filter(|_| !styled) { - None => None, - Some((_, run)) => { - let mut probe = t.clone(); - edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); - let db = vectorcraft_text::FontDb::global(); - alone_in_face(&vectorcraft_text::layout(db, &probe)).unwrap_or_else(|| { - let st = CharStyle { glyph_alternate: None, ..run.style.clone() }; - let mut single = TextObject::point(Point::ZERO, &grapheme, st); - single.vertical = t.vertical; - own_glyph(&vectorcraft_text::layout(db, &single), 0) - }) - } - }; + let unchosen = holder.as_ref().filter(|_| !styled).and_then(|_| { + let mut probe = t.clone(); + edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); + own_glyph(&plain, &lay, ch, &bytes, &face).unwrap_or_else(|| shaped_alone(&probe, ch, &bytes, &face).0) + }); let substituted = unchosen.is_some_and(|g| g != default); let choice = match gid.filter(|g| *g != default || substituted) { None => None, @@ -1230,10 +1295,9 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result { let shown = || { let mut probe = t.clone(); edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = Some(c.clone())); - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe); - lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map(|g| g.gid) + own_glyph(&plain, &vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe), ch, &bytes, &face) }; - if styled || shown().is_some_and(|g| g != c.gid) { + if styled || shown().is_some_and(|g| g != Some(c.gid)) { return Err(bad( C, format!("glyph {} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system)", c.gid), @@ -1259,7 +1323,10 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result { let (ch, bytes, face) = glyph_target(&t, p, C)?; let default = face.glyph_for(ch); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); - let chosen = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map_or(default, |g| g.gid); + // A character that is not laid out (overflowing text) reports the glyph it is drawn with when + // it is shaped alone, as `text.setGlyphAlternate` finds it; a fallback face's glyph when it is + // drawn in one. + let chosen = drawn_glyph(&t.plain_text(), &lay, ch, &bytes, &face).or_else(|| shaped_alone(&t, ch, &bytes, &face).1).unwrap_or(default); let alternates: Vec = face.alternates(ch).iter().map(|a| json!({"gid": a.gid, "feature": String::from_utf8_lossy(&a.feature)})).collect(); Ok(json!({"char": ch.to_string(), "font": face.family, "style": face.style, "default": default, "chosen": chosen, "alternates": alternates})) } 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/prefs.rs b/crates/engine/src/prefs.rs index 5deb00ddde..ce7c5e4a62 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,14 @@ pub enum DrawMode { Inside, } +/// A saved Default Language as its tag: older preferences hold the language's name, and one the list +/// no longer has reads as the default. +fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + let tag = vectorcraft_doc::setup::char_language(&saved).ok().flatten(); + Ok(tag.or_else(|| vectorcraft_doc::setup::LANGUAGES.first().map(|(_, t, _)| *t)).unwrap_or_default().to_string()) +} + /// Application preferences (Edit → Preferences). Every field is reachable through `prefs.get` / /// `prefs.set {key, value}` (camelCase keys, validated against [`cmd::prefscmds::PREF_SPECS`]). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -114,6 +122,9 @@ pub struct Prefs { pub show_slice_numbers: bool, pub slice_line_color: String, // Hyphenation + /// Default Language: the BCP 47 tag of the language new type takes when its document's language + /// is the default ([`vectorcraft_doc::setup::LANGUAGES`]). + #[serde(deserialize_with = "language_tag")] pub hyphenation_language: String, pub hyphenation_exceptions: String, /// Type › Options › Additional Fonts Folder: a folder (read with its subfolders) whose fonts @@ -404,7 +415,7 @@ impl Default for Prefs { snap_perpendicular: true, show_slice_numbers: true, slice_line_color: s("#ff3f3f"), - hyphenation_language: s("English: USA"), + hyphenation_language: s("en-US"), hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6b048e6fa3..41946c0ebd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -292,6 +292,27 @@ impl Session { true } + /// Move the document in tab `from` to tab `to` (a document tab dragged along the strip, + /// `document.move`); the documents between them shift by one. The current document stays the + /// current one, wherever it moves to, and its tool keeps its state: no document is switched to. + /// False, changing nothing, when either index is past the last document. + pub fn move_document(&mut self, from: usize, to: usize) -> bool { + let n = self.docs.len(); + if from >= n || to >= n { + return false; + } + if from == to { + return true; + } + let active = self.active().map(|d| d.uid); + let d = self.docs.remove(from); + self.docs.insert(to, d); + if let Some(uid) = active { + self.active = self.docs.iter().position(|d| d.uid == uid); + } + true + } + /// Commands with enablement (for menus, palette, MCP `list_commands`). pub fn commands(&self) -> Vec { command_specs().iter().map(|c| c.info(self)).collect() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a1fa3e0487..812a6282f2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -41,6 +41,7 @@ mod cut; mod dashalign; mod distort; mod docsetup; +mod document_move; mod draw2; mod dynamic_symbols; mod editcolors; @@ -108,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/appearance.rs b/crates/engine/src/tests/appearance.rs index 9bed4eb343..ada5fdd2f0 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -554,6 +554,49 @@ fn add_fill_copies_the_active_row_in_each_object_that_has_it() { } } +/// A paint edit of the active row changes the equal row of each object that has one, even when +/// another selected object has none; that object's row stands for itself, as with only it and the +/// first selected object selected. +#[test] +fn paint_edits_change_the_active_row_in_each_object_that_has_it() { + let mut s = session(); + let [a, b, c] = [rect(&mut s, 50.0), rect(&mut s, 200.0), rect(&mut s, 300.0)]; + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red] + // b gets a yellow fill below the others: [Fill yellow, Fill green, Stroke, Fill red]. + run(&mut s, "appearance.addFill", json!({"ids": [b.0]})); + run(&mut s, "appearance.moveItem", json!({"ids": [b.0], "from": 3, "to": 0})); + run(&mut s, "appearance.setItem", json!({"ids": [b.0], "index": 0, "color": "#ffff00"})); + run(&mut s, "appearance.setItem", json!({"ids": [c.0], "index": 0, "color": "#0000ff"})); // [Fill blue, Stroke, Fill red] + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "paint.setFill", json!({"color": "#ff00ff"})); + let (na, nb, nc) = (node(&s, a), node(&s, b), node(&s, c)); + assert_eq!(fill_paint(&na, 0).color().unwrap().to_hex(), "#ff00ff"); + assert_eq!(fill_paint(&nb, 1).color().unwrap().to_hex(), "#ff00ff", "{:?}", nb.appearance); + assert_eq!(fill_paint(&nb, 0).color().unwrap().to_hex(), "#ffff00", "{:?}", nb.appearance); + assert_eq!(fill_paint(&nc, 0).color().unwrap().to_hex(), "#ff00ff", "{:?}", nc.appearance); +} + +/// An object-level effect is removed from each object that has an equal one, even when another +/// selected object has none. +#[test] +fn removing_an_effect_reaches_each_object_that_has_it() { + let mut s = session(); + let [a, b, c] = [rect(&mut s, 50.0), rect(&mut s, 200.0), rect(&mut s, 300.0)]; + run(&mut s, "effect.apply", json!({"ids": [a.0], "effect": "stylize.feather", "item": null})); + run(&mut s, "effect.apply", json!({"ids": [a.0, b.0], "effect": "distort.twist", "item": null})); + // a has [feather, twist], b [twist], c none. + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + run(&mut s, "effect.remove", json!({"index": 1, "item": null, "aligned": true})); + let ids = |id: NodeId| node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect::>(); + assert_eq!(ids(a), ["stylize.feather"]); + assert!(ids(b).is_empty(), "b loses its twist: {:?}", ids(b)); + assert!(ids(c).is_empty()); +} + /// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1 /// and 2 equal a's rows 0 and 1. fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) { @@ -916,6 +959,16 @@ fn shared_effects_and_new_fills_reach_every_selected_object() { assert!(s.execute("appearance.moveItem", &json!({"from": 1, "to": 0, "aligned": true})).is_err()); } +/// An effect applied to the first object's stroke row goes on the equal stroke of the other +/// object, which sits lower in a longer stack there. +#[test] +fn an_effect_on_a_shared_row_reaches_it_at_another_index() { + let mut s = session(); + let (a, b) = mixed_circles(&mut s, true); + run(&mut s, "effect.apply", json!({"effect": "distort.twist", "item": 1, "aligned": true})); + assert_eq!((stroke(&node(&s, a), 1).effects.len(), stroke(&node(&s, b), 2).effects.len()), (1, 1)); +} + /// Rows deleted together, one shared (the stroke) and one not (a's fill): each object loses its /// own copy of the shared row, and the other object keeps the items at those indices of a's stack. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 7a28b922bf..4784831efb 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1224,6 +1224,32 @@ fn place_and_break_link_round_trip_geometry() { assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation"); } +#[test] +fn hidden_instance_fill_does_not_tint_expanded_symbol_art() { + for command in ["symbol.breakLink", "object.expand"] { + let mut s = session(); + let source = rect(&mut s, 100.0, 50.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [source.0], "color": "#0000ff"})).unwrap(); + let inst = NodeId(s.execute("symbol.new", &json!({"name": "Blue Box"})).unwrap()["id"].as_u64().unwrap()); + s.execute("appearance.addFill", &json!({"ids": [inst.0]})).unwrap(); + let fill = node(&s, inst).appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": fill, "color": "#ff0000"})).unwrap(); + let center = |s: &Session| { + let doc = s.doc().unwrap().doc.clone(); + vectorcraft_render::Renderer::new().render_region(&doc, Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixel(140, 70) + }; + let tinted = center(&s); + assert!(tinted[0] > tinted[2], "the visible instance fill tints the symbol: {tinted:?}"); + s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": fill, "visible": false})).unwrap(); + let original = center(&s); + assert!(original[2] > original[0], "hiding the fill restores the blue symbol: {original:?}"); + + let params = if command == "symbol.breakLink" { json!({"ids": [inst.0]}) } else { json!({"object": true, "fill": false, "stroke": false}) }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(center(&s), original, "{command} must keep the untinted colors"); + } +} + #[test] fn break_link_then_update_redefines_all_instances() { let mut s = session(); 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/compound_shape.rs b/crates/engine/src/tests/compound_shape.rs index 2de8a35b95..7455fbfa5a 100644 --- a/crates/engine/src/tests/compound_shape.rs +++ b/crates/engine/src/tests/compound_shape.rs @@ -664,3 +664,35 @@ fn expanded(s: &mut Session, id: NodeId) -> f64 { let made = run(s, "object.compoundShape.expand", json!({})); node_area(&node(s, NodeId(made["ids"][0].as_u64().unwrap()))) } + +/// Locking (or hiding) the layer of an isolated compound shape locks its members too: a click or +/// a marquee with the Selection tool selects none of them, as outside isolation mode (#5309). +#[test] +fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + for (prop, value) in [("locked", true), ("visible", false)] { + let (mut s, back, _front) = two_squares(); + let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": id.0})); + let layer = s.doc().unwrap().doc.parent_of(id).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + }; + click(&mut s, 25.0, 50.0); + assert_eq!(selected(&s), vec![back], "isolated, a click selects a member"); + run(&mut s, "select.none", json!({})); + run(&mut s, "layer.setProps", json!({"id": layer.0, prop: value})); + click(&mut s, 25.0, 50.0); + assert!(selected(&s).is_empty(), "{prop}: the layer's art isn't selected by a click"); + for (k, x, y) in + [(PointerKind::Down, -10.0, -10.0), (PointerKind::Drag, 60.0, 60.0), (PointerKind::Drag, 120.0, 120.0), (PointerKind::Up, 120.0, 120.0)] + { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + assert!(selected(&s).is_empty(), "{prop}: nor by a marquee"); + } +} diff --git a/crates/engine/src/tests/document_move.rs b/crates/engine/src/tests/document_move.rs new file mode 100644 index 0000000000..f68c729081 --- /dev/null +++ b/crates/engine/src/tests/document_move.rs @@ -0,0 +1,133 @@ +//! `document.move` (#5663): a document tab dragged along the tab strip moves its document to +//! another place among the open documents, and the current document stays the current one. + +use serde_json::{Value, json}; + +use crate::*; + +/// A session with documents A, B, C and D, in that order, D current. +fn four() -> Session { + let mut s = Session::new(); + for name in ["A", "B", "C", "D"] { + s.execute("file.new", &json!({"name": name, "created": null})).unwrap(); + } + s +} + +fn order(s: &Session) -> String { + s.documents().iter().map(DocState::title).collect::>().join("") +} + +fn current(s: &Session) -> String { + s.active().map(DocState::title).unwrap_or_default() +} + +fn moved(s: &mut Session, p: Value) -> Value { + s.execute("document.move", &p).unwrap_or_else(|e| panic!("document.move {p}: {e}")) +} + +#[test] +fn a_document_moves_to_its_new_tab_and_the_others_shift() { + let mut s = four(); + assert_eq!(order(&s), "ABCD"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 2})), json!({"index": 2})); + assert_eq!(order(&s), "BCAD", "forward: the documents between shift left"); + assert_eq!(moved(&mut s, json!({"from": 3, "to": 0})), json!({"index": 0})); + assert_eq!(order(&s), "DBCA", "backward: the documents between shift right"); + assert_eq!(moved(&mut s, json!({"from": 1, "to": 1})), json!({"index": 1})); + assert_eq!(order(&s), "DBCA", "onto itself: nothing changes"); +} + +#[test] +fn the_current_document_stays_current_wherever_the_move_puts_it() { + let mut s = four(); + assert!(s.set_active(1)); + // The current document itself moves. + moved(&mut s, json!({"from": 1, "to": 3})); + assert_eq!((order(&s), current(&s)), ("ACDB".into(), "B".into())); + assert_eq!(s.active_index(), Some(3)); + // A document moves past the current one, which shifts by one. + moved(&mut s, json!({"from": 3, "to": 0})); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!((order(&s), current(&s)), ("DBAC".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); + // A move on one side of the current document leaves it where it is. + moved(&mut s, json!({"from": 2, "to": 3})); + assert_eq!((order(&s), current(&s)), ("DBCA".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); +} + +#[test] +fn without_from_the_current_document_moves() { + let mut s = four(); + assert!(s.set_active(2)); + moved(&mut s, json!({"to": 0})); + assert_eq!((order(&s), current(&s)), ("CABD".into(), "C".into())); +} + +#[test] +fn a_move_past_the_last_tab_ends_there_and_bad_indices_change_nothing() { + let mut s = four(); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 99})), json!({"index": 3})); + assert_eq!(order(&s), "BCDA"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": u64::MAX})), json!({"index": 3})); + assert_eq!(order(&s), "CDAB"); + for p in [ + json!({"from": 4, "to": 0}), + json!({"from": u64::MAX, "to": 0}), + json!({"from": 0}), + json!({"from": -1, "to": 0}), + json!({"from": 0, "to": "1"}), + ] { + assert!(s.execute("document.move", &p).is_err(), "{p} is refused"); + assert_eq!(order(&s), "CDAB", "{p} changes nothing"); + } + assert!(!s.move_document(0, 4)); + assert!(!s.move_document(4, 0)); + assert_eq!(order(&s), "CDAB"); +} + +#[test] +fn moving_needs_an_open_document_and_one_document_stays_put() { + let mut s = Session::new(); + assert!(s.execute("document.move", &json!({"to": 0})).is_err(), "no document open"); + s.execute("file.new", &json!({"name": "A", "created": null})).unwrap(); + assert_eq!(moved(&mut s, json!({"to": 5})), json!({"index": 0})); + assert_eq!((order(&s), current(&s)), ("A".into(), "A".into())); +} + +#[test] +fn a_move_keeps_the_tool_and_the_documents_edits() { + let mut s = four(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let resets = s.tool_resets; + let nodes = s.doc().unwrap().doc.node_count(); + let history = super::history(&s); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!(super::history(&s), history, "a move is no undo step, and it keeps Redo"); + assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes); + assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit"); +} + +/// A recording replays the move before the steps after it, so an `index` they name is the same +/// document as when they were recorded. +#[test] +fn a_journaled_move_replays_in_order() { + let mut s = four(); + for (id, p) in [ + ("document.move", json!({"from": 0, "to": 3})), + ("document.activate", json!({"index": 3})), + ("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!((order(&s), current(&s)), ("BCDA".into(), "A".into())); + let mut r = Session::new(); + for (id, p) in &s.journal { + r.execute(id, p).unwrap(); + } + assert_eq!((order(&r), current(&r)), ("BCDA".into(), "A".into())); + let counts = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + assert_eq!(counts(&r), counts(&s), "the rectangle is in the same document after the replay"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 0b952a8196..77648e9804 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -394,10 +394,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(); @@ -409,7 +410,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); @@ -4007,11 +4008,17 @@ fn pen_continue_at_a_first_anchor_in_a_compound_reverses_only_that_subpath() { /// The anchors of a closed, slightly wobbly blob drawn at `fidelity`: samples half a point apart, /// with a small tremor on top of the outline. fn blob_anchors(s: &mut Session, fidelity: f64) -> usize { + scaled_blob_anchors(s, fidelity, 1.0) +} + +/// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale` +/// times. +fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { let pts: Vec<_> = (0..1200) .map(|i| { let a = i as f64 / 1200.0 * std::f64::consts::TAU; let r = 90.0 + 12.0 * (3.0 * a).sin() + 0.15 * (97.0 * a).sin(); - json!([400.0 + r * a.cos(), 300.0 + r * a.sin()]) + json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale]) }) .collect(); let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap(); @@ -4026,9 +4033,26 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() { assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); // Below the old floor of 0.05 the stroke keeps more of itself. assert!(counts[4] > counts[2], "{counts:?}"); - // Below 0.01 is read as 0.01. - assert_eq!(blob_anchors(&mut s, 0.001), counts[4]); - assert_eq!(blob_anchors(&mut s, 0.0), counts[4]); + // Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the + // floor (#5729). + let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0; + let at_floor = blob_anchors(&mut s, floor); + assert!(at_floor >= counts[4], "{counts:?}"); + assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor); + assert_eq!(blob_anchors(&mut s, 0.0), at_floor); +} + +/// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as +/// many anchors, down to the lowest Fidelity at the highest zoom. +#[test] +fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() { + let mut s = session(); + for fidelity in [1.5, 0.1, 0.01] { + let want = blob_anchors(&mut s, fidelity); + for zoom in [4.0, 64.0, 640.0] { + assert_eq!(scaled_blob_anchors(&mut s, fidelity / zoom, 1.0 / zoom), want, "{fidelity} at {zoom}x"); + } + } } /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 93759d2b61..090cb98285 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -52,6 +52,57 @@ fn expandable(s: &Session) -> bool { s.commands().iter().find(|c| c.id == "effect.expandAppearance").unwrap().enabled } +#[test] +fn symbol_instance_tint_survives_expanding_an_object_effect() { + let mut s = session(); + square(&mut s); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Tinted Square"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let fill = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": fill, "color": "#00ff00", "opacity": 50})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 6}})); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. })); + let before = render(&s); + assert_ne!(before.pixel(100, 100), [255, 255, 255, 255], "the symbol is visible"); + assert_ne!(before.pixel(100, 100), [255, 0, 0, 255], "the instance fill tints the red symbol art"); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + n.walk(&mut |part| assert!(part.appearance.effects.is_empty())); + let after = render(&s); + assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); +} + +/// An instance fill with an opacity of 0 does not tint the symbol's art, so expanding keeps the +/// art's global swatch link. +#[test] +fn a_symbol_instance_fill_with_no_opacity_keeps_swatch_links_when_expanded() { + let mut s = session(); + let sq = square(&mut s); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": "#2a6fb0", "global": true})); + run(&mut s, "paint.setFill", json!({"ids": [sq.0], "swatch": "Brand"})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Linked Square"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let fill = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": fill, "color": "#00ff00", "opacity": 0})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 6}})); + assert!(expandable(&s)); + + run(&mut s, "effect.expandAppearance", json!({})); + let n = node(&s, id); + assert!(!matches!(n.kind, NodeKind::SymbolInstance { .. })); + let mut linked = 0; + n.walk(&mut |part| { + if let vectorcraft_color::Paint::Solid { swatch: Some(name), .. } = part.appearance.fill_paint() { + assert_eq!(name, "Brand"); + linked += 1; + } + }); + assert!(linked > 0, "the expanded art keeps the Brand swatch link"); +} + #[test] fn two_fills_and_an_offset_stroke_become_three_paths_that_look_the_same() { let mut s = session(); diff --git a/crates/engine/src/tests/gradpresets.rs b/crates/engine/src/tests/gradpresets.rs index 78be419af5..437f96d26c 100644 --- a/crates/engine/src/tests/gradpresets.rs +++ b/crates/engine/src/tests/gradpresets.rs @@ -137,6 +137,183 @@ fn saving_needs_a_gradient_behind_the_proxy() { assert!(s.execute("gradient.presets.save", &json!({"name": 7})).is_err(), "a name is text"); } +/// Save Gradient Preset is enabled exactly when saving works, with and without a gradient behind +/// the active proxy: the defaults with nothing selected, a fill or a stroke, a group's first +/// painted member, type and an Appearance panel row. +#[test] +fn the_save_check_matches_saving_with_and_without_a_gradient() { + /// What the case is, how its session is made, and whether a gradient is behind the proxy. + type Case = (&'static str, fn() -> Session, bool); + let cases: [Case; 9] = [ + ( + "default solid paint", + || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s + }, + false, + ), + ( + "default gradient paint", + || { + let (mut s, _) = session_with(json!({"gradient": {}})); + s.execute("select.none", &json!({})).unwrap(); + s + }, + true, + ), + ("solid fill", || session_with(json!({"color": "#336699"})).0, false), + ("gradient fill", || session_with(json!({"gradient": {"kind": "radial"}})).0, true), + ( + "gradient fill, Stroke proxy in front", + || { + let (mut s, _) = session_with(json!({"gradient": {}})); + s.execute("paint.toggleActive", &json!({"fill": false})).unwrap(); + s + }, + false, + ), + ( + "gradient stroke, Stroke proxy in front", + || { + let (mut s, _) = session_with(json!({"color": "#336699"})); + s.execute("paint.setStroke", &json!({"gradient": {}, "focus": false})).unwrap(); + s.execute("paint.toggleActive", &json!({"fill": false})).unwrap(); + s + }, + true, + ), + ( + "group of a gradient and a solid", + || { + let (mut s, a) = session_with(json!({"gradient": {}})); + let b = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s + }, + true, + ), + ( + "type with a gradient fill", + || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 100, "text": "type"})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s + }, + true, + ), + ( + "a solid fill row active under a gradient fill", + || { + let (mut s, _) = session_with(json!({"color": "#336699"})); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {}, "item": null})).unwrap(); + let items = &s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap().appearance.items; + let solid = items + .iter() + .position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if matches!(f.paint, Paint::Solid { .. }))) + .unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": solid})).unwrap(); + s + }, + false, + ), + ]; + for (why, make, gradient) in cases { + let mut s = make(); + let enabled = (crate::find_command("gradient.presets.save").unwrap().enabled)(&s).is_ok(); + assert_eq!((enabled, s.execute("gradient.presets.save", &json!({})).is_ok()), (gradient, gradient), "{why}"); + } +} + +/// [`Node::proxy_paint_only`] picks the paint [`Node::proxy_paint`] does, for fills and strokes, +/// with and without an Appearance panel row, on paths with several fills, type, an empty path +/// and a colorized object. +#[test] +fn the_unmeasured_proxy_paint_is_the_measured_one() { + let (mut s, id) = session_with(json!({"gradient": {}})); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + let plain = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let colorized = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.edit("Colorize", |d, _| { + d.node_mut(colorized).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 200, "text": "type"})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let mut nodes: Vec = [id, plain, colorized, text].iter().map(|i| d.node(*i).unwrap().clone()).collect(); + nodes.push(vectorcraft_doc::Node::path(NodeId(9999), Default::default(), (*d.node(plain).unwrap().appearance).clone())); + let mut runless = d.node(text).unwrap().clone(); + if let vectorcraft_doc::NodeKind::Text(t) = &mut runless.kind { + t.runs.clear(); + } + nodes.push(runless); + for n in &nodes { + for stroke in [false, true] { + for item in [None, Some(0), Some(1), Some(2), Some(3), Some(9)] { + assert_eq!(n.proxy_paint_only(stroke, item), n.proxy_paint(stroke, item).map(|p| p.0), "{:?} stroke {stroke} item {item:?}", n.id); + } + } + } +} + +/// On objects made from a fixed seed (paths, an empty path, type with and without runs, each +/// with zero to four fills and strokes of none, a solid color or a gradient, some colorized), +/// [`Node::proxy_paint_only`] picks the paint [`Node::proxy_paint`] does for every row. +#[test] +fn the_unmeasured_proxy_paint_is_the_measured_one_on_varied_objects() { + let (mut s, rect) = session_with(json!({"gradient": {}})); + let gradient = s.doc().unwrap().doc.node(rect).unwrap().appearance.paint_at(None, true).unwrap().clone(); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 200, "text": "type"})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let mut runless = d.node(text).unwrap().clone(); + if let vectorcraft_doc::NodeKind::Text(t) = &mut runless.kind { + t.runs.clear(); + } + let empty = vectorcraft_doc::Node::path(NodeId(9999), Default::default(), Default::default()); + let bases = [d.node(rect).unwrap().clone(), empty, d.node(text).unwrap().clone(), runless]; + let mut seed: u64 = 0x9a1d_5eed_c0de; + let mut next = |n: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + let (mut checked, mut some) = (0, 0); + for _ in 0..200 { + let mut n = bases[next(4) as usize].clone(); + let paints = [Paint::None, Paint::solid(Color::rgb8(next(256) as u8, 0, 0)), gradient.clone()]; + let mut look = vectorcraft_doc::Appearance::default(); + for _ in 0..next(5) { + let p = paints[next(3) as usize].clone(); + look.items.push(if next(2) == 0 { + vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(p)) + } else { + vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(p, 1.0 + next(5) as f64)) + }); + } + n.appearance = look.into(); + if next(4) == 0 { + n.extras_mut().colorize = Some(Box::new(paints[next(3) as usize].clone())); + } + for stroke in [false, true] { + for item in [None, Some(0), Some(1), Some(2), Some(3), Some(4)] { + let measured = n.proxy_paint(stroke, item).map(|p| p.0); + assert_eq!(n.proxy_paint_only(stroke, item), measured, "{n:?} stroke {stroke} item {item:?}"); + checked += 1; + some += usize::from(measured.is_some()); + } + } + } + assert!(some > checked / 4 && some < checked, "both answers come up: {some} of {checked} found a paint"); +} + #[test] fn saved_presets_round_trip_with_the_preferences() { let (mut s, _) = session_with(json!({"gradient": {}})); 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/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index c355793d9b..951a9ec31a 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -192,6 +192,27 @@ fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn spot_stops_with_process_plates_export_both_in_device_n_shadings() { + // #3235: Ink 0 % to 100 % over a constant 30 % cyan plate, as a DeviceN gradient imported + // from a PDF has it. + let (mut s, id) = setup(); + let cyan = json!({"c": 0.3, "m": 0, "y": 0, "k": 0}); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "swatch": "Ink", "plates": [0.3, 0, 0, 0]}]})); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "a DeviceN shading of Cyan and Ink"); + assert!(pdf.contains("/C0[0.3 0]/C1[0.3 1]"), "the cyan plate runs under the whole gradient"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); + let stops = gradient(&s, id).gradient.stops; + assert_eq!((stops[1].swatch.as_deref(), stops[1].plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0])), "{stops:?}"); + // The plates are part of the stop's params, so moving the vector keeps them. + run(&mut s, "paint.editGradient", json!({"angle": 45})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, Some([0.3, 0.0, 0.0, 0.0])); + // An unlinked stop has none. + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "color": "#ffffff", "plates": [0.3, 0, 0, 0]}]})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, None); +} + #[test] fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { let (mut s, _) = setup(); @@ -315,6 +336,17 @@ fn perceptual_spot_gradients_with_rgb_stops_in_a_cmyk_document_export_as_device_ assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Ink]/DeviceCMYK"), "{what}: a DeviceN shading with Ink"); assert!(!r.warnings.iter().any(|w| w.contains("spot")), "{what}: {:?}", r.warnings); } + // A conversion to an RGB destination keeps the RGB stop in RGB, in a CMYK document too: an + // image, with the spot warning. + let mut to_rgb = plain.clone(); + to_rgb.settings.output = vectorcraft_pdf::OutputSettings { + conversion: vectorcraft_pdf::ColorConversion::Destination, + destination: vectorcraft_color::cms::SRGB.into(), + ..Default::default() + }; + let r = vectorcraft_pdf::export_with_report(&cmyk, &to_rgb).unwrap(); + assert!(String::from_utf8_lossy(&r.bytes).contains("/Subtype/Image"), "RGB destination: an image"); + assert!(r.warnings.iter().any(|w| w.contains("spot")), "RGB destination: {:?}", r.warnings); } #[test] 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/menucmds.rs b/crates/engine/src/tests/menucmds.rs index d14502659b..450baabc11 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -1070,6 +1070,61 @@ fn transform_each_scales_each_about_its_own_center() { assert_eq!(undo_len(&s), n + 1); } +/// The dialog's Absolute (`relative: false`): `scaleH` and `scaleV` are the width and height each +/// object becomes, measured on its own bounds, so objects of different sizes come out alike about +/// their own reference points. A side left out keeps its size, a side of 0 (a line) stays 0, and +/// Absolute already at the size the objects have changes nothing and records no undo step. +#[test] +fn transform_each_absolute_takes_each_object_to_the_size_given() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0); + let b = rect(&mut s, 200.0, 0.0, 40.0, 80.0); + sel(&mut s, &[a, b]); + let n = undo_len(&s); + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 60, "scaleV": 20})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(20.0, 15.0, 80.0, 35.0)); + assert_eq!(bounds(&s, b), Rect::new(190.0, 30.0, 250.0, 50.0)); + assert_eq!(undo_len(&s), n + 1); + // A side left out keeps its size, and the reference point still holds the new size in place. + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 30, "reference": 0})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(20.0, 15.0, 50.0, 35.0), Rect::new(190.0, 30.0, 220.0, 50.0))); + let before = (undo_len(&s), bounds(&s, a), bounds(&s, b)); + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 30, "scaleV": 20})).unwrap(); + assert_eq!((undo_len(&s), bounds(&s, a), bounds(&s, b)), before, "already the size given"); + // A line has no height to take: its side stays as it is. + let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 10}, {"x": 100, "y": 10}], "closed": false})).unwrap()); + sel(&mut s, &[line]); + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 50, "scaleV": 80})).unwrap(); + assert_eq!(bounds(&s, line), Rect::new(25.0, 10.0, 75.0, 10.0)); + // A scale of 0 is refused in either mode, as it collapses the object. + for p in [json!({"relative": false, "scaleH": 0}), json!({"scaleH": 0})] { + let r = s.execute("object.transformEach", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == "scale must be non-zero"), "{p}: {r:?}"); + } +} + +/// Absolute measures each object's own box, rotated with it, as the Transform panel shows it: a +/// square turned 45° keeps its size when the size it shows is applied, and a width applied is the +/// square's own width, not its bounding box's. +#[test] +fn transform_each_absolute_measures_a_rotated_object_its_own_way() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 45})).unwrap(); + let own = |s: &Session| s.doc().unwrap().doc.oriented_bounds(&[a], false).unwrap().rect; + let bbox = |s: &Session| bounds(s, a); + assert!((own(&s).width() - 100.0).abs() < 1e-6 && (bbox(&s).width() - 141.421).abs() < 0.01, "turned 45°"); + // The size it shows, applied, changes nothing and records no undo step. + let before = (undo_len(&s), bbox(&s)); + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 100, "scaleV": 100})).unwrap(); + assert_eq!((undo_len(&s), bbox(&s)), before, "already the size it shows"); + // A width is the square's own width. + s.execute("object.transformEach", &json!({"relative": false, "scaleH": 200})).unwrap(); + assert!((own(&s).width() - 200.0).abs() < 1e-6, "200 wide: {:?}", own(&s)); + assert!((own(&s).height() - 100.0).abs() < 1e-6, "its height kept: {:?}", own(&s)); +} + #[test] fn transform_each_move_reference_and_copy() { let mut s = session(); @@ -1144,9 +1199,10 @@ fn transform_each_refuses_a_number_given_as_text() { assert_eq!(bounds(&s, a), Rect::new(35.0, 25.0, 85.0, 75.0)); } -/// Transform Each refuses Reflect X, Reflect Y, Random, Copy, Scale Strokes & Effects, Scale -/// Corners, Transform Objects or Transform Patterns given as text or as another value that is not -/// true or false, and the object stays as it was and is not copied; true, false and null still work. +/// Transform Each refuses Reflect X, Reflect Y, Random, Copy, Relative, Scale Strokes & Effects, +/// Scale Corners, Transform Objects or Transform Patterns given as text or as another value that is +/// not true or false, and the object stays as it was and is not copied; true, false and null still +/// work. #[test] fn transform_each_refuses_a_boolean_given_as_text() { let mut s = session(); @@ -1160,6 +1216,8 @@ fn transform_each_refuses_a_boolean_given_as_text() { ("random", json!({"moveH": 10, "random": "false"})), ("copy", json!({"copy": "true"})), ("copy", json!({"moveH": 10, "copy": [true]})), + ("relative", json!({"relative": "false"})), + ("relative", json!({"relative": 0})), ("strokes", json!({"scaleH": 50, "scaleV": 50, "strokes": "false"})), ("corners", json!({"scaleH": 50, "corners": 1})), ("objects", json!({"moveH": 10, "objects": "false"})), diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 5b9973e563..e3a5588b7d 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -188,7 +188,7 @@ fn newer_keys_and_legacy_profiles_survive_open_and_save() { /// A version 1 document saved before VectorCraft 0.21.0 turned its Twist effects counterclockwise /// for a positive angle. It opens with the angles negated, so its art turns as it did; saved -/// again it is a version 2 document, and saved for an older file version it is version 1 again. +/// again it is a document of the current version, and saved for an older file version it is version 1 again. #[test] fn a_version_1_documents_twist_turns_as_it_was_saved() { use vectorcraft_doc::{Appearance, Document, Effect, Node}; @@ -212,7 +212,7 @@ fn a_version_1_documents_twist_turns_as_it_was_saved() { let p = turned.subpaths[0].anchors[0].p; assert!(p.y < 49.5, "{p:?}"); let again = json_of(&saved(&mut s, json!({}))); - assert_eq!(again["document"]["version"], 2); + assert_eq!(again["document"]["version"], vectorcraft_doc::FORMAT_VERSION); assert!(again.to_string().contains(r#""angle":-45.0"#), "{again}"); // Saved for an older file version, it is version 1 with its angle as 0.20.0 saved it. let older = json_of(&saved(&mut s, json!({"version": 3}))); 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/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index e6b4ca3d02..3cc47b7ac1 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -1355,3 +1355,215 @@ fn delete_empty_artboards_measures_clipped_art_through_the_clip() { assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [1, 3]})); assert_eq!(artboard_names(&s), ["Artboard 1", "Artboard 3"]); } + +/// Is Delete Empty Artboards enabled, and does running it then delete something? The two answers +/// must agree. +fn delete_empty_enabled_and_outcome(s: &mut Session) -> (bool, bool) { + let spec = crate::cmd::command_specs().iter().find(|c| c.id == "artboard.deleteEmpty").unwrap(); + let enabled = (spec.enabled)(s).is_ok(); + (enabled, s.execute("artboard.deleteEmpty", &json!({})).is_ok()) +} + +/// Delete Empty Artboards is enabled exactly when it deletes something: never with one artboard, +/// with every artboard empty (all but artboard 1 go), with one empty, not when the only empty one +/// is locked, and with art nested in groups and sublayers counted. +#[test] +fn delete_empty_artboards_is_enabled_exactly_when_it_deletes_something() { + /// What the case is, how its session is made, and whether the command deletes something. + type Case = (&'static str, fn() -> Session, bool); + let cases: [Case; 8] = [ + ("one empty artboard", || row_of_artboards(1), false), + ( + "one artboard with art", + || { + let mut s = row_of_artboards(1); + box_at(&mut s, 10.0, 20.0); + s + }, + false, + ), + ("every artboard empty", || row_of_artboards(3), true), + ( + "one empty", + || { + let mut s = row_of_artboards(2); + box_at(&mut s, 10.0, 20.0); + s + }, + true, + ), + ( + "the empty one locked", + || { + let mut s = row_of_artboards(2); + box_at(&mut s, 10.0, 20.0); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + s + }, + false, + ), + ( + "every artboard empty and locked", + || { + let mut s = row_of_artboards(2); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + s + }, + false, + ), + ( + "nested art on each", + || { + let mut s = row_of_artboards(2); + let a = box_at(&mut s, 10.0, 20.0); + let b = box_at(&mut s, 30.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("layer.newSublayer", &json!({})).unwrap(); + box_at(&mut s, 410.0, 20.0); + s + }, + false, + ), + ( + "nested art on one", + || { + let mut s = row_of_artboards(3); + s.execute("layer.newSublayer", &json!({})).unwrap(); + let a = box_at(&mut s, 410.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s + }, + true, + ), + ]; + for (why, make, deletes) in cases { + assert_eq!(delete_empty_enabled_and_outcome(&mut make()), (deletes, deletes), "{why}"); + } +} + +/// On documents made from a fixed seed (artboards in a row, some locked, boxes on, between and +/// across them, some grouped), Delete Empty Artboards' enabled state matches what it does. +#[test] +fn delete_empty_artboards_enabled_state_matches_the_command_on_varied_documents() { + let mut seed: u64 = 0x5eed_a17b_0a2d; + let mut next = |n: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + let mut enabled_count = 0; + for _ in 0..60 { + let mut s = row_of_artboards(1 + next(4) as usize); + let artboards = s.doc().unwrap().doc.artboards.len(); + for i in 0..artboards { + if next(4) == 0 { + s.execute("artboard.setProps", &json!({"index": i, "locked": true})).unwrap(); + } + } + let mut ids = vec![]; + for _ in 0..next(4) { + ids.push(box_at(&mut s, next(1700) as f64 - 50.0, 5.0 + next(300) as f64).0); + } + if ids.len() > 1 && next(2) == 0 { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + let (enabled, deleted) = delete_empty_enabled_and_outcome(&mut s); + assert_eq!(enabled, deleted, "{:?}", s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, a.locked)).collect::>()); + enabled_count += usize::from(enabled); + } + assert!(enabled_count > 5 && enabled_count < 55, "both answers come up: {enabled_count} of 60 enabled"); +} + +/// On paths and compound paths made from a fixed seed (curves, open and closed, with strokes of +/// every join, cap and alignment, miter limits, arrowheads, width profiles and dashes), an +/// artboard has art exactly when an object's visual bounds meet it, for artboards just inside, +/// on and just outside each object's visual box and far from it; and +/// [`Document::any_artboard_without_art`] answers as asking [`Document::artboard_has_art`] of each. +#[test] +fn empty_artboard_checks_match_the_visual_bounds_on_varied_strokes() { + use vectorcraft_doc::{Appearance, AppearanceItem, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile}; + use vectorcraft_geom::Rect; + let mut seed: u64 = 0xa27b_0a2d_e6b7; + let mut next = |n: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + let (mut rects_checked, mut with_art) = (0, 0); + for _ in 0..40 { + let mut s = session(); + let path = |s: &mut Session, next: &mut dyn FnMut(u64) -> u64| { + let mut d = format!("M {} {}", 100 + next(400), 100 + next(300)); + for _ in 0..1 + next(4) { + let mut pt = || format!("{} {}", 100 + next(400), 100 + next(300)); + d += &format!(" C {} {} {}", pt(), pt(), pt()); + } + if next(2) == 0 { + d += " Z"; + } + s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap() + }; + let mut objects = vec![]; + for _ in 0..1 + next(3) { + let id = if next(3) == 0 { + let ids = [path(&mut s, &mut next), path(&mut s, &mut next)]; + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap() + } else { + path(&mut s, &mut next) + }; + let mut look = Appearance::default(); + for _ in 0..1 + next(2) { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 0.5 + next(30) as f64); + st.join = [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel][next(3) as usize]; + st.cap = [LineCap::Butt, LineCap::Round, LineCap::Square][next(3) as usize]; + st.align = [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside][next(3) as usize]; + st.miter_limit = 1.0 + next(20) as f64; + let mut head = || (next(3) == 0).then(|| Arrowhead::ALL[next(Arrowhead::ALL.len() as u64) as usize]); + (st.start_arrow, st.end_arrow) = (head(), head()); + st.arrow_scale = (50.0 + next(250) as f64, 50.0 + next(250) as f64); + if next(3) == 0 { + st.profile = Some(WidthProfile { points: vec![(0.0, next(3) as f64, 1.0), (0.5, 0.5, next(4) as f64), (1.0, 1.0, 0.25)] }); + } + if next(3) == 0 { + st.dash = Some(Dash { pattern: vec![1.0 + next(10) as f64, 1.0 + next(10) as f64], offset: 0.0, align_corners: false }); + } + look.items.push(AppearanceItem::Stroke(st)); + } + s.edit("Strokes", |d, _| { + d.node_mut(NodeId(id)).unwrap().appearance = look.into(); + Ok(()) + }) + .unwrap(); + objects.push(NodeId(id)); + } + let d = &s.doc().unwrap().doc; + let symbols = d.symbol_boxes(); + let boxes: Vec = objects.iter().filter_map(|id| d.node(*id).unwrap().visual_bounds_with(&symbols)).collect(); + let has_art = |r: Rect| { + let r = r.inflate(1e-6, 1e-6); + boxes.iter().any(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1) + }; + let mut rects = vec![Rect::new(5000.0, 5000.0, 5200.0, 5150.0)]; + for b in &boxes { + for gap in [-0.01, 0.0, 5e-7, 2e-6, 0.01, 1.0] { + rects.push(Rect::new(b.x1 + gap, b.y0, b.x1 + gap + 10.0, b.y1)); + rects.push(Rect::new(b.x0 - gap - 10.0, b.y0, b.x0 - gap, b.y1)); + rects.push(Rect::new(b.x0, b.y1 + gap, b.x1, b.y1 + gap + 10.0)); + rects.push(Rect::new(b.x0, b.y0 - gap - 10.0, b.x1, b.y0 - gap)); + } + } + for r in &rects { + assert_eq!(d.artboard_has_art(*r), has_art(*r), "{r:?} against {boxes:?}"); + rects_checked += 1; + with_art += usize::from(has_art(*r)); + } + for _ in 0..20 { + let pick: Vec = (0..1 + next(3)).map(|_| rects[next(rects.len() as u64) as usize]).collect(); + assert_eq!(d.any_artboard_without_art(pick.iter().copied()), pick.iter().any(|r| !has_art(*r)), "{pick:?} against {boxes:?}"); + } + } + assert!(with_art > rects_checked / 4 && with_art < rects_checked * 3 / 4, "both answers come up: {with_art} of {rects_checked}"); +} 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 87b943d6c1..dcd1bd6a1b 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -582,6 +582,60 @@ fn set_pref(s: &mut Session, key: &str, value: Value) { s.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); } +/// New type with the session's defaults: its id and language. +fn new_type(s: &mut Session) -> (NodeId, Option) { + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + (id, type_language(s, id)) +} + +fn type_language(s: &Session, id: NodeId) -> Option { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") }; + t.runs[0].style.language.clone() +} + +/// Preferences › Hyphenation › Default Language (#394) is the language of new type, stored as its +/// tag. Type already there keeps its language, and a language chosen in Document Setup comes first. +#[test] +fn default_language_is_the_language_of_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let (before, language) = new_type(&mut s); + assert_eq!(language, None, "the default language isn't stored"); + + set_pref(&mut s, "hyphenationLanguage", json!("German")); + assert_eq!(s.prefs.hyphenation_language, "de", "a name is stored as its tag"); + assert_eq!(new_type(&mut s).1.as_deref(), Some("de")); + assert_eq!(type_language(&s, before), None, "type already there stays as it is"); + + s.execute("document.setup", &json!({"language": "French"})).unwrap(); + assert_eq!(new_type(&mut s).1.as_deref(), Some("fr"), "the document's own language comes first"); + + set_pref(&mut s, "hyphenationLanguage", json!("en-US")); + s.execute("document.setup", &json!({"language": "English: USA"})).unwrap(); + assert_eq!(new_type(&mut s).1, None); +} + +/// Preferences saved before the language was a tag hold its name; a language no longer in the list +/// reads as the default. +#[test] +fn a_saved_default_language_reads_as_its_tag() { + let read = |v: &str| serde_json::from_value::(json!({"hyphenationLanguage": v})).unwrap().hyphenation_language; + assert_eq!(read("German"), "de"); + assert_eq!(read("English: USA"), "en-US"); + assert_eq!(read("de"), "de"); + assert_eq!(read("Klingon"), "en-US"); + assert_eq!(Prefs::default().hyphenation_language, "en-US"); +} + +/// The preference offers every language the Character panel and Document Setup do. +#[test] +fn default_language_offers_every_language() { + let spec = PREF_SPECS.iter().find(|p| p.key == "hyphenationLanguage").unwrap(); + let crate::cmd::prefscmds::PrefKind::Choice(options) = spec.kind else { panic!("a choice") }; + let languages: Vec<(&str, &str)> = vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, tag, _)| (*tag, *name)).collect(); + assert_eq!(options, languages.as_slice()); +} + fn gesture(s: &mut Session, v: ViewInfo, events: &[(vectorcraft_tools::PointerKind, f64, f64)]) { for (k, x, y) in events { s.pointer(&vectorcraft_tools::PointerEvent::new(*k, *x, *y), v).unwrap(); @@ -1072,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}; @@ -1088,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(); @@ -1947,6 +2008,52 @@ fn a_move_held_by_a_paths_stroke_lands_the_path_on_a_ruler_guide() { } } +/// #5746: a rectangle dragged until its left edge and its top edge are each 1 px from a ruler +/// guide lands on both guides, with "align", whichever guide was added last and wherever it was +/// grabbed; between two upright guides, its left edge lands on the one within reach; and an edge +/// Smart Guides line up with another object stays there, not on a ruler guide as near. +#[test] +fn a_moved_rectangle_lines_its_edges_up_with_two_ruler_guides() { + use vectorcraft_tools::Overlay; + use vectorcraft_tools::PointerKind::{Down, Drag, Up}; + let v = ViewInfo::default(); + // (guides as (vertical, pos), where it is grabbed, the top left it lands on) + type Case = (&'static [(bool, f64)], (f64, f64), (f64, f64)); + let cases: [Case; 3] = [ + (&[(true, 250.0), (false, 320.0)], (200.0, 100.0), (250.0, 320.0)), + (&[(false, 320.0), (true, 250.0)], (100.0, 175.0), (250.0, 320.0)), + (&[(true, 250.0), (true, 455.0)], (200.0, 175.0), (250.0, 100.0)), + ]; + for (guides, (x, y), want) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + for (vertical, pos) in guides { + s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + // 1 px past the guides: the left edge at 251, the top edge at 321 (or where it was). + let (to_x, to_y) = (x + 151.0, if want.1 == 100.0 { y } else { y + 221.0 }); + gesture(&mut s, v, &[(Down, x, y), (Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), (Drag, to_x, to_y)]); + let align = s.overlays(v).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align")); + gesture(&mut s, v, &[(Up, to_x, to_y)]); + assert_eq!(top_left(&s, id), want, "guides {guides:?}, grabbed at ({x}, {y})"); + assert!(align, "guides {guides:?}, grabbed at ({x}, {y}): no align"); + } + // Dragged by its centre until its left edge is at 401: 1 px from another rectangle's left + // edge (400) and 1 px from a ruler guide (402). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 400, "y": 400, "width": 60, "height": 60})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 402.0})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + gesture(&mut s, v, &[(Down, 200.0, 175.0), (Drag, 350.0, 175.0), (Drag, 501.0, 175.0), (Up, 501.0, 175.0)]); + assert_eq!(top_left(&s, id), (400.0, 100.0), "a Smart Guides alignment gave way to a ruler guide"); +} + /// #3701: at 28,757%, Direct Selection pressed 1.5 px beside a rectangle's straight left side and /// dragged until the side is 1 px from a ruler guide lands both its anchors on the guide; so does /// the same press and drag on the rectangle selected whole, which moves it. 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 923cd1d12a..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"] { @@ -2561,6 +2728,217 @@ fn the_default_glyph_chosen_in_overflowing_vertical_type_is_kept() { assert_eq!(held, [g('!')], "the default glyph is kept as the choice"); } +/// A character that overflows its area reports as `chosen` the glyph it is drawn with when it is +/// shaped alone: the glyph `salt` draws, a chosen default glyph, and the `vert` glyph of vertical +/// type. +#[test] +fn the_glyph_query_shapes_an_overflowing_character() { + use vectorcraft_text::test_fonts::{VERTICAL_PUNCTUATION_FAMILY, alternates_family, alternates_font, vertical_punctuation_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + db.add_font(vertical_punctuation_font(true).expect("the test font builds")); + let face = db.face(alternates_family(true), "Regular").expect("the test face"); + let g = |c| face.glyph_for(c); + let mut s = session(); + let chosen = |s: &mut Session, id: NodeId, start: usize| { + s.execute("text.glyphAlternates", &json!({"id": id.0, "start": start})).unwrap()["chosen"].clone() + }; + + let area = json!({"x": 0, "y": 300, "text": "xa", "size": 20, "font": alternates_family(true), "area": {"width": 200, "height": 4}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": boxed.0, "start": 0, "end": 2, "features": ["salt"]})).unwrap(); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + assert_eq!(chosen(&mut s, boxed, 1), json!(g('b')), "the glyph salt draws"); + s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 1, "gid": g('a')})).unwrap(); + assert_eq!(chosen(&mut s, boxed, 1), json!(g('a')), "the chosen default glyph"); + + let vface = db.face(VERTICAL_PUNCTUATION_FAMILY, "Regular").expect("the test face"); + let text = + json!({"x": 0, "y": 0, "text": "!!", "size": 20, "font": VERTICAL_PUNCTUATION_FAMILY, "vertical": true, "area": {"width": 4, "height": 4}}); + let vertical = NodeId(s.execute("text.create", &text).unwrap()["id"].as_u64().unwrap()); + assert!(vectorcraft_text::layout(db, &obj(&s, vertical)).glyphs.is_empty(), "the text overflows"); + assert_eq!(chosen(&mut s, vertical, 0), json!(vface.glyph_for('I')), "vert draws ! as I"); +} + +/// A parenthesis set right to left is drawn mirrored: in a paragraph whose direction is right to +/// left, and after Hebrew in a paragraph of automatic direction, but not when its character +/// direction is left to right. When it overflows its area, the glyph query shapes it in the same +/// direction and reports the glyph the text draws when it fits. +#[test] +fn the_glyph_query_shapes_an_overflowing_character_in_its_paragraph_direction() { + let db = vectorcraft_text::FontDb::global(); + let face = db.face("Source Sans 3", "Regular").expect("the bundled face"); + let mut s = session(); + let create = |s: &mut Session, text: &str, rtl: bool, char_ltr: bool, height: f64| { + let spec = json!({"x": 0, "y": 0, "text": text, "size": 20, "font": "Source Sans 3", "area": {"width": 200, "height": height}}); + let id = NodeId(s.execute("text.create", &spec).unwrap()["id"].as_u64().unwrap()); + if rtl { + s.execute("text.setFormat", &json!({"ids": [id.0], "direction": "rightToLeft", "start": 2, "end": 3})).unwrap(); + } + if char_ltr { + s.execute("text.setFormat", &json!({"ids": [id.0], "charDirection": "leftToRight", "start": 2, "end": 3})).unwrap(); + } + id + }; + for (text, rtl, char_ltr, at, drawn) in [("a\n(", true, false, 2, ')'), ("a\n\u{5D0}(", false, false, 4, ')'), ("a\n(", true, true, 2, '(')] { + let open = create(&mut s, text, rtl, char_ltr, 200.0); + let lay = vectorcraft_text::layout(db, &obj(&s, open)); + assert_eq!(lay.glyphs.iter().find(|g| g.byte == at).map(|g| g.gid), Some(face.glyph_for(drawn)), "{text:?}: the parenthesis drawn"); + + let boxed = create(&mut s, text, rtl, char_ltr, 30.0); + let lay = vectorcraft_text::layout(db, &obj(&s, boxed)); + assert!(lay.glyphs.iter().all(|g| g.byte < 2), "{text:?}: the second paragraph overflows"); + let r = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": at})).unwrap(); + assert_eq!(r["chosen"], json!(face.glyph_for(drawn)), "{text:?}: the glyph drawn when it fits"); + } +} + +/// A vowel sign drawn before its consonant (Devanagari Ka with the vowel sign I) is in the +/// consonant's cluster, drawn first: with `salt`, the glyph reported for the consonant is the one +/// the feature draws, not the vowel sign's, and the default glyph chosen for it is drawn. +#[test] +fn the_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { + use vectorcraft_text::test_fonts::{MATRA_FAMILY, matra_font, source_sans_gid}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(matra_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let mut s = session(); + let text = "क\u{93F}"; + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": text, "size": 20, "font": MATRA_FAMILY})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": text.len(), "features": ["salt"]})).unwrap(); + let gids = |s: &Session| vectorcraft_text::layout(db, &obj(s, id)).glyphs.iter().map(|gl| (gl.gid, gl.byte, gl.len)).collect::>(); + assert_eq!(gids(&s), [(g('i'), 0, 6), (g('b'), 0, 6)], "the vowel sign is drawn first, in the cluster of Ka as salt draws it"); + + let query = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap(); + assert_eq!(query["chosen"], json!(g('b')), "the glyph salt draws for Ka"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b'))); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": g('a')})).unwrap(); + assert_eq!(r["gid"], json!(g('a'))); + assert!(gids(&s).iter().any(|&(gl, byte, _)| (gl, byte) == (g('a'), 0)), "Ka draws its default glyph: {:?}", gids(&s)); + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap()["chosen"], json!(g('a'))); +} + +/// Ka with a nukta and the vowel sign I is one cluster: the vowel sign drawn first, then the +/// ligature of Ka and the nukta, which is neither Ka's default glyph nor one of its alternates. The +/// glyph reported for Ka is the ligature, not the vowel sign. +#[test] +fn the_ligature_of_a_consonant_after_its_vowel_sign_is_reported() { + use vectorcraft_text::test_fonts::{MATRA_FAMILY, matra_font, source_sans_gid}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(matra_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let mut s = session(); + let text = "क\u{93C}\u{93F}"; + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": text, "size": 20, "font": MATRA_FAMILY})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let gids: Vec<_> = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().map(|gl| (gl.gid, gl.byte, gl.len)).collect(); + assert_eq!(gids, [(g('i'), 0, 9), (g('N'), 0, 9)], "the vowel sign is drawn first, then the ligature"); + + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap()["chosen"], json!(g('N'))); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('N')), "the ligature is drawn for Ka"); +} + +/// Ka, the halant, Ka again and the vowel sign I are one cluster: the vowel sign drawn first, the +/// first Ka's half form, which the font lists as an alternate of Ka, then the second Ka's default +/// glyph. The glyph reported for the first Ka is its half form, the first of its glyphs in the +/// cluster, not the second Ka's default glyph. The font also lists the vowel sign's glyph as an +/// alternate of Ka; drawn for the vowel sign, it is not reported for Ka. +#[test] +fn the_first_of_a_characters_glyphs_in_its_cluster_is_reported() { + use vectorcraft_text::test_fonts::{CONJUNCT_FAMILY, conjunct_font, source_sans_gid}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(conjunct_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let mut s = session(); + let text = "क\u{94D}क\u{93F}"; + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": text, "size": 20, "font": CONJUNCT_FAMILY})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let gids: Vec<_> = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().map(|gl| (gl.gid, gl.byte, gl.len)).collect(); + assert_eq!(gids, [(g('i'), 0, 12), (g('k'), 0, 12), (g('K'), 0, 12)], "the vowel sign, the half form, then the second Ka"); + + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap()["chosen"], json!(g('k'))); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('k')), "the half form is drawn for the first Ka"); + + let text = "क\u{93F}"; + let r = s.execute("text.create", &json!({"x": 100, "y": 200, "text": text, "size": 20, "font": CONJUNCT_FAMILY})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let gids: Vec<_> = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().map(|gl| (gl.gid, gl.byte, gl.len)).collect(); + assert_eq!(gids, [(g('i'), 0, 6), (g('K'), 0, 6)], "the vowel sign, then Ka"); + assert_eq!(s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap()["chosen"], json!(g('K'))); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('K')), "Ka's default glyph, not the vowel sign's"); +} + +/// A character that overflows its area is shaped with its grapheme: the nukta after Ka makes the +/// font's `nukt` ligature, which `salt` does not change, so `gid: null` reports the ligature as it +/// does for the laid-out text. +#[test] +fn the_glyph_of_an_overflowing_character_is_shaped_with_its_grapheme() { + use vectorcraft_text::test_fonts::{MATRA_FAMILY, matra_font, source_sans_gid}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(matra_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let mut s = session(); + let text = "क\u{93C}"; + let point = json!({"x": 100, "y": 100, "text": text, "size": 20, "font": MATRA_FAMILY}); + let id = NodeId(s.execute("text.create", &point).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": text.len(), "features": ["salt"]})).unwrap(); + let gids: Vec<_> = vectorcraft_text::layout(db, &obj(&s, id)).glyphs.iter().map(|gl| (gl.gid, gl.byte, gl.len)).collect(); + assert_eq!(gids, [(g('N'), 0, 6)], "Ka and the nukta make the ligature"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": id.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('N'))); + + let area = json!({"x": 0, "y": 300, "text": text, "size": 20, "font": MATRA_FAMILY, "area": {"width": 200, "height": 4}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": boxed.0, "start": 0, "end": text.len(), "features": ["salt"]})).unwrap(); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('N')), "the overflowing Ka is shaped with its nukta"); +} + +/// A grapheme whose characters have different styles is shaped in those styles when it overflows: +/// a nukta of another size does not make the `nukt` ligature with Ka, so `gid: null` reports the +/// glyph `salt` draws for Ka, as it does for the laid-out text. +#[test] +fn an_overflowing_grapheme_keeps_the_styles_of_its_characters() { + use vectorcraft_text::test_fonts::{MATRA_FAMILY, matra_font, source_sans_gid}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(matra_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a Source Sans glyph")); + let mut s = session(); + let text = "क\u{93C}"; + let styled = |s: &mut Session, area: Option| { + let mut spec = json!({"x": 0, "y": 300, "text": text, "size": 20, "font": MATRA_FAMILY}); + if let Some(area) = area { + spec["area"] = area; + } + let id = NodeId(s.execute("text.create", &spec).unwrap()["id"].as_u64().unwrap()); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": text.len(), "features": ["salt"]})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 3, "end": text.len(), "size": 30})).unwrap(); + id + }; + let open = styled(&mut s, None); + let lay = vectorcraft_text::layout(db, &obj(&s, open)); + assert_eq!(lay.glyphs.iter().find(|gl| gl.byte == 0).map(|gl| gl.gid), Some(g('b')), "the nukta of another size makes no ligature"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": open.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b'))); + + let boxed = styled(&mut s, Some(json!({"width": 200, "height": 4}))); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + let r = s.execute("text.setGlyphAlternate", &json!({"id": boxed.0, "start": 0, "gid": null})).unwrap(); + assert_eq!(r["gid"], json!(g('b')), "the overflowing Ka is shaped apart from the nukta of another size"); +} + #[test] fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; @@ -2582,4 +2960,71 @@ fn glyph_alternates_query_reports_the_fallback_glyph_that_is_drawn() { let query = s.execute("text.glyphAlternates", &json!({"id": id.0, "start": 0})).unwrap(); assert_eq!(query["chosen"], json!(glyph.gid), "the query reports the visible fallback glyph"); assert!(query["alternates"].as_array().unwrap().is_empty()); + + let area = json!({"x": 0, "y": 300, "text": ch.to_string(), "font": alternates_family(true), "area": {"width": 200, "height": 2}}); + let boxed = NodeId(s.execute("text.create", &area).unwrap()["id"].as_u64().unwrap()); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + let query = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": 0})).unwrap(); + assert_eq!(query["chosen"], json!(glyph.gid), "an overflowing character reports the fallback glyph it is drawn with"); +} + +/// A fallback face draws Ka with the vowel sign I in one cluster, the vowel sign first. The glyph +/// reported for Ka is the fallback face's glyph for Ka, laid out or overflowing, not the vowel +/// sign's. +#[test] +fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { + use vectorcraft_text::test_fonts::{MATRA_FAMILY, alternates_family, alternates_font, matra_font}; + let _fonts = crate::adding_fonts(); + let db = vectorcraft_text::FontDb::global(); + db.add_font(alternates_font(true).expect("the test font builds")); + db.add_font(matra_font().expect("the test font builds")); + let requested = db.face(alternates_family(true), "Regular").expect("the test face"); + let text = "क\u{93F}"; + assert_eq!(requested.glyph_for('क'), 0); + let mut s = session(); + let create = |s: &mut Session, height: f64| { + let spec = json!({"x": 0, "y": 0, "text": text, "font": alternates_family(true), "area": {"width": 200, "height": height}}); + NodeId(s.execute("text.create", &spec).unwrap()["id"].as_u64().unwrap()) + }; + let open = create(&mut s, 200.0); + 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 = fallback.glyph_for('क'); + let drawn: Vec<_> = glyphs.iter().map(|g| (g.gid, g.byte)).collect(); + // 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"); + + let boxed = create(&mut s, 2.0); + assert!(vectorcraft_text::layout(db, &obj(&s, boxed)).glyphs.is_empty(), "the text overflows"); + 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/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 3010901ca7..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]})), @@ -526,6 +530,10 @@ fn structured_junk() { ("document.open", json!({"name": "x.pdf", "dataBase64": "JVBERi0xLjQK"})), ("document.open", json!({"name": "x.vectorcraft", "dataBase64": "e30="})), ("document.activate", json!({"index": 99})), + ("document.move", json!({"from": 99, "to": 0})), + ("document.move", json!({"from": 0, "to": u64::MAX})), + ("document.move", json!({"from": -1, "to": 1e308})), + ("document.move", json!({"from": "x", "to": null})), ("file.close", json!({"index": 99})), ("file.new", json!({"width": -1, "height": 0, "artboards": 1000000})), ("command.batch", json!({"commands": [{"command": 5}, {"params": 3}]})), @@ -593,6 +601,12 @@ fn structured_junk() { ("addon.pathtools.cornerSet", json!({"items": [1, null, {"anchors": "x"}], "radius": 1})), ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 1e308, "kind": "spiky"})), ("addon.pathtools.cornerSet", json!({"items": "all", "radius": f64::NAN, "anchors": [-1, 1.5, "x"]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"items": [{"id": 2, "anchors": [1, u64::MAX]}], "radius": 5, "every": "even"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "every": [1, "x", null]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "minAngle": 0, "maxAngle": 0})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": 180, "maxAngle": 180, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": f64::MAX, "maxAngle": -1e-300})), ("addon.pathtools.cornerRemove", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.cornerRemove", json!({"items": [{"id": 2, "anchors": [u64::MAX]}]})), ("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.98})), @@ -662,6 +676,11 @@ fn structured_junk() { ("addon.type.textTweaker", json!({"attribute": "rotation", "from": -360, "to": 360, "shape": "bow", "skipSpaces": false, "ids": [u64::MAX]})), ("addon.type.textTweaker", json!({"attribute": "hScale", "id": 2, "start": u64::MAX, "end": 0, "shape": "ease"})), ("addon.type.textTweaker", json!({"attribute": ["size"], "from": "x", "seed": 1e308, "skipSpaces": "no", "ids": "all"})), + ("addon.type.releasePath", json!({"mode": "both", "keepOriginal": true, "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8]})), + ("addon.type.releasePath", json!({"mode": "path", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), + ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), + ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), + ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), ("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.breakText", json!({"by": ["lines"]})), ("addon.cleanup.breakText", json!({"by": "paragraphs"})), 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/eps/src/scene.rs b/crates/eps/src/scene.rs index 64c5da6d4d..1c3143f3f6 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -751,7 +751,8 @@ impl<'a> Scene<'a> { /// The stops of a gradient with a spot ink as tints of its inks: a Separation space when every /// stop is a tint of one spot ink or paper white, else (at Level 3) a DeviceN space of the /// process inks the stops use, in CMYK order, and the spot inks, in the order the stops name - /// them. Paper white adds no ink and a gray stop is black ink. An off-center midpoint is a stop + /// them. Paper white adds no ink, a gray stop is black ink, and a spot stop's process plates + /// print with its ink. An off-center midpoint is a stop /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; /// it is then written in process colors. @@ -799,6 +800,10 @@ impl<'a> Scene<'a> { if let Some(i) = names.iter().position(|m| *m == n) { v[4 + i] = unit(s.tint); } + // Process plates printed with the spot ink (a DeviceN mix from a file). + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(unit)); + } } None if paper(&s.color) => {} None => match self.process(&s.color) { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 2067a7d9c2..2a59f99df2 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -352,6 +352,16 @@ fn gradients_mixing_spot_inks_with_other_inks_are_device_n_shadings() { assert!(page.contains("/C0 [0 0 1] /C1 [0.6 0 0]") && page.contains("/C0 [0.6 0 0] /C1 [0 0.4 0]"), "{page}"); assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + // Gold Ink 0% to 100% over a constant 30% cyan plate (a DeviceN gradient read from a PDF, + // #3235): Cyan and Gold Ink. + let mut over = spot_stop(1.0, "Gold Ink", GOLD, 1.0); + over.plates = Some([0.3, 0.0, 0.0, 0.0]); + let plated = spot_gradient_doc(vec![GradientStop::new(0.0, Color::cmyk(0.3, 0.0, 0.0, 0.0)), over]); + let out = export(&plated, &opts(&plated), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains("/VCdn0 [/DeviceN [/Cyan (Gold Ink) cvn ] /DeviceCMYK {2 array astore"), "{ps}"); + assert!(checked_page(&ps).contains("/C0 [0.3 0] /C1 [0.3 1]"), "{ps}"); + // Read back as bands, the tint transforms give each ink's CMYK equivalent. for (d, end) in [(&two, [0.5, 0.0, 0.5, 0.0]), (&mixed, [0.0, 0.0, 0.0, 0.4])] { let out = export(d, &EpsOptions { compatible_gradients: true, ..opts(d) }, None, None).unwrap(); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 65c10ba802..f82cd4eb1b 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -251,8 +251,11 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } - // Apps that read only older file versions predate 0.21.0 and turn Twist the other way. + // Apps before this one's version take Color Halftone's Max Radius in points (#3260), and + // predate 0.21.0, turning Twist the other way. The radii first: their conversion runs only on + // a document of version 3 or later, and the Twist one then marks it version 1. if version < VERSION { + d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } let v1 = if version == 1 { @@ -547,6 +550,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result doc.migrate_overprint_black(); // Saved before v3: the assigned profiles move out of `unknown`. doc.migrate_color_profiles(); + // A document before version 3: Color Halftone's Max Radius in points becomes pixels (#3260). + doc.migrate_halftone_radii(); doc.fix_next_id(); // Untrusted: the bleed and type proportions, within the ranges Document Setup takes. doc.setup.keep_in_range(); @@ -839,6 +844,49 @@ mod tests { use vectorcraft_doc::{Appearance, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect, shapes}; + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document + /// version 3 (#3260): a file from before (version 1, or version 2 from 0.21.0 on) opens with + /// its radius in points converted, one saved since opens as it was. At 72 ppi a point is a + /// pixel, so the number stays. + #[test] + fn halftone_radii_of_older_documents_open_in_pixels() { + for ppi in [72.0, 300.0] { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = ppi; + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut look = Appearance::default_art(); + look.effects.push(vectorcraft_doc::Effect { + id: "pixelate.colorHalftone".into(), + params: serde_json::json!({"maxRadius": 8.0}), + visible: true, + }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), look)).unwrap(); + let radius = |d: &Document| d.node(id).unwrap().appearance.effects[0].params["maxRadius"].as_f64().unwrap(); + assert_eq!(radius(&load(&save(&d, false)).unwrap()), 8.0, "{ppi} ppi: saved in pixels, opened in pixels"); + // Version 2 (0.21.0's Twist) still held the radius in points. + d.version = 2; + let v2 = load(&save(&d, false)).unwrap(); + assert!((radius(&v2) - 8.0 * ppi / 72.0).abs() < 1e-9, "version 2, 8 pt at {ppi} ppi: {}", radius(&v2)); + d.version = 1; + let old = load(&save(&d, false)).unwrap(); + assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); + assert!((radius(&old) - 8.0 * ppi / 72.0).abs() < 1e-9, "8 pt at {ppi} ppi: {}", radius(&old)); + // Saved for an older app, in every older version: the radius in points, which opens + // here in pixels again. + let px = radius(&old); + for version in MIN_VERSION..VERSION { + let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); + let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); + let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); + assert!((saved - 8.0).abs() < 1e-9, "{ppi} ppi, version {version} holds 8 pt: {saved}"); + let back = load(&bytes).unwrap(); + assert!((radius(&back) - px).abs() < 1e-9, "{ppi} ppi, version {version}: {}", radius(&back)); + } + assert_eq!(radius(&old), px, "{ppi} ppi: saving leaves the open document as it is"); + } + } + #[test] fn roundtrip() { let mut d = Document::new(100.0, 100.0); @@ -909,8 +957,8 @@ mod tests { /// A version 1 document written before VectorCraft 0.21.0 (or by an app the file does not /// name) has its Twist angles negated when it opens; one written by 0.21.0 or later, and a - /// version 2 document, keep them. Each opens as version 2. A save for an older file version - /// negates them back. + /// later document, keep them. Each opens as the current version. A save for an older file + /// version negates them back. #[test] fn twist_angles_follow_the_document_version_and_generator() { use vectorcraft_doc::Effect; @@ -921,9 +969,14 @@ mod tests { a.effects.push(Effect { id: "distort.twist".into(), params: serde_json::json!({"angle": 30.0}), visible: true }); d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), a)).unwrap(); let angle = |d: &Document| d.node(id).and_then(|n| n.appearance.effects[0].params["angle"].as_f64()); + let now = vectorcraft_doc::FORMAT_VERSION; let current = save(&d, false); let back = load(¤t).unwrap(); - assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "a version 2 document is read as saved"); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "a current document is read as saved"); + let mut v2: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v2["document"]["version"] = 2.into(); + let back = load(&serde_json::to_vec(&v2).unwrap()).unwrap(); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "a version 2 document keeps its angles"); let opened = |generator: Option<&str>| { let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); v["document"]["version"] = 1.into(); @@ -937,10 +990,10 @@ mod tests { (d.version, angle(&d)) }; for g in [Some("VectorCraft 0.20.0"), Some("VectorCraft 0.9.12"), Some("DrawCraft 0.1.0"), Some("VectorCraft"), None] { - assert_eq!(opened(g), (2, Some(-30.0)), "{g:?}"); + assert_eq!(opened(g), (now, Some(-30.0)), "{g:?}"); } for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.3", "VectorCraft 1.0.0"] { - assert_eq!(opened(Some(g)), (2, Some(30.0)), "{g}"); + assert_eq!(opened(Some(g)), (now, Some(30.0)), "{g}"); } // A file may repeat `generator`: the first one names the app. let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); @@ -954,7 +1007,7 @@ mod tests { v["generator"] = "VectorCraft 0.20.0".into(); let old = load(&serde_json::to_vec(&v).unwrap()).unwrap(); let again = load(&save(&old, false)).unwrap(); - assert_eq!((again.version, angle(&again)), (2, Some(-30.0)), "saved again, it is version 2"); + assert_eq!((again.version, angle(&again)), (now, Some(-30.0)), "saved again, it is the current version"); // Saved for an older file version (apps before 0.21.0): version 1 with the angle negated // back, whatever the generator, and it reopens as it was. for version in MIN_VERSION..VERSION { @@ -963,7 +1016,7 @@ mod tests { assert_eq!(v["document"]["version"], 1, "file version {version}"); assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}"); let back = load(&bytes).unwrap(); - assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "file version {version}"); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "file version {version}"); } } diff --git a/crates/geom/src/bez.rs b/crates/geom/src/bez.rs index 408f3abdb5..8f6b3c4a0a 100644 --- a/crates/geom/src/bez.rs +++ b/crates/geom/src/bez.rs @@ -39,6 +39,15 @@ pub fn segments(els: &[PathEl]) -> Vec { kurbo::segments(els.iter().copied()).collect() } +/// Whether `s` has length: a segment all of whose points coincide has none, and no direction. +pub fn has_length(s: &PathSeg) -> bool { + match s { + PathSeg::Line(l) => l.p1 != l.p0, + PathSeg::Quad(q) => q.p1 != q.p0 || q.p2 != q.p0, + PathSeg::Cubic(c) => c.p1 != c.p0 || c.p2 != c.p0 || c.p3 != c.p0, + } +} + /// Unit tangent of `s` at `t`, robust at ends where control points coincide with the end point. pub fn tangent(s: &PathSeg, t: f64) -> Vec2 { let d = match s { 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/export/paint.rs b/crates/pdf/src/export/paint.rs index 379ebbd506..3138484ebd 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -92,7 +92,8 @@ impl Exporter<'_> { .stops .iter() .map(|s| match s.swatch.as_deref() { - Some(n) if n == ink => Some(s.tint), + // A stop that also prints process plates needs a DeviceN space. + Some(n) if n == ink && s.plates.is_none() => Some(s.tint), _ if self.paper_stop(s) => Some(0.0), _ => None, }) @@ -119,7 +120,8 @@ impl Exporter<'_> { /// a DeviceN space of the process inks the stops use (in CMYK order) and the spot inks (in /// the order the stops name them), with midpoints as explicit stops (the tints and opacity /// there are halfway), or for a Perceptual gradient the stops on its curve - /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink. `None`, with a + /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink; a spot stop with + /// process plates ([`vectorcraft_color::GradientStop::plates`]) prints them too. `None`, with a /// warning, when a stop is written in RGB or Lab or the spot inks can't share a DeviceN space; /// the gradient is then written in the colors of its stops. fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { @@ -145,6 +147,9 @@ impl Exporter<'_> { Some(n) => { let i = spots.iter().position(|(m, _)| *m == n)?; v[4 + i] = s.tint; + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(|t| t.clamp(0.0, 1.0))); + } } None if self.paper_stop(s) => {} None => match self.page_color(&s.color) { @@ -379,7 +384,7 @@ impl Exporter<'_> { fn one_spot_ink<'g>(&self, g: &'g vectorcraft_color::Gradient) -> Option<&'g str> { let spot = |s: &'g vectorcraft_color::GradientStop| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)); let ink = g.stops.iter().find_map(spot)?; - g.stops.iter().all(|s| spot(s) == Some(ink) || self.paper_stop(s)).then_some(ink) + g.stops.iter().all(|s| (spot(s) == Some(ink) && s.plates.is_none()) || self.paper_stop(s)).then_some(ink) } /// Can every stop of `g` be inks of a DeviceN space ([`Self::device_n_stops`]): is a stop diff --git a/crates/pdf/src/import_color.rs b/crates/pdf/src/import_color.rs index 2362634edb..b7e033b6ce 100644 --- a/crates/pdf/src/import_color.rs +++ b/crates/pdf/src/import_color.rs @@ -323,6 +323,41 @@ impl<'p> Colors<'p> { } } + /// A gradient stop's colour that paints one spot ink together with process plates (a + /// DeviceN colour of an ink and process colorants): the ink's swatch (marked used), its tint + /// and the process plates (C, M, Y, K). `None` for any other colour ([`Colors::native`] takes + /// it). + pub fn ink_with_plates(&mut self, space: Space, comps: &[f32]) -> Option<(String, f32, [f32; 4])> { + let Space::Inks(i) = space else { return None }; + let colorants = &self.spaces.get(i)?.colorants; + let mut cmyk = [0.0f32; 4]; + let mut ink = None; + for (c, t) in colorants.iter().zip(comps) { + let t = round3(t.clamp(0.0, 1.0)); + match *c { + Colorant::Unknown => return None, + Colorant::None => {} + Colorant::Process(ch) => { + if let Some(v) = cmyk.get_mut(ch) { + *v = v.max(t); + } + } + // A second ink (or every plate) painting too can't be one stop. + Colorant::Ink(_) | Colorant::All if t > 0.0 && ink.is_some() => return None, + Colorant::All if t > 0.0 => return None, + Colorant::Ink(k) if t > 0.0 => ink = Some((k, t)), + Colorant::Ink(_) | Colorant::All => {} + } + } + let (k, t) = ink?; + if cmyk.iter().all(|v| *v <= 0.0) { + return None; + } + let ink = self.inks.get_mut(k)?; + ink.used = true; + Some((ink.name.clone(), t, cmyk)) + } + /// Mark each ink that components `comps` of `space` paint with (a tint above 0) as used, so it /// becomes a spot swatch; nothing for a space with a colorant that can't be read. pub fn mark_inks(&mut self, space: Space, comps: &[f32]) { diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index a8a8b25eaa..c80b2a29b4 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{AppearanceItem, Node, NodeKind, OpacityMask}; use vectorcraft_geom::PathData; use crate::import::{closed_subpaths, round3}; -use crate::import_color::{Colors, Native}; +use crate::import_color::{Colors, Native, Space}; use crate::import_mask::{contains, is_rectangle, luminance}; /// The most mesh patches (or triangles) imported per shading: past it, the shading is a flat @@ -51,14 +51,8 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink } } let ts: Vec = linear_keep(&pts).iter().filter_map(|&k| pts.get(k)).map(|p| p.0).collect(); - let mut stop_at = |t: f32, offset: f32| -> GradientStop { - let rgb = sample(t).unwrap_or(Color::BLACK); - match at(t).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - } - }; + let mut stop_at = + |t: f32, offset: f32| -> GradientStop { shading_stop(colors, space, at(t).as_deref(), offset, sample(t).unwrap_or(Color::BLACK)) }; let c = |x: f32, y: f32| m * Point::new(x as f64, y as f64); let (kind, geom, stops) = if *axial { let geom = GradientGeom { start: c(coords[0], coords[1]), end: c(coords[2], coords[3]), aspect: 1.0, focal: None }; @@ -81,6 +75,21 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink Some((g, *extend)) } +/// A shading's stop at `offset` of components `comps` of `space` in their own model, linked to +/// its spot swatch at its tint (with the process plates it prints with, looking like `rgb`, the +/// colour the file gives it); `rgb` when the components can't be read or kept. +fn shading_stop(colors: &mut Colors<'_>, space: Space, comps: Option<&[f32]>, offset: f32, rgb: Color) -> GradientStop { + let Some(v) = comps else { return GradientStop::new(offset, rgb) }; + if let Some((name, tint, plates)) = colors.ink_with_plates(space, v) { + return GradientStop { swatch: Some(name), tint, plates: Some(plates), ..GradientStop::new(offset, rgb) }; + } + match colors.native(space, v) { + Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, + Some(Native { color, link: None }) => GradientStop::new(offset, color), + None => GradientStop::new(offset, rgb), + } +} + /// The samples of `pts` (offset, RGB; at least one) a gradient keeps as stops: the first, the /// last, and each one that linear interpolation between its neighbouring stops doesn't reproduce. fn linear_keep(pts: &[(f32, [f32; 3])]) -> Vec { @@ -299,11 +308,7 @@ fn function_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option< for k in linear_keep(&pts) { let Some(&(offset, read, c)) = piece.get(k) else { continue }; let rgb = Color::rgb(round3(c[0]), round3(c[1]), round3(c[2])); - out.push(match value(read).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - }); + out.push(shading_stop(colors, space, value(read).as_deref(), offset, rgb)); } } if out.len() > MAX_FUNCTION_STOPS { 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/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index e26697858f..011f298eea 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -178,12 +178,65 @@ fn a_spot_ink_mixed_with_a_process_plate_keeps_its_swatch() { for (what, page) in [("fill", fill), ("shading", sh)] { let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); let d = &r.document; - assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); - assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); let gold = d.swatch("Gold").unwrap_or_else(|| panic!("{what}: no Gold swatch")); assert!(gold.spot && gold.global, "{what}: Gold is a spot swatch"); assert!(near(gold.paint.color().unwrap(), Color::cmyk(0.0, 0.0, 1.0, 0.0)), "{what}: {gold:?}"); assert_eq!(d.swatches.iter().filter(|s| s.spot).count(), 1, "{what}: Cyan is a process plate"); + if what == "fill" { + // A solid paint can't link to an ink and process plates together. + assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); + assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); + } + } +} + +/// A gradient stop of `d`'s only gradient, in paint order. +fn gradient_stops(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n: &Node| { + for i in &n.appearance.items { + if let Paint::Gradient(g) = i.paint() { + out.extend(g.gradient.stops.iter().cloned()); + } + } + }); + out +} + +#[test] +fn a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks() { + // #3235: an axial shading in [/DeviceN [/Gold /Cyan] /DeviceCMYK …], Gold 0 to 1 over Cyan + // at 0.3 (ISO 32000-1:2008, 8.6.6.5 and 8.7.4.5.3). Its stops link to Gold, with the cyan + // plate kept, and PDF export (PDF/X-4 too) writes it again as a DeviceN shading of both inks. + let space = format!("[/DeviceN [/Gold /Cyan] /DeviceCMYK {} 0 R]", first_extra(1)); + let func = "<< /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1 0 1] /Length 17 >>\nstream\n{ exch 0 exch 0 }\nendstream"; + let shading = format!( + "<< /ShadingType 2 /ColorSpace {space} /Coords [0 0 50 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0 0.3] /C1 [1 0.3] /N 1 >> /Extend [true true] >>" + ); + let page = PdfPage { resources: format!("/Shading << /Sh0 {shading} >>"), ..PdfPage::new(100.0, 50.0, "q 0 0 50 50 re W n /Sh0 sh Q") }; + let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("several inks")), "{:?}", r.warnings); + let d = &r.document; + let stops = gradient_stops(d); + let (Some(first), Some(last)) = (stops.first(), stops.last()) else { panic!("no gradient: {stops:?}") }; + // Gold at 0 % is cyan alone; Gold at 100 % keeps the cyan plate. + assert_eq!((first.swatch.as_deref(), first.plates), (None, None), "{first:?}"); + assert!(near(first.color, Color::cmyk(0.3, 0.0, 0.0, 0.0)), "{first:?}"); + assert_eq!(last.swatch.as_deref(), Some("Gold"), "{last:?}"); + assert!((last.tint - 1.0).abs() < 1e-3, "{last:?}"); + let plates = last.plates.unwrap_or_else(|| panic!("no plates: {last:?}")); + assert!((plates[0] - 0.3).abs() < 1e-3 && plates[1..].iter().all(|p| *p == 0.0), "{plates:?}"); + // The stop looks as the file draws it: cyan and yellow, a green. + let [r_, g_, b_] = last.color.to_rgb(); + assert!(g_ > r_ && g_ > b_, "{:?}", last.color); + for standard in [Standard::None, Standard::PdfX4] { + let mut o = PdfOptions::uncompressed(); + (o.settings.standard, o.settings.compatibility) = (standard, standard.version()); + let text = String::from_utf8_lossy(&export(d, &o).unwrap()).into_owned(); + assert!(text.contains("/DeviceN [/Cyan /Gold]") || text.contains("/DeviceN[/Cyan/Gold]"), "{standard:?}: no DeviceN space of Cyan and Gold"); + assert!(text.contains("/Separation /Gold") || text.contains("/Separation/Gold"), "{standard:?}: Gold has no Separation colorant"); + assert!(text.contains("/C0 [0.3 0]") || text.contains("/C0[0.3 0]"), "{standard:?}: the first stop is cyan alone"); + assert!(text.contains("/C1 [0.3 1]") || text.contains("/C1[0.3 1]"), "{standard:?}: the last stop is cyan and Gold"); } } diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index 88d7216380..99afde0773 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -77,18 +77,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 +98,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/brush_fx.rs b/crates/render/src/brush_fx.rs index 52f045cbb9..f412d7249c 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -125,6 +125,16 @@ pub(crate) fn cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { Some(b.inflate(pad, pad)) } +/// [`cull_bounds`] of path or compound path `n` made from `visual`, its visual bounds, when the +/// renderer measures it by those ([`crate::fx::path_cull_bounds`]); else `None`. +pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnOnce() -> Option) -> Option> { + let b = crate::fx::path_cull_bounds(symbols, n, visual)?; + Some(b.map(|b| { + let pad = pad(symbols, n); + b.inflate(pad, pad) + })) +} + /// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art /// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it /// has a visible brushed stroke and of the objects in that art that have one diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 81b7198937..df71c6da97 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,6 +1,6 @@ use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; -use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, live}; +use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, kurbo, live}; /// Hasher for pointer-keyed caches: a multiply-xorshift (SipHash showed up in frame profiles). #[derive(Default, Clone, Copy)] @@ -30,23 +30,46 @@ pub(crate) type PtrMap = HashMap, pub(crate) outline: Arc, pub(crate) stamp: u64, pub(crate) crop: Option, + pub(crate) own: bool, } /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. pub(crate) type Slices = Arc>; -/// [`Slices`] cached for a stroke: (owning node, slices, last frame used). +/// The key of cached [`Slices`]: ([`Renderer::stroke_owner`] of the stroke's object, stroke layer +/// address, tolerance level). +pub(crate) type SliceKey = (usize, usize, i32); + +/// What the [`SliceKey`] of the latest slices of an object's stroke is found under once the object +/// has changed: (the object's id, the stroke's place in its appearance items, tolerance level). +pub(crate) type MovedSliceKey = (u64, usize, i32); + +/// [`Slices`] cached for a stroke: (owning node, the node whose path and stroke the slices were +/// made from, either the owning node or an earlier copy of it that the owning node is moved from, +/// the slices, the offset they are drawn moved by, the fill rule they were made with, whether they +/// were made along the path [`Node::stroke_path`] makes from that node, last frame used). pub(crate) struct SliceEntry { pub(crate) node: Arc, + pub(crate) made: Arc, pub(crate) slices: Slices, + pub(crate) by: kurbo::Vec2, + pub(crate) rule: FillRule, + pub(crate) own: bool, pub(crate) stamp: u64, } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c53e841cc..305ece3982 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -70,7 +70,7 @@ mod renderer; #[cfg(test)] pub(crate) use bounds::visual_bounds; -pub(crate) use bounds::{cull_bounds, drawn_outline, painted_reach}; +pub(crate) use bounds::{cull_bounds, drawn_outline, painted_reach, path_cull_bounds}; #[cfg(test)] pub(crate) use entries::Drawn; pub(crate) use entries::{DocInputs, FxGeom, Reads, ShadowEntry}; diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 725a62f92b..86f04ffa55 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -239,6 +239,23 @@ pub(crate) fn cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { cull_bounds_in(symbols, n, true) } +/// [`cull_bounds`] of path or compound path `n` made from `visual`, its visual bounds as +/// [`Node::visual_bounds_with`] measures them, when [`cull_bounds`] measures `n` by those (it has +/// no crop marks, Vector Halftone, container appearance or effects); else `None`. +pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnOnce() -> Option) -> Option> { + let plain = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && !effects::has_crop_marks(n) + && !effects::addons::halftone::has_halftone(n) + && !effects::has_container_appearance(n) + && !has_fx(n) + && !has_object_fx(n); + plain.then(|| { + let b = visual()?; + let a = live_content_reach(symbols, n); + Some(b.inflate(a, a)) + }) +} + /// [`cull_bounds`] of `n`. With `after_reshape` true, the effects in the art of a symbol instance /// with geometry effects of its own are measured on the art as those effects reshape it /// ([`reshaped_art_effects_reach`]). With `after_reshape` false, they are measured on the art diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index a49817cd06..8159673cae 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -70,7 +70,11 @@ impl Renderer { } let fits = full.area() <= PIXEL_BUDGET; // Device pixels from a pixel to the content deciding it (`None`: anywhere). - let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px)); + // De-Interlace's field lines and Color Halftone's pixels: the rows of the document's + // raster grid (1 to 2400 ppi). + let ppi = doc_raster_ppi(f.doc); + let line = 72.0 / ppi; + let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx, line).map(|d| m + d / f.px)); let linear = linear_key(f.view); let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); // Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a @@ -104,13 +108,14 @@ impl Renderer { Ink::Display | Ink::RichBlack if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk, _ => effects::pixel::Channels::Rgb, }; - // De-Interlace's field lines: the rows of the document's raster grid (1 to 2400 ppi). - let ppi = doc_raster_ppi(f.doc); // What the content reads (as the raster kept for it found it, else found now), with the - // channels the effects run on and, under De-Interlace or Rasterize, the resolution. + // channels the effects run on and, under De-Interlace, Color Halftone (its dots are sized + // in the grid's pixels) or Rasterize, the resolution. let inputs = key.map(|key| { let reads = self.pixel_fx.get(&key).filter(|e| e.node.is(content.node)).map_or_else(|| Reads::of(content.node), |e| e.inputs.reads); - let interlaced = chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }) | RasterFx::Rasterize(_))); + let interlaced = chain + .iter() + .any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. } | PixelFx::ColorHalftone { .. }) | RasterFx::Rasterize(_))); self.raster_inputs(f, content.node, reads).with((std::mem::discriminant(&channels), interlaced.then_some(ppi.to_bits()))) }); let interacting = f.opts.interacting; @@ -156,7 +161,6 @@ impl Renderer { let to_doc = view.inverse(); let px = f.px / k; let frame = Frame { mt: false, view, visible: to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), px, ..*f }; - let line = 72.0 / ppi; let (before, decoded) = (self.stats.moved, crate::paint::decode_failures()); let outer_image_left_out = self.image_left_out.replace(false); let pattern_images_left_out = crate::pattern::images_left_out(); @@ -644,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/raster.rs b/crates/render/src/fx/raster.rs index 70bbafec52..23f080daf4 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -70,12 +70,12 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool { matches!(chain.first(), Some(RasterFx::Rasterize(r)) if !r.anti_alias && r.cell(72.0) >= px) } -/// How far (document units) from a pixel the content deciding it after `fx` lies; `None` when -/// anywhere in the object. -pub(super) fn looks_around(fx: &RasterFx) -> Option { +/// How far (document units) from a pixel the content deciding it after `fx` lies, with the +/// document's raster grid lines `line` apart; `None` when anywhere in the object. +pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option { match fx { RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius), - RasterFx::Pixel(p) => p.reach(), + RasterFx::Pixel(p) => p.reach(line), RasterFx::Rasterize(r) => Some(r.reach()), _ => Some(0.0), } diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index a187be25e7..644325f4a3 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; @@ -375,23 +376,43 @@ 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 (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 (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 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 +} + /// Pixels `pm` colorized with `rgb`: each pixel takes the color, as opaque as the pixel is dark /// (255 less its Rec. 709 luma) times its alpha, so white pixels are transparent. pub(crate) fn colorized(pm: &Pixmap, [r, g, b]: [u8; 3]) -> Pixmap { diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index d4a5629e56..c4e1d0bb74 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -395,6 +395,16 @@ pub(crate) fn cmyk_pixmap(blob: &ImageBlob, lut: &InkLut) -> Option { inks_pixmap(&blob.cmyk()?, lut) } +/// 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 key.luts.0 == 0 || key.adjust.is_some() || key.grey { + 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 +442,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 +494,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 { diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs new file mode 100644 index 0000000000..293e824664 --- /dev/null +++ b/crates/render/src/kept_paths.rs @@ -0,0 +1,643 @@ +//! 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. +//! 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, 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 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. + start: usize, + /// Its segments (as [`SubPath::segment_count`] counts them). + segs: usize, + anchors: usize, + closed: bool, + /// 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>, +} + +/// The path of a long path or compound path ([`Node::stroke_path`]), with its geometric bounds by +/// runs of segments and the tips of a miter-joined stroke along it by runs of joints. +pub(crate) struct KeptPath { + /// The object the path was made from (kept alive). + pub(crate) node: Arc, + pub(crate) path: Arc, + /// The subpaths of each path of the object: the path itself, or each member of a compound path. + parts: Vec>, + /// The stroke the subpaths' tips were measured for. + tips_of: Option, + /// The last frame that used it. + pub(crate) stamp: u64, +} + +/// The paths of `n`: its own, or those of the members of a compound path whose members are all +/// paths and that is not a Shaper group or an Image Trace object. `None` for anything else. +fn paths(n: &Node) -> Option> { + match &n.kind { + NodeKind::Path { path, .. } => Some(vec![path]), + NodeKind::Compound { children, .. } if n.extras().shaper.is_none() && n.extras().trace.is_none() => { + children.iter().map(|c| c.path_data()).collect() + } + _ => None, + } +} + +/// Whether `n` has a path that is kept ([`KeptPath`]): a path or compound path with at least +/// [`KEPT_ANCHORS`] anchors, none of whose closed subpaths starts at a point that is not a number +/// (its path closes with an extra segment there). +pub(crate) fn kept(n: &Node) -> bool { + let Some(paths) = paths(n) else { return false }; + let subs = || paths.iter().flat_map(|p| &p.subpaths); + subs().map(|s| s.anchors.len()).sum::() >= KEPT_ANCHORS + && subs().filter(|s| s.closed).all(|s| s.anchors.first().is_none_or(|a| !a.p.x.is_nan() && !a.p.y.is_nan())) +} + +/// Whether anchors `a` and `b` have the same points, bit for bit. +fn same(a: &Anchor, b: &Anchor) -> bool { + 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. +fn element(sp: &SubPath, i: usize) -> PathEl { + let c = sp.segment(i); + 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 { + 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)?)?; + Some(match *els.get(self.start + 1 + i)? { + PathEl::LineTo(p) => PathSeg::Line(vectorcraft_geom::Line::new(p0, p)), + PathEl::QuadTo(a, p) => PathSeg::Quad(vectorcraft_geom::kurbo::QuadBez::new(p0, a, p)), + PathEl::CurveTo(a, b, p) => PathSeg::Cubic(vectorcraft_geom::CubicBez::new(p0, a, b, p)), + PathEl::MoveTo(_) | PathEl::ClosePath => return None, + }) + } + + fn runs(&self) -> usize { + 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 { + 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 + /// `None` when there is none other than `i`. + fn next_drawn(&self, els: &[PathEl], i: usize) -> Option { + let after = i + 1..self.segs; + let round = if self.closed { 0..i } else { 0..0 }; + after.chain(round).filter_map(|j| self.seg(els, j)).find(has_length) + } + + /// The segment with length before segment `i` (round from the end when closed), when it is + /// within [`RUN`] segments of `i`: `Ok(None)` when there is none, `Err(())` when the search + /// gave up. + fn prev_drawn(&self, els: &[PathEl], i: usize) -> Result, ()> { + let before = (0..i).rev(); + let round = if self.closed { (i + 1..self.segs).rev() } else { (0..0).rev() }; + for (steps, j) in before.chain(round).enumerate() { + if steps >= RUN { + return Err(()); + } + if self.seg(els, j).is_some_and(|s| has_length(&s)) { + return Ok(Some(j)); + } + } + Ok(None) + } + + /// The box of the miter tips of `st` at the joints whose first segment is in run `r` + /// ([`StrokeLayer::miter_tip`]). + fn run_tips(&self, els: &[PathEl], r: usize, st: &StrokeLayer) -> Option { + let mut out: Option = None; + 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) { + out = Some(out.map_or(Rect::from_points(tip, tip), |o| o.union_pt(tip))); + } + } + 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 +/// its miter limit. +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 { + if !kept(n) { + return None; + } + let path = n.stroke_path()?; + let els = path.elements(); + let mut start = 0; + let mut parts = vec![]; + for pd in paths(n)? { + let mut subs = vec![]; + for sp in &pd.subpaths { + let sub = Sub::measured(sp, start, els, None); + start += sub.len(); + subs.push(sub); + } + parts.push(subs); + } + (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 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 }; + if !kept(n) || self.parts.len() != was.len() || self.parts.iter().zip(&was).any(|(s, p)| s.len() != p.subpaths.len()) { + return false; + } + // 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(); + // 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 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; + } + 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); + } + 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)); + } + 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 + /// [`PathData::bounds`] measures it, joined. + pub(crate) fn geometric(&self) -> Option { + let els = self.path.elements(); + self.parts.iter().fold(None, |acc, subs| { + let anchors: usize = subs.iter().map(|s| s.anchors).sum(); + let b = match anchors { + 0 => None, + // One anchor: the point itself. + 1 => subs.iter().find(|s| s.anchors == 1).and_then(|s| els.get(s.start)).and_then(end).map(|p| Rect::from_points(p, p)), + _ => Some(subs.iter().flat_map(|s| s.boxes.iter().flatten()).copied().reduce(|a, b| a.union(b)).unwrap_or_default()), + }; + vectorcraft_geom::union_opt(acc, b) + }) + } + + /// The box of the miter tips of `st` at every joint of the path ([`StrokeLayer::miter_tip`]), + /// for [`StrokeLayer::bounds_with_tips`]: measured whole when the tips kept are another + /// stroke's, then kept up to date with the path. + pub(crate) fn tips(&mut self, st: &StrokeLayer) -> Option { + if st.join != LineJoin::Miter { + return None; + } + if self.tips_of.as_ref().is_none_or(|t| t.join != LineJoin::Miter || tips_key(t) != tips_key(st)) { + let els = self.path.elements(); + for sub in self.parts.iter_mut().flatten() { + sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); + } + self.tips_of = Some(st.clone()); + } + self.parts.iter().flatten().flat_map(|s| s.tips.iter().flatten()).copied().reduce(|a, b| a.union(b)) + } + + /// Each subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each + /// of its runs. + #[cfg(test)] + 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 8bf6b0d232..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; @@ -60,6 +61,9 @@ pub struct Renderer { /// Worker threads for the multithreaded rasterizer (0 = single-threaded). pub threads: u16, geom: PtrMap, + /// The paths of long paths and compound paths, by object id (see [`Self::kept_path`]): after + /// an edit, `geom` makes the new object's path and bounds from the path kept for its id. + kept: PtrMap, /// The symbols (name and art) of the document last drawn, which `geom`'s bounds measured /// symbol instances by (see [`Self::check_symbols`]). The art is held weakly: the reference /// keeps the art's allocation, so no other art can get its address, and does not keep the @@ -71,6 +75,9 @@ pub struct Renderer { /// Expanded stroke outlines keyed by ([`Self::stroke_owner`], stroke layer address, width bits, /// tolerance level): panning re-renders reuse them instead of re-expanding every stroke. strokes: PtrMap, + /// The key in `strokes` of the latest outline of each stroke of an object, under its + /// [`frame::MovedKey`]: a moved copy of the object draws that outline moved ([`Self::moved_outline`]). + moved_strokes: PtrMap, /// Expanded character stroke outlines, with the glyph geometry kept in `texts` they belong to, /// keyed by ([`Self::stroke_owner`] of that geometry, run, width bits, tolerance level): type /// that doesn't change draws them again instead of expanding its strokes in every frame. Within @@ -162,7 +169,11 @@ pub struct Renderer { clip_paints: FrameCache, /// Gradients along or across strokes (see [`Self::fill_path_gradient`]), keyed by /// ([`Self::stroke_owner`], stroke layer address, tolerance level). - stroke_slices: PtrMap<(usize, usize, i32), SliceEntry>, + stroke_slices: PtrMap, + /// The key in `stroke_slices` of the latest slices of each stroke of an object, under its + /// [`frame::MovedSliceKey`]: a moved copy of the object draws those slices moved + /// ([`Self::moved_slices`]). + moved_slices: PtrMap, /// What the image keys colour adjustments give their recoloured images name: the image /// recoloured and the adjustment, with its hash (see [`Self::adjusted_image`]). adjusts: HashMap, @@ -203,6 +214,7 @@ mod bounds; mod clock; mod frame; mod geometry; +mod kept_paths; mod node_checks; mod options; mod renderer; 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.rs b/crates/render/src/renderer.rs index 1e07075e71..2f69551c11 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -18,6 +18,9 @@ use super::{ group, ink, kurbo, live, lru, peniko, proof, vello_cpu, }; +#[cfg(test)] +pub(crate) use paint::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; + mod images; mod nodes; mod paint; @@ -34,9 +37,11 @@ impl Renderer { clips: FrameCache::new(lru::CLIP_BUDGET, 256), threads: default_threads(), geom: PtrMap::default(), + kept: PtrMap::default(), symbols: vec![], plugin_revision: 0, strokes: PtrMap::default(), + moved_strokes: PtrMap::default(), char_strokes: FrameCache::new(lru::CHAR_STROKE_BUDGET, 0), cur: None, made_again: false, @@ -71,6 +76,7 @@ impl Renderer { twice_drawn: 0, clip_paints: FrameCache::new(lru::CLIP_BUDGET, 256), stroke_slices: PtrMap::default(), + moved_slices: PtrMap::default(), adjusts: HashMap::new(), dim_images: None, inline_depth: 0, @@ -180,11 +186,18 @@ impl Renderer { // them, a drag left up to that many old copies of the object alive, each with all its // members (and, for a compound path, its assembled path). self.geom.retain(|_, e| g - e.stamp <= 3); + // A kept path stays while its object is in `geom`, which keeps the objects still drawn. + let geom = &self.geom; + self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node))); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); + let strokes = &self.strokes; + self.moved_strokes.retain(|_, k| strokes.contains_key(k)); } if self.stroke_slices.len() > 256 { self.stroke_slices.retain(|_, e| g - e.stamp <= 3); + let slices = &self.stroke_slices; + self.moved_slices.retain(|_, k| slices.contains_key(k)); } if self.shadows.len() > 256 { self.shadows.retain(|_, e| g - e.stamp <= 3); diff --git a/crates/render/src/renderer/images.rs b/crates/render/src/renderer/images.rs index 6cabfc5bfc..0f22fbae39 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)) } @@ -70,18 +76,21 @@ impl Renderer { Some(pm) } else { self.image_pixmap(f.doc, &im.key, im.pixels.as_deref(), outline, !mips).map(|(key, 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); let (key, pm) = match tint { - Some(rgb) => colorized_pixmap(key, &pm, rgb, !mips), + 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`). - 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 } + let (key, pm) = if outline || tint.is_some() { (key, pm) } else { ink::ink_image(&key, &pm, f.ink, blob, true) }; + match f.plates.filter(|_| !outline && tint.is_none()) { + Some(lut) => proof::plate_image(lut, &key, &pm, blob, true).1, + None => pm, + } }) }; if let Some(pm) = shown { @@ -314,10 +323,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 79455cd75b..176739c31b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -4,6 +4,7 @@ use super::{ holds_instance, holds_plugin_effect, images, kurbo, lru, mask_value, painted_items, plain_image, polygon_length, rects_overlap, shape_masked_image, single_plain_fill, text_geom_snapped, white_shape_mask, }; +use crate::kept_paths::{self, KeptPath}; impl Renderer { /// Cached cull bounds of a node (containers union their cached children), symbol instances @@ -28,12 +29,56 @@ impl Renderer { } acc } - _ => brush_fx::cull_bounds(symbols, a), + _ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)), }; self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp }); b } + /// The kept path of long path or compound path `a` ([`KeptPath`]), made, or brought up to date + /// from the one kept for its id, when it is not `a`'s yet. `None` when `a` has none. + fn kept_path(&mut self, a: &Arc) -> Option<&mut KeptPath> { + if !kept_paths::kept(a) { + return None; + } + let stamp = self.stamp; + let made = match self.kept.get_mut(&a.id) { + Some(k) if Arc::ptr_eq(&k.node, a) => true, + Some(k) => { + // The object the path was made from, when no longer drawn, shares the path through + // its `geom` entry: dropping that entry lets the path change in place. + let old = Arc::as_ptr(&k.node) as usize; + if self.geom.get(&old).is_some_and(|e| Arc::ptr_eq(&e.node, &k.node) && e.stamp != stamp) { + self.geom.remove(&old); + } + k.update(a) + } + None => false, + }; + if !made { + let k = KeptPath::new(a, stamp)?; + self.kept.insert(a.id, k); + } + let k = self.kept.get_mut(&a.id)?; + k.stamp = stamp; + Some(k) + } + + /// Cull bounds of long path or compound path `a` measured from its kept path + /// ([`Self::kept_path`]): the same as [`brush_fx::cull_bounds`]. `None` when it has no kept path + /// or is measured another way ([`brush_fx::path_cull_bounds`]). + fn kept_bounds(&mut self, symbols: &SymbolBoxes, a: &Arc) -> Option> { + let k = self.kept_path(a)?; + brush_fx::path_cull_bounds(symbols, a, || { + let b = k.geometric()?; + let bp = k.path.clone(); + Some(a.appearance.stroked_bounds_by(b, |s| { + let tips = k.tips(s); + s.bounds_with_tips(&bp, b, tips) + })) + }) + } + /// Drop the cached bounds of symbol instances and of the objects that hold them when `doc`'s /// symbols are not those of the document last drawn (by name and art): those bounds measured /// the instances by their symbol's art. @@ -105,7 +150,10 @@ impl Renderer { { return Some(p.clone()); } - let p = Arc::new(a.stroke_path()?); + let p = match self.kept_path(a) { + Some(k) => k.path.clone(), + None => Arc::new(a.stroke_path()?), + }; let bounds = self.bounds_of(symbols, a); self.geom.insert(key, GeomEntry { node: a.clone(), bounds, path: Some(p.clone()), stamp: self.stamp }); Some(p) @@ -170,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; } @@ -438,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; } @@ -488,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 00d9153c1b..ae65cf8456 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -3,6 +3,7 @@ use super::{ Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, peniko, rects_overlap, }; +use crate::frame::{MovedKey, MovedSliceKey, StrokeKey}; use crate::paint; impl Renderer { @@ -133,9 +134,9 @@ impl Renderer { } else if paint::set_paint(ctx, &st.paint, paint_bounds, f) { self.fold_alpha(ctx, f.ink, &st.paint); ctx.set_fill_rule(peniko::Fill::NonZero); - match self.cached_stroke(f, chars, &pieces.line, st, width) { + 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); @@ -163,7 +164,9 @@ impl Renderer { /// Paint the line and arrowheads (`pieces`) of stroke `st` of `bp` (filled with `rule`) with /// its gradient `g` laid along or across the path ([`effects::stroke::gradient_slices`]). Each /// piece clips the slices, grown a pixel into each other and each replacing what it covers, so - /// neighbours meet without seams and translucent colours paint once. + /// neighbours meet without seams and translucent colours paint once. The slices of a stroke + /// of `self.cur` are kept in `stroke_slices`, and a moved copy of the object draws the slices + /// made before it moved, moved by the same offset ([`Self::moved_slices`]). #[allow(clippy::too_many_arguments)] fn fill_path_gradient( &mut self, @@ -179,6 +182,8 @@ impl Renderer { ) { let level = (f.px * 0.25).log2().floor() as i32; let make = || -> Slices { + #[cfg(test)] + SLICES_MADE.with(|n| n.set(n.get() + 1)); let tol = 2f64.powi(level); // Reach a pixel past the stroke, so its antialiased edge has colour under it. let slices = effects::stroke::gradient_slices(bp, rule, st, tol, f.px + tol, f.px); @@ -192,26 +197,41 @@ impl Renderer { .collect(), ) }; - let slices = match self.cur.clone().filter(|n| owns_stroke(n, st)) { + let (slices, by) = match self.cur.clone().filter(|n| owns_stroke(n, st)) { Some(node) => { let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, level); match self.stroke_slices.get_mut(&key) { Some(e) if Arc::ptr_eq(&e.node, &node) => { e.stamp = self.stamp; - e.slices.clone() + (e.slices.clone(), e.by) } _ => { - let slices = make(); - self.stroke_slices.insert(key, SliceEntry { node, slices: slices.clone(), stamp: self.stamp }); - slices + // Under its object's id, the stroke's place and the tolerance level, the key + // of the stroke's latest slices is kept, except for art made again in every + // frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, level)); + let kept = moved.and_then(|mk| self.moved_slices(mk, &node, st, rule, bp)); + let (made, slices, by, own) = match kept { + Some((made, slices, by)) => (made, slices, by, true), + None => { + let own = moved.is_some() && self.own_path(&node, bp); + (node.clone(), make(), kurbo::Vec2::ZERO, own) + } + }; + self.stroke_slices.insert(key, SliceEntry { node, made, slices: slices.clone(), by, rule, own, stamp: self.stamp }); + if let Some(mk) = moved { + self.moved_slices.insert(mk, key); + } + (slices, by) } } } - None => make(), + None => (make(), kurbo::Vec2::ZERO), }; - let line = match self.cached_stroke(f, chars, &pieces.line, st, width) { + 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)) { @@ -222,8 +242,18 @@ impl Renderer { ctx.push_clip_layer(clip); ctx.set_blend_mode(BlendMode::new(Mix::Normal, Compose::Copy)); for (shape, paint, b) in slices.iter() { - if rects_overlap(*b, cb) && paint::set_paint(ctx, paint, *b, f) { - ctx.fill_path(shape); + let b = *b + by; + if !rects_overlap(b, cb) { + continue; + } + if by == kurbo::Vec2::ZERO { + if paint::set_paint(ctx, paint, b, f) { + ctx.fill_path(shape); + } + } else if paint::set_paint(ctx, &moved_paint(paint, by), b, f) { + let mut shape = shape.clone(); + shape.apply_affine(Affine::translate(by)); + ctx.fill_path(&shape); } } ctx.set_blend_mode(BlendMode::default()); @@ -236,17 +266,18 @@ impl Renderer { /// stroke of `self.cur` in `strokes` (under [`Self::stroke_owner`] and the stroke layer). The /// tolerance (vello's 0.25 device px) is bucketed to powers of two, never coarser than needed, /// so zooming reuses outlines until the level changes. Other strokes aren't cached: for them - /// this returns `None`. + /// this returns `None`. `line` is the line of `st` along `path` ([`effects::stroke::stroke_pieces`]). fn cached_stroke( &mut self, f: &Frame, chars: Option<(&Arc, usize)>, + path: &BezPath, line: &BezPath, st: &StrokeLayer, 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) @@ -269,21 +300,142 @@ impl Renderer { e.stamp = self.stamp; return Some(e.outline.clone()); } - // A long stroke without dashes or a width profile is outlined only in and around the view, - // with a margin of the view's own size on each side ([`crop_line`]). + // Under its object's id, the stroke's place and the outline's width and tolerance, the key + // of the stroke's latest outline is kept, except for art made again in every frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level)); + let own = moved.is_some() && self.own_path(&node, path); + if let Some(mk) = moved + && let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v) + { + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); + return Some(outline); + } + #[cfg(test)] + STROKES_OUTLINED.with(|n| n.set(n.get() + 1)); + // A long stroke without a width profile is outlined only in and around the view, with a + // margin of the view's own size on each side ([`crop_dashed`] for a dashed one, + // [`crop_line`] otherwise). let region = v.inflate(v.width(), v.height()); let tol = 2f64.powi(level); + if crops() + && line.elements().len() > CROP_ELEMENTS + && st.dash.is_some() + && st.profile.is_none() + && let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol) + { + let outline = Arc::new(outline); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved); + return Some(outline); + } let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) .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.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop }); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); Some(outline) } + /// Whether `path` is the path that `geom` keeps for `node` ([`Self::path_of`]), the path + /// [`Node::stroke_path`] makes from its anchors. + fn own_path(&self, node: &Arc, path: &BezPath) -> bool { + self.geom + .get(&(Arc::as_ptr(node) as usize)) + .is_some_and(|g| Arc::ptr_eq(&g.node, node) && g.path.as_deref().is_some_and(|p| std::ptr::eq(p, path))) + } + + /// Keeps outline `e` in `strokes` under `key`, and lists `key` as the latest outline under + /// `moved` ([`MovedKey`]). + fn keep_stroke(&mut self, key: StrokeKey, e: StrokeEntry, moved: Option) { + self.strokes.insert(key, e); + if let Some(mk) = moved { + self.moved_strokes.insert(mk, key); + } + } + + /// The outline of stroke `st` of `node` along `line`, made from the latest outline kept under + /// `mk` ([`MovedKey`]) when that outline was made along a line of its object's own path, its + /// object is `node` changed, its stroke differs from `st` in its paint at most, and its line is + /// `line` moved (to within rounding): that outline moved by the same offset, with the region it + /// was cropped to moved too. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier line is made again from its object and stroke only when + /// they match. `None` when there is no such outline, or when its region does not hold the view + /// `v`. + fn moved_outline(&self, mk: MovedKey, node: &Node, st: &StrokeLayer, line: &BezPath, v: Rect) -> Option<(Arc, Option)> { + let e = self.strokes.get(self.moved_strokes.get(&mk)?)?; + if !e.own || e.node.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.node.appearance.items.get(mk.1) else { + return None; + }; + let unpainted = |s: &StrokeLayer| StrokeLayer { paint: vectorcraft_color::Paint::None, ..s.clone() }; + if !std::ptr::eq(old, st) && unpainted(old) != unpainted(st) { + return None; + } + if !anchors_moved(&e.node, node) { + return None; + } + let path = e.node.stroke_path()?; + let by = offset_between(&effects::stroke::stroke_pieces(&path, old).line, line)?; + let crop = e.crop.map(|r| r + by); + if crop.is_some_and(|r| r.x0 > v.x0 || r.y0 > v.y0 || r.x1 < v.x1 || r.y1 < v.y1) { + return None; + } + if by == kurbo::Vec2::ZERO { + return Some((e.outline.clone(), crop)); + } + let mut outline = (*e.outline).clone(); + outline.apply_affine(Affine::translate(by)); + Some((Arc::new(outline), crop)) + } + + /// The slices of stroke `st` of `node` along `bp` (filled with `rule`), made from the latest + /// slices kept under `mk` ([`MovedSliceKey`]) when those were made along their object's own + /// path, their object is `node` changed, its stroke there differs from `st` at most in where + /// its gradient is placed, its fill rule is `rule`, and `bp` is its path moved (to within + /// rounding): the node they were made from, those slices, and the offset from that node to + /// `bp`, which the slices are drawn moved by. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier path is made again from its object only when they + /// match. `None` when there are no such slices. + fn moved_slices( + &self, + mk: MovedSliceKey, + node: &Node, + st: &StrokeLayer, + rule: FillRule, + bp: &BezPath, + ) -> Option<(Arc, Slices, kurbo::Vec2)> { + let e = self.stroke_slices.get(self.moved_slices.get(&mk)?)?; + if !e.own || e.rule != rule || e.made.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.made.appearance.items.get(mk.1) else { + return None; + }; + // The slices take only the gradient's stops and kind, not where it is placed, which a move + // moves too. + let unplaced = |s: &StrokeLayer| { + let mut s = s.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut s.paint { + g.geom = None; + g.angle = 0.0; + } + s + }; + if !std::ptr::eq(old, st) && unplaced(old) != unplaced(st) { + return None; + } + if !anchors_moved(&e.made, node) { + return None; + } + let by = offset_between(&e.made.stroke_path()?, bp)?; + Some((e.made.clone(), e.slices.clone(), by)) + } + /// What the `strokes`, `char_strokes` and `stroke_slices` keys hold for a stroke owner at /// `address` (`self.cur` or kept glyph geometry): the address, or 0 while art made again in /// every frame is drawn ([`Self::made_again`]). @@ -300,6 +452,121 @@ pub(crate) const CROP_ELEMENTS: usize = 1024; thread_local! { /// Whether long strokes are outlined near the view only on this thread ([`crop_line`]). pub(crate) static CROP_STROKES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// How many stroke outlines of nodes [`Renderer::cached_stroke`] has made on this thread. + pub(crate) static STROKES_OUTLINED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many sets of gradient stroke slices [`Renderer::fill_path_gradient`] has made on this + /// thread. + pub(crate) static SLICES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Paint `p` of a slice ([`Slices`]) moved by `by`: a gradient's start, end and focal point moved. +fn moved_paint(p: &vectorcraft_color::Paint, by: kurbo::Vec2) -> vectorcraft_color::Paint { + let mut p = p.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut p + && let Some(geom) = &mut g.geom + { + geom.start += by; + geom.end += by; + if let Some(focal) = &mut geom.focal { + *focal += by; + } + } + p +} + +/// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each point within +/// the rounding that [`Offset::holds`] allows). `None` otherwise, and for an empty path. +pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option { + if !matches!(was.elements().first(), Some(kurbo::PathEl::MoveTo(_))) { + return None; + } + let mut offset = Offset::new(); + (path_pairs(was, now, |a, b| offset.takes(a, b)) && path_pairs(was, now, |a, b| offset.holds(a, b))).then(|| offset.by()) +} + +/// Whether `was` and `now` have the same elements, and `f` holds for each pair of their points. +/// Stops at the first pair for which `f` does not hold. +fn path_pairs(was: &BezPath, now: &BezPath, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + use kurbo::PathEl; + let (was, now) = (was.elements(), now.elements()); + was.len() == now.len() + && was.iter().zip(now).all(|pair| match pair { + (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => f(*a, *b), + (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => f(*a0, *b0) && f(*a1, *b1), + (PathEl::CurveTo(a0, a1, a2), PathEl::CurveTo(b0, b1, b2)) => f(*a0, *b0) && f(*a1, *b1) && f(*a2, *b2), + (PathEl::ClosePath, PathEl::ClosePath) => true, + _ => false, + }) +} + +/// One offset between pairs of points. Pairs are read once with [`Offset::takes`], which measures +/// the offset on each axis at the pair with the smallest coordinates on that axis, and once more +/// with [`Offset::holds`], which checks every pair against that offset. +struct Offset { + by: [f64; 2], + size: [f64; 2], +} + +impl Offset { + fn new() -> Self { + Self { by: [0.0; 2], size: [f64::INFINITY; 2] } + } + + /// Whether `b` is `a` moved by the offset measured so far, on each axis within 3 units in the + /// last place of the larger of the pair's coordinates and those of the pair the offset was + /// measured at. A pair with smaller coordinates than any before it on an axis then measures the + /// offset on that axis. + fn takes(&mut self, a: kurbo::Point, b: kurbo::Point) -> bool { + [(a.x, b.x), (a.y, b.y)].into_iter().zip(self.by.iter_mut().zip(&mut self.size)).all(|((a, b), (by, size))| { + let at = a.abs().max(b.abs()); + if at.is_nan() || at >= *size { + return (b - a - *by).abs() <= 3.0 * ulp(at); + } + let near = size.is_infinite() || (b - a - *by).abs() <= 3.0 * ulp(*size); + (*by, *size) = (b - a, at); + near && by.is_finite() + }) + } + + /// Whether `b` is `a` moved by the offset, on each axis within 3 units in the last place of the + /// larger of the pair's coordinates: the most that rounding `b`, the pair the offset was measured + /// at (whose coordinates are no larger), and the two offsets can make together. + fn holds(&self, a: kurbo::Point, b: kurbo::Point) -> bool { + let near = |a: f64, b: f64, by: f64| (b - a - by).abs() <= 3.0 * ulp(a.abs().max(b.abs())); + near(a.x, b.x, self.by[0]) && near(a.y, b.y, self.by[1]) + } + + fn by(&self) -> kurbo::Vec2 { + kurbo::Vec2::new(self.by[0], self.by[1]) + } +} + +/// The distance from `x`, which is 0 or more, to the next larger `f64`. +fn ulp(x: f64) -> f64 { + f64::from_bits(x.to_bits() + 1) - x +} + +/// Whether the anchors and handles of path `now` are those of path `was` moved by one offset, +/// measured as [`offset_between`] measures it, with the same subpaths, anchor counts and closed +/// subpaths. It reads the anchors without making either path ([`Node::stroke_path`]), and stops at +/// the first anchor that differs. `false` for objects other than paths. +pub(crate) fn anchors_moved(was: &Node, now: &Node) -> bool { + let (vectorcraft_doc::NodeKind::Path { path: was, .. }, vectorcraft_doc::NodeKind::Path { path: now, .. }) = (&was.kind, &now.kind) else { + return false; + }; + let mut offset = Offset::new(); + anchor_pairs(was, now, |a, b| offset.takes(a, b)) && anchor_pairs(was, now, |a, b| offset.holds(a, b)) +} + +/// Whether `was` and `now` have the same subpaths, anchor counts and closed subpaths, and `f` holds +/// for each pair of their anchors and handles. Stops at the first pair for which `f` does not hold. +fn anchor_pairs(was: &vectorcraft_geom::PathData, now: &vectorcraft_geom::PathData, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + was.subpaths.len() == now.subpaths.len() + && was.subpaths.iter().zip(&now.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(a, b)| f(a.p, b.p) && f(a.h_in, b.h_in) && f(a.h_out, b.h_out)) + }) } fn crops() -> bool { @@ -316,6 +583,38 @@ pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 width / 2.0 * corner + 2.0 * px + tol } +/// Whether the box of segment `s`'s control points meets `near`. A coordinate that is not a number +/// counts as near. +fn is_near(s: &kurbo::PathSeg, near: Rect) -> bool { + use kurbo::PathSeg; + let pts: &[kurbo::Point] = match s { + PathSeg::Line(l) => &[l.p0, l.p1], + PathSeg::Quad(q) => &[q.p0, q.p1, q.p2], + PathSeg::Cubic(c) => &[c.p0, c.p1, c.p2, c.p3], + }; + !(pts.iter().all(|p| p.x < near.x0) + || pts.iter().all(|p| p.x > near.x1) + || pts.iter().all(|p| p.y < near.y0) + || pts.iter().all(|p| p.y > near.y1)) +} + +/// The outline of the line `line` of dashed stroke `st` (without a width profile) at `width`, +/// flattened to `tol`, made from the segments within `reach` of `region` only, for drawing in +/// `region`. The dashes and dots on those segments sit where the whole line puts them +/// ([`effects::stroke::dash_kept`]); a pattern that draws the stroke solid is outlined as a solid +/// line along [`crop_line`]. `None` when every segment is kept. +fn crop_dashed(line: &BezPath, st: &StrokeLayer, width: f64, region: Rect, reach: f64, tol: f64) -> Option { + let near = region.inflate(reach, reach); + if kurbo::segments(line.elements().iter().copied()).all(|s| is_near(&s, near)) { + return None; + } + if let Some(outline) = effects::stroke::dashed_line_outline_kept(line, st, width, tol, &|s| is_near(s, near)) { + return Some(outline); + } + let solid = StrokeLayer { dash: None, ..st.clone() }; + crop_line(line, region, reach, width).map(|part| effects::stroke::line_outline(&part, &solid, width, tol)) +} + /// The stroke line `line` without the segments whose control points' box lies more than `reach` /// from `region`, for outlining a stroke of `width` that is drawn only in `region`. A subpath that /// loses some of its segments is replaced by its runs of kept segments, each an open subpath; a @@ -326,18 +625,7 @@ pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 pub(crate) fn crop_line(line: &BezPath, region: Rect, reach: f64, width: f64) -> Option { use kurbo::{PathEl, PathSeg}; let near = region.inflate(reach, reach); - let keep = |s: &PathSeg| { - let pts: &[kurbo::Point] = match s { - PathSeg::Line(l) => &[l.p0, l.p1], - PathSeg::Quad(q) => &[q.p0, q.p1, q.p2], - PathSeg::Cubic(c) => &[c.p0, c.p1, c.p2, c.p3], - }; - // A coordinate that is not a number keeps the segment. - !(pts.iter().all(|p| p.x < near.x0) - || pts.iter().all(|p| p.x > near.x1) - || pts.iter().all(|p| p.y < near.y0) - || pts.iter().all(|p| p.y > near.y1)) - }; + let keep = |s: &PathSeg| is_near(s, near); let els = line.elements(); let mut starts: Vec = els.iter().enumerate().filter(|(_, e)| matches!(e, PathEl::MoveTo(_))).map(|(i, _)| i).collect(); if starts.first() != Some(&0) { 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 c82daf32d9..82a1374dab 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -19,15 +19,18 @@ pub(super) mod fontchange; mod freeform; mod fxzoom; mod isolation; +mod keptpath; mod knockout; mod layeropts; mod longstroke; mod memory; +mod movedstroke; mod objectfx; 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 new file mode 100644 index 0000000000..a2f8b3ad85 --- /dev/null +++ b/crates/render/src/tests/keptpath.rs @@ -0,0 +1,580 @@ +//! The paths of long paths and compound paths are kept by object id (`kept_paths`): after an edit, +//! the renderer changes only the parts of the path that the edit moved, and draws and culls the +//! object as a renderer that makes its path again does. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath, Vec2}; + +use crate::*; + +const SIZE: u32 = 120; + +fn stroke(width: f64, join: LineJoin, cap: LineCap) -> StrokeLayer { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + st.join = join; + st.cap = cap; + st.miter_limit = 10.0; + st +} + +/// `n` anchors 8 pt apart from x = `x0`, up and down by 30 pt: sharp corners, every fifth anchor +/// smooth, and every 50th anchor doubled (a segment without length). +fn zigzag(n: usize, x0: f64) -> SubPath { + let mut anchors = vec![]; + for i in 0..n { + let p = Point::new(x0 + i as f64 * 8.0, if i % 2 == 0 { 0.0 } else { 30.0 }); + anchors.push(if i % 5 == 0 { Anchor::smooth(p, p + Vec2::new(3.0, 4.0)) } else { Anchor::corner(p) }); + if i % 50 == 25 { + anchors.push(Anchor::corner(p)); + } + } + SubPath::new(anchors, false) +} + +/// A closed polygon of `n` anchors round a circle of radius `r` about `c`. +fn ring(n: usize, c: Point, r: f64) -> SubPath { + let points: Vec = (0..n).map(|i| c + Vec2::from_angle(i as f64 / n as f64 * std::f64::consts::TAU) * r).collect(); + SubPath::polyline(&points, true) +} + +/// `d` with `n` added to its first layer, and `n`'s id. +fn add(d: &mut Document, n: Node) -> NodeId { + let (id, l) = (n.id, d.layers[0].id); + d.insert(Some(l), 0, n).unwrap(); + id +} + +fn look(items: Vec) -> Appearance { + Appearance { items: items.into_iter().map(AppearanceItem::Stroke).collect(), ..Default::default() } +} + +/// The view with (12,000, 15) in the middle of the frame. +fn view() -> Affine { + Affine::translate((f64::from(SIZE) / 2.0 - 12_000.0, f64::from(SIZE) / 2.0 - 15.0)) +} + +fn render(r: &mut Renderer, d: &Document) -> Rendered { + r.render(d, SIZE, SIZE, view(), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// Draw `d` with `r` and check what `r` drew and kept for object `id` against what a new renderer +/// draws and what the object measures without kept paths. +fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { + let img = render(r, d); + assert!(img.pixels == render(&mut Renderer::new(), d).pixels, "{what}: the same pixels as a new renderer"); + let n = d.node(id).unwrap(); + let e = r.geom.get(&(n as *const Node as usize)).unwrap_or_else(|| panic!("{what}: measured")); + assert_eq!(e.bounds, crate::brush_fx::cull_bounds(&d.symbol_boxes(), n), "{what}: the same cull bounds"); + if let Some(p) = &e.path { + assert!(**p == n.stroke_path().unwrap(), "{what}: the same path"); + } + 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 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"), + } +} + +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)); +} + +#[test] +fn a_long_path_draws_and_culls_after_each_edit_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), + SubPath::new(vec![Anchor::corner(Point::new(50.0, 200.0))], false), + SubPath::new(vec![], false), + ring(200, Point::new(12_000.0, 3000.0), 100.0), + ]); + 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"); + let first = d.clone(); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 12] = [ + ("one anchor moved", |p| moved(&mut p.subpaths[0].anchors[1530], Vec2::new(0.0, 40.0))), + ("a handle moved", |p| { + let a = &mut p.subpaths[0].anchors[1532]; + a.h_out = a.p + Vec2::new(10.0, -20.0); + }), + ("an anchor moved onto the one before it", |p| { + let at = p.subpaths[0].anchors[1534].p; + p.subpaths[0].anchors[1535] = Anchor::corner(at); + }), + ("that anchor moved off it", |p| moved(&mut p.subpaths[0].anchors[1535], Vec2::new(5.0, 5.0))), + ("a doubled anchor moved off its twin", |p| moved(&mut p.subpaths[0].anchors[1536], Vec2::new(0.0, -12.0))), + ("1,200 anchors moved", |p| p.subpaths[0].anchors[..1200].iter_mut().for_each(|a| moved(a, Vec2::new(2.0, 1.0)))), + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ("the first anchor of the closed subpath moved", |p| moved(&mut p.subpaths[0].anchors[0], Vec2::new(0.0, -60.0))), + ("the subpath opened", |p| p.subpaths[0].closed = false), + ("an anchor of another subpath moved into the view", |p| p.subpaths[3].anchors[50] = Anchor::corner(Point::new(11_990.0, 20.0))), + ]; + for (what, edit) in edits { + edit(path_of(&mut d, id)); + check(&mut r, &d, id, what); + } + check(&mut r, &first, id, "undone to the start"); + moved(&mut path_of(&mut d, id).subpaths[1].anchors[0], Vec2::new(5.0, 5.0)); + check(&mut r, &d, id, "redone, the one-anchor subpath moved"); + path_of(&mut d, id).subpaths[2].anchors.push(Anchor::corner(Point::new(12_010.0, 40.0))); + check(&mut r, &d, id, "the empty subpath given an anchor"); +} + +#[test] +fn a_long_compound_path_draws_and_culls_after_each_edit_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let none = Appearance::default(); + let members = [ + PathData::single(zigzag(1500, 6000.0)), + PathData::single(ring(1500, Point::new(12_000.0, 15.0), 45.0)), + PathData::single(SubPath::new(vec![Anchor::corner(Point::new(11_980.0, 0.0))], false)), + PathData::new(vec![]), + ]; + let ids: Vec = members.iter().map(|_| d.alloc_id()).collect(); + let children = ids.iter().zip(members).map(|(id, p)| Arc::new(Node::path(*id, p, none.clone()))).collect(); + 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 first = d.clone(); + moved(&mut path_of(&mut d, ids[1]).subpaths[0].anchors[700], Vec2::new(-30.0, 10.0)); + check(&mut r, &d, id, "an anchor of the ring moved"); + moved(&mut path_of(&mut d, ids[0]).subpaths[0].anchors[0], Vec2::new(-30.0, 10.0)); + check(&mut r, &d, id, "the first anchor of the zigzag moved"); + moved(&mut path_of(&mut d, ids[2]).subpaths[0].anchors[0], Vec2::new(-30.0, 10.0)); + check(&mut r, &d, id, "the one-anchor member moved"); + path_of(&mut d, ids[3]).subpaths.push(SubPath::new(vec![Anchor::corner(Point::new(12_020.0, 30.0))], false)); + check(&mut r, &d, id, "the empty member given an anchor"); + check(&mut r, &first, id, "undone to the start"); +} + +#[test] +fn edits_in_runs_of_segments_without_length_measure_as_when_the_path_is_made_again() { + // A closed subpath whose anchors move onto their neighbours and off them again, the joints' + // miter tips skipping the segments without length, round the start too. + let mut d = Document::new(1000.0, 1000.0); + let mut sp = zigzag(1200, 11_900.0); + sp.closed = true; + let n = Node::path(d.alloc_id(), PathData::single(sp), look(vec![stroke(5.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + let mut seed: u64 = 7; + let mut next = |m: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % m + }; + for step in 0..60 { + let p = path_of(&mut d, id); + let n = p.subpaths[0].anchors.len(); + // Near the start, the end, or where one run of 128 segments ends and the next starts. + let k = [next(40), n - 1 - next(40), 128 * (1 + next(8)) + next(3)][step % 3]; + let to = match next(3) { + 0 => p.subpaths[0].anchors[(k + n - 1) % n].p, + 1 => p.subpaths[0].anchors[(k + 1) % n].p, + _ => p.subpaths[0].anchors[k].p + Vec2::new(next(20) as f64 - 10.0, next(20) as f64 - 10.0), + }; + p.subpaths[0].anchors[k] = Anchor::corner(to); + check(&mut r, &d, id, &format!("step {step}, anchor {k}")); + } +} + +#[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); + 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"); + moved(&mut path_of(&mut d, id).subpaths[0].anchors[1500], Vec2::new(0.0, 40.0)); + check(&mut r, &d, id, "one anchor moved"); + assert_eq!(kept(&r), before, "the kept path changed in place"); +} diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index ef7a449d3f..ffabf0a264 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -1,5 +1,5 @@ -//! A long stroke without dashes or a width profile is outlined in and around the view only -//! (`crop_line`), and draws the same pixels as when it is outlined whole. +//! A long stroke without a width profile is outlined in and around the view only (`crop_line`, +//! and for dashes `dash_kept`), and draws the same pixels as when it is outlined whole. use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, StrokeLayer}; @@ -12,8 +12,13 @@ const SIZE: u32 = 200; /// A document holding `path` stroked with `st` and no fill. fn doc(path: &BezPath, st: StrokeLayer) -> Document { + doc_with(path, vec![AppearanceItem::Stroke(st)]) +} + +/// A document holding `path` painted with `items`. +fn doc_with(path: &BezPath, items: Vec) -> Document { let mut d = Document::new(1000.0, 1000.0); - let n = Node::path(d.alloc_id(), PathData::from_bezpath(path), Appearance { items: vec![AppearanceItem::Stroke(st)], ..Default::default() }); + let n = Node::path(d.alloc_id(), PathData::from_bezpath(path), Appearance { items, ..Default::default() }); let l = d.layers[0].id; d.insert(Some(l), 0, n).unwrap(); d @@ -98,6 +103,111 @@ fn a_long_stroke_draws_the_same_pixels_outlined_near_the_view() { } } +fn dashed(mut st: StrokeLayer, pattern: &[f64], offset: f64, align_corners: bool) -> StrokeLayer { + st.dash = Some(vectorcraft_doc::Dash { pattern: pattern.to_vec(), offset, align_corners }); + st +} + +/// A document holding `path` filled red and stroked with `st`. +fn filled(path: &BezPath, st: StrokeLayer) -> Document { + let fill = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))); + doc_with(path, vec![fill, AppearanceItem::Stroke(st)]) +} + +#[test] +fn a_long_dashed_stroke_draws_the_same_pixels_outlined_near_the_view() { + let round = stroke(6.0, LineJoin::Round, LineCap::Round); + let mut two_rings = ring(4000, 5000.0); + two_rings.extend(ring(3000, 4980.0).iter()); + let cases = [ + ( + "zigzag, miter joins, square caps", + doc(&zigzag(), dashed(stroke(6.0, LineJoin::Miter, LineCap::Square), &[30.0, 12.0], 7.0, false)), + Point::new(12_000.0, 15.0), + ), + ( + "ring through its start, a dash across it", + doc(&ring(4000, 5000.0), dashed(round.clone(), &[40.0, 25.0], 0.0, false)), + Point::new(5000.0, 0.0), + ), + ("ring, dots", doc(&ring(4000, 5000.0), dashed(round.clone(), &[0.0, 9.0], 0.0, false)), Point::new(0.0, 5000.0)), + ("ring filled, dashed", filled(&ring(4000, 5000.0), dashed(round.clone(), &[15.0, 10.0, 0.0, 10.0], 4.0, false)), Point::new(-5000.0, 0.0)), + ( + "zigzag, dashes fitted to corners", + doc(&zigzag(), dashed(stroke(4.0, LineJoin::Bevel, LineCap::Butt), &[5.0, 3.0], 0.0, true)), + Point::new(8000.0, 15.0), + ), + ("two subpaths, dashed", doc(&two_rings, dashed(round.clone(), &[25.0, 15.0], 0.0, false)), Point::new(0.0, -4990.0)), + ("a pattern too fine, drawn solid", doc(&zigzag(), dashed(round, &[0.001, 0.001], 0.0, false)), Point::new(12_000.0, 15.0)), + ]; + for (what, d, at) in &cases { + let mut r = Renderer::new(); + let img = render(&mut r, d, *at); + assert!(r.strokes.values().any(|e| e.crop.is_some()), "{what}: outlined near the view"); + assert!(img.pixels == whole(d, *at).pixels, "{what}: the same pixels as the whole outline"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "{what}: the stroke shows"); + for step in [Point::new(60.0, 40.0), Point::new(450.0, 0.0), Point::new(-900.0, 300.0)] { + let next = *at + step.to_vec2(); + assert!(render(&mut r, d, next).pixels == whole(d, next).pixels, "{what}, moved by {step:?}: the same pixels"); + } + } +} + +#[test] +fn a_long_dashed_stroke_draws_the_same_pixels_after_its_path_changes() { + let st = dashed(stroke(5.0, LineJoin::Miter, LineCap::Butt), &[18.0, 7.0], 3.0, false); + let at = Point::new(12_000.0, 15.0); + let mut r = Renderer::new(); + render(&mut r, &doc(&zigzag(), st.clone()), at); + // An anchor in the view moved, then one far before it, which shifts every dash after it. + for (i, by) in [(1501, Vec2::new(0.0, 12.0)), (40, Vec2::new(-3.0, 0.0))] { + let mut bp = zigzag(); + let mut els = bp.elements().to_vec(); + let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(i) else { + panic!("anchor {i} is not a line"); + }; + *p += by; + bp = BezPath::from_vec(els); + let d = doc(&bp, st.clone()); + assert!(render(&mut r, &d, at).pixels == whole(&d, at).pixels, "anchor {i} moved: the same pixels"); + } +} + +#[test] +fn short_dashed_strokes_are_outlined_whole() { + let st = dashed(stroke(4.0, LineJoin::Round, LineCap::Round), &[6.0, 4.0], 0.0, false); + let one = BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(100.0, 100.0))]); + let mut dot = one.clone(); + dot.line_to((100.0, 100.0)); + for (what, bp) in + [("empty", BezPath::new()), ("one anchor", one), ("one anchor, closed on itself", dot), ("a ring of 40 anchors", ring(40, 80.0))] + { + let d = doc(&bp, st.clone()); + let mut r = Renderer::new(); + let img = render(&mut r, &d, Point::new(100.0, 100.0)); + assert!(r.strokes.values().all(|e| e.crop.is_none()), "{what}: outlined whole"); + assert!(img.pixels == whole(&d, Point::new(100.0, 100.0)).pixels, "{what}: the same pixels"); + } +} + +#[test] +fn a_dashed_stroke_a_wide_stroke_crosses_over_draws_the_same_pixels() { + // The closed sliver of `a_stroke_a_wide_stroke_crosses_over_stays_whole`, dashed. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for i in 1..=2000 { + bp.line_to((f64::from(i) * 10.0, 0.0)); + } + bp.line_to((20_000.0, 4.0)); + bp.line_to((0.0, 4.0)); + bp.close_path(); + let d = doc(&bp, dashed(stroke(10.0, LineJoin::Miter, LineCap::Butt), &[35.0, 15.0], 0.0, false)); + for at in [Point::new(20_000.0, 2.0), Point::new(9_000.0, 2.0), Point::new(0.0, 2.0)] { + let mut r = Renderer::new(); + assert!(render(&mut r, &d, at).pixels == whole(&d, at).pixels, "at {at:?}: the same pixels"); + } +} + /// A zigzag of 3,000 anchors 8 pt apart between y = 60 and y = 550, through the bottom of a view /// on y = 0. fn tall_zigzag() -> BezPath { diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index f0c4b40e1f..976709e752 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2422,3 +2422,75 @@ 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:?}"); + } +} diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs new file mode 100644 index 0000000000..f08e341c25 --- /dev/null +++ b/crates/render/src/tests/movedstroke.rs @@ -0,0 +1,465 @@ +//! A moved object draws its stroke from the outline made for it before it moved, and a gradient +//! along or across its stroke from the slices made for it before it moved, moved by the same +//! offset, with the pixels a new renderer draws. A change other than a move outlines the stroke +//! and makes the slices again. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeGradientMode, StrokeLayer, + WidthProfile, +}; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::renderer::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; +use crate::*; + +const SIZE: u32 = 200; + +/// The view that shows `at` in the middle of the 200×200 frame. +fn view_at(at: Point) -> Affine { + Affine::translate((100.0 - at.x, 100.0 - at.y)) +} + +fn render(r: &mut Renderer, d: &Document, at: Point) -> Rendered { + r.render(d, SIZE, SIZE, view_at(at), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// How many stroke outlines the renderers on this thread have made. +fn outlined() -> usize { + STROKES_OUTLINED.with(std::cell::Cell::get) +} + +/// A document holding `path` painted with `items`, and the path's id. +fn doc(path: &BezPath, items: Vec) -> (Document, NodeId) { + let mut d = Document::new(1000.0, 1000.0); + let id = d.alloc_id(); + let n = Node::path(id, PathData::from_bezpath(path), Appearance { items, ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + (d, id) +} + +fn stroke(width: f64, join: LineJoin, cap: LineCap) -> StrokeLayer { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + st.join = join; + st.cap = cap; + st.miter_limit = 10.0; + st +} + +fn dashed(mut st: StrokeLayer, pattern: &[f64]) -> StrokeLayer { + st.dash = Some(Dash { pattern: pattern.to_vec(), offset: 0.0, align_corners: false }); + st +} + +/// `n` anchors 8 pt apart, up and down by 30 pt, every third segment curved. +fn zigzag(n: usize) -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 0.0 } else { 30.0 }); + bp.move_to(at(0)); + for i in 1..n { + if i % 3 == 0 { + bp.curve_to(at(i - 1) + Vec2::new(6.0, 0.0), at(i) + Vec2::new(-6.0, 10.0), at(i)); + } else { + bp.line_to(at(i)); + } + } + bp +} + +/// A closed polygon of `n` anchors round a circle of radius `r` about the origin. +fn ring(n: usize, r: f64) -> BezPath { + let mut bp = BezPath::new(); + for i in 0..n { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = Point::new(r * t.cos(), r * t.sin()); + if i == 0 { bp.move_to(p) } else { bp.line_to(p) } + } + bp.close_path(); + bp +} + +/// The documents of the cases: open and closed paths, short and long (outlined near the view), plain, +/// dashed, with a width profile, with arrowheads, and filled with a gradient (which a move changes, so the moved +/// object has an appearance of its own), each with the point the view is centered on. +fn cases() -> Vec<(&'static str, (Document, NodeId), Point)> { + let round = stroke(6.0, LineJoin::Round, LineCap::Round); + let mut lens = stroke(10.0, LineJoin::Round, LineCap::Butt); + lens.profile = Some(WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }); + let mut arrows = stroke(4.0, LineJoin::Miter, LineCap::Butt); + arrows.start_arrow = Some(Arrowhead::Triangle); + arrows.end_arrow = Some(Arrowhead::Circle); + arrows.arrow_align = ArrowAlign::Tip; + let gradient = FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))); + let only = |st: StrokeLayer| vec![AppearanceItem::Stroke(st)]; + vec![ + ("a short open path", doc(&zigzag(20), only(stroke(5.0, LineJoin::Miter, LineCap::Square))), Point::new(70.0, 15.0)), + ("a short closed path, dashed", doc(&ring(40, 80.0), only(dashed(round.clone(), &[12.0, 7.0]))), Point::new(0.0, 0.0)), + ("a long open path", doc(&zigzag(3000), only(stroke(6.0, LineJoin::Miter, LineCap::Square))), Point::new(12_000.0, 15.0)), + ("a long closed path", doc(&ring(4000, 5000.0), only(round.clone())), Point::new(0.0, 5000.0)), + ( + "a long open path, dashed", + doc(&zigzag(3000), only(dashed(stroke(5.0, LineJoin::Bevel, LineCap::Butt), &[30.0, 12.0]))), + Point::new(8000.0, 15.0), + ), + ( + "a long closed path, dashed, filled with a gradient", + doc(&ring(4000, 5000.0), vec![AppearanceItem::Fill(gradient), AppearanceItem::Stroke(dashed(round, &[25.0, 15.0]))]), + Point::new(-5000.0, 0.0), + ), + ("a long open path, a width profile", doc(&zigzag(3000), only(lens)), Point::new(12_000.0, 15.0)), + // The heads shorten the line, so the line is not the path itself. + ("a short open path, arrowheads", doc(&zigzag(20), only(arrows.clone())), Point::new(70.0, 15.0)), + ("a long open path, arrowheads", doc(&zigzag(3000), only(arrows)), Point::new(40.0, 15.0)), + ] +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many stroke outlines `r` made. +fn after(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = outlined(); + let img = render(r, d, at); + let made = outlined() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +#[test] +fn a_moved_path_draws_its_stroke_from_the_outline_made_before() { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new outline"); + } + // A fill of another color keeps the path where it is. + let made = after(&mut r, &mut d, id, at, |n| { + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + } + }); + assert_eq!(made, 0, "{what}, a fill changed: no new outline"); + } +} + +#[test] +fn a_path_changed_otherwise_outlines_its_stroke_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut bp = path.to_bezpath(); + let mut els = bp.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + bp = BezPath::from_vec(els); + *path = PathData::from_bezpath(&bp); + }; + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + // A move, then an edit of an anchor near the path's start. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved"); + assert_eq!(after(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the outline made for the edited path. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved after the edit"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + // Another join. + let rejoin = |n: &mut Node| { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + s.join = if s.join == LineJoin::Round { LineJoin::Bevel } else { LineJoin::Round }; + } + } + }; + assert_eq!(after(&mut r, &mut d, id, at, rejoin), 1, "{what}: another join"); + // Back to the first join and moved again: the outline of the join before is not used. + assert_eq!( + after(&mut r, &mut d, id, at, |n| { + rejoin(n); + n.transform(Affine::translate((1.0, 0.0)), true); + }), + 1, + "{what}: the join changed back and moved" + ); + } +} + +/// Checks that each case, drawn once and then changed by `change` (given the point the view is +/// centered on), is drawn with one new outline and the pixels of a new renderer. +fn outlined_again(change: impl Fn(&mut Node, Point)) { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert_eq!(after(&mut r, &mut d, id, at, |n| change(n, at)), 1, "{what}"); + } +} + +/// Applies `change` to every stroke of `n`. +fn restroke(n: &mut Node, change: impl Fn(&mut StrokeLayer)) { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + change(s); + } + } +} + +#[test] +fn a_sheared_path_outlines_its_stroke_again() { + // Sheared about the view's center, stroke weights kept. + outlined_again(|n, at| n.transform(Affine::translate(at.to_vec2()) * Affine::skew(0.001, 0.0) * Affine::translate(-at.to_vec2()), false)); +} + +#[test] +fn another_stroke_width_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.width += 1.0)); +} + +#[test] +fn another_cap_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.cap = if s.cap == LineCap::Round { LineCap::Butt } else { LineCap::Round })); +} + +#[test] +fn another_dash_pattern_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.dash { + Some(d) => d.pattern[0] += 4.0, + None => s.dash = Some(Dash { pattern: vec![9.0, 5.0], offset: 0.0, align_corners: false }), + }) + }); +} + +#[test] +fn another_width_profile_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.profile { + Some(p) => p.points[1].1 = 0.5, + None => s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.25, 0.25)] }), + }) + }); +} + +#[test] +fn a_small_edit_far_from_the_origin_is_not_taken_for_a_move() { + for (far, edits) in [(1e9, &[0.5, 0.0005][..]), (1e15, &[0.5][..])] { + let was = Affine::translate((far, -far)) * zigzag(20); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!( + offset_between(&was, &moved), + Some(moved.elements()[0].end_point().unwrap() - was.elements()[0].end_point().unwrap()), + "at {far}: moved" + ); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "at {far}: anchors moved"); + for &edit in edits { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "at {far}: an anchor moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "at {far}: an anchor moved by {edit} pt, read from the anchors"); + // The third segment is a curve: its first handle. + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::CurveTo(h, _, _)) = els.get_mut(3) { + h.x += edit; + } + assert!(!anchors_moved(&node(&was), &node(&BezPath::from_vec(els))), "at {far}: a handle moved by {edit} pt"); + } + } +} + +#[test] +fn an_edit_near_the_origin_is_not_taken_for_a_move_when_the_path_starts_far_from_it() { + // A subpath at 1e16 pt, where coordinates step by 2 pt, then one near the origin. + let mut was = BezPath::new(); + was.move_to((1e16, 1e16)); + was.line_to((1e16 + 64.0, 1e16)); + was.extend(zigzag(20)); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(by), "moved: the offset of the subpath near the origin"); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "anchors moved"); + // The first and the third anchor of the subpath near the origin. + for at in [2, 4] { + for edit in [1.0, 0.5] { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p)) = els.get_mut(at) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "element {at} moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "element {at} moved by {edit} pt, read from the anchors"); + } + } +} + +#[test] +fn points_each_near_the_one_before_are_checked_against_one_offset() { + let path = |xs: [f64; 3]| { + let mut bp = BezPath::new(); + bp.move_to((xs[0], 0.0)); + bp.line_to((xs[1], 0.0)); + bp.line_to((xs[2], 0.0)); + bp + }; + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let was = path([1e16, 1e15, 1e14]); + // Coordinates step by 2, 0.125 and 0.015625 pt there. + let moved = Affine::translate((6.25, 0.0)) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(Vec2::new(6.25, 0.0)), "moved"); + assert!(anchors_moved(&node(&was), &node(&moved)), "anchors moved"); + // Each point is within rounding of the one before it, but the first did not move. + let edited = path([1e16, 1e15 + 6.0, 1e14 + 6.25]); + assert_eq!(offset_between(&was, &edited), None); + assert!(!anchors_moved(&node(&was), &node(&edited))); +} + +/// How many sets of gradient stroke slices the renderers on this thread have made. +fn sliced() -> usize { + SLICES_MADE.with(std::cell::Cell::get) +} + +/// A stroke of `width` whose black to blue gradient runs `mode` (along or across the path). +fn gradient_stroke(width: f64, mode: StrokeGradientMode) -> StrokeLayer { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]); + let mut st = stroke(width, LineJoin::Round, LineCap::Butt); + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + st.gradient_mode = mode; + st +} + +/// The documents of the gradient cases: open and closed paths, short and long (their line outlined +/// near the view), each with a gradient along and across the stroke, with the point the view is +/// centered on. +fn gradient_cases() -> Vec<(String, (Document, NodeId), Point)> { + let mut out = vec![]; + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let only = || vec![AppearanceItem::Stroke(gradient_stroke(12.0, mode))]; + out.push((format!("a short open path, {mode:?}"), doc(&zigzag(20), only()), Point::new(70.0, 15.0))); + out.push((format!("a short closed path, {mode:?}"), doc(&ring(40, 80.0), only()), Point::new(80.0, 0.0))); + out.push((format!("a long open path, {mode:?}"), doc(&zigzag(3000), only()), Point::new(12_000.0, 15.0))); + out.push((format!("a long closed path, {mode:?}"), doc(&ring(4000, 5000.0), only()), Point::new(0.0, 5000.0))); + // A placed gradient, whose start and end a move moves too. + let mut st = gradient_stroke(12.0, mode); + if let Paint::Gradient(g) = &mut st.paint { + g.geom = Some(GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(140.0, 30.0), aspect: 1.0, focal: None }); + g.angle = 12.0; + } + out.push(( + format!("a short open path with a placed gradient, {mode:?}"), + doc(&zigzag(20), vec![AppearanceItem::Stroke(st)]), + Point::new(70.0, 15.0), + )); + } + out +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many sets of slices `r` made. +fn after_sliced(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = sliced(); + let img = render(r, d, at); + let made = sliced() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +/// Sets the color of the last stop of each stroke's gradient in `n`. +fn recolor(n: &mut Node, color: Color) { + restroke(n, |s| { + if let Paint::Gradient(g) = &mut s.paint + && let Some(stop) = g.gradient.stops.last_mut() + { + stop.color = color; + } + }) +} + +#[test] +fn a_moved_path_draws_its_gradient_stroke_from_the_slices_made_before() { + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new slices"); + } + assert_eq!(after_sliced(&mut r, &mut d, id, at, |_| {}), 0, "{what}: drawn again after the moves"); + } +} + +#[test] +fn a_path_changed_otherwise_makes_its_gradient_stroke_slices_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut els = path.to_bezpath().elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + *path = PathData::from_bezpath(&BezPath::from_vec(els)); + }; + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + let nudge = |n: &mut Node| n.transform(Affine::translate((0.5, 0.0)), true); + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the slices made for the edited path. + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved after the edit"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| recolor(n, Color::rgb(0.0, 0.5, 0.0))), 1, "{what}: another gradient"); + // Moved with the gradient changed back: the slices of that gradient made before are not used. + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + recolor(n, Color::rgb(0.0, 0.0, 1.0)); + nudge(n); + }), + 1, + "{what}: the gradient changed back and moved" + ); + // Moved with the gradient laid the other way. + let turn = |s: &mut StrokeLayer| { + s.gradient_mode = if s.gradient_mode == StrokeGradientMode::Along { StrokeGradientMode::Across } else { StrokeGradientMode::Along } + }; + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + restroke(n, turn); + nudge(n); + }), + 1, + "{what}: the gradient laid the other way and moved" + ); + } +} + +#[test] +fn a_path_moved_out_of_the_region_its_outline_was_cropped_to_is_outlined_again() { + let (mut d, id) = doc(&zigzag(3000), vec![AppearanceItem::Stroke(stroke(6.0, LineJoin::Miter, LineCap::Square))]); + let at = Point::new(12_000.0, 15.0); + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert!(r.strokes.values().any(|e| e.crop.is_some()), "outlined near the view"); + // The outline reaches the view's size past each side of it: 200 pt. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 0, "moved within the region"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 1, "moved past it"); +} 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/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/export/text.rs b/crates/svg/src/export/text.rs index 387a1a3420..01510cd0d7 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -784,15 +784,26 @@ fn end_segment( } } +#[cfg(test)] +thread_local! { + /// Tests: how many times [`reader_advances`] laid out type again on this thread. + static READER_LAYOUTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The advance a reader of live SVG text gives each character cluster of `t` and how far from /// its pen it draws the cluster's first glyph, keyed by the cluster's byte offset: `t` laid out /// as point type (which isn't justified) without Mojikumi, scaled as `t`'s layout `lay` is by /// Shrink Text to Fit. Without `kerning`, the font's pair kerning is left out (as manual -/// kerning leaves it out). +/// kerning leaves it out). When that leaves `t` as it is, its glyphs are read from `lay`, which +/// is `t`'s layout, instead of laying it out again. fn reader_advances(t: &TextObject, lay: &vectorcraft_text::TextLayout, kerning: bool) -> HashMap { + // Mojikumi that spaces none of the characters sets them as Mojikumi None does. + let mojikumi = lay.mojikumi_applies(&t.plain_text()); let mut set = TextObject { kind: TextKind::Point, ..t.clone() }; for p in std::iter::once(&mut set.para).chain(set.paras.iter_mut()) { - p.mojikumi = vectorcraft_doc::Mojikumi::None; + if mojikumi { + p.mojikumi = vectorcraft_doc::Mojikumi::None; + } // A reader spaces words and letters as the font does. p.justification = vectorcraft_doc::JustificationOptions::default(); } @@ -801,8 +812,17 @@ fn reader_advances(t: &TextObject, lay: &vectorcraft_text::TextLayout, kerning: r.style.kerning.get_or_insert(0.0); } } + let relaid; + let glyphs = if set == *t { + &lay.glyphs + } else { + #[cfg(test)] + READER_LAYOUTS.with(|n| n.set(n.get() + 1)); + relaid = vectorcraft_text::layout(FontDb::global(), &set); + &relaid.glyphs + }; let mut out: HashMap = HashMap::new(); - for g in vectorcraft_text::layout(FontDb::global(), &set).glyphs.iter().filter(|g| g.len > 0) { + for g in glyphs.iter().filter(|g| g.len > 0) { let (advance, _) = out.entry(g.byte).or_insert((0.0, (g.xf.translation().x - g.origin.x) * lay.fit_scale)); *advance += g.advance * lay.fit_scale; } @@ -819,3 +839,6 @@ fn line_start(line: &[Segment], anchor: Option) -> Option<(f64, f64)> { }; Some((x, first.y)) } + +#[cfg(test)] +mod tests; diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs new file mode 100644 index 0000000000..fa8ca0455c --- /dev/null +++ b/crates/svg/src/export/text/tests.rs @@ -0,0 +1,136 @@ +//! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid +//! out again each time, which happens only when a reader sets the type differently from its layout. + +use super::*; +use vectorcraft_doc::text::{Bullet, ParaList}; +use vectorcraft_doc::{Document, JustificationOptions, Mojikumi, TextRun}; +use vectorcraft_geom::{Point, shapes}; + +/// The advances with `t` laid out again as a reader sets it, whatever it holds. +fn laid_out_again(t: &TextObject, lay: &vectorcraft_text::TextLayout, kerning: bool) -> HashMap { + let mut set = TextObject { kind: TextKind::Point, ..t.clone() }; + for p in std::iter::once(&mut set.para).chain(set.paras.iter_mut()) { + p.mojikumi = Mojikumi::None; + p.justification = JustificationOptions::default(); + } + if !kerning { + for r in &mut set.runs { + r.style.kerning.get_or_insert(0.0); + } + } + let mut out: HashMap = HashMap::new(); + for g in vectorcraft_text::layout(FontDb::global(), &set).glyphs.iter().filter(|g| g.len > 0) { + let (advance, _) = out.entry(g.byte).or_insert((0.0, (g.xf.translation().x - g.origin.x) * lay.fit_scale)); + *advance += g.advance * lay.fit_scale; + } + out +} + +fn style() -> CharStyle { + CharStyle { size: 12.0, fill: Paint::solid(vectorcraft_color::Color::BLACK), ..CharStyle::default() } +} + +/// Point type with Line-end Punctuation Half Width, the setting new type gets. +fn point(text: &str) -> TextObject { + let mut t = TextObject::point(Point::new(20.0, 20.0), text, style()); + t.para.mojikumi = Mojikumi::LineEndHalf; + t +} + +/// How many times [`reader_advances`] laid out `t` again (`kerning` as it is given), after checking +/// that it gives what laying out again gives. +fn layouts_again(t: &TextObject, kerning: bool) -> usize { + let lay = vectorcraft_text::layout(FontDb::global(), t); + READER_LAYOUTS.with(|n| n.set(0)); + let got = reader_advances(t, &lay, kerning); + let again = READER_LAYOUTS.with(std::cell::Cell::get); + assert_eq!(got, laid_out_again(t, &lay, kerning), "{:?}", t.plain_text()); + again +} + +/// SVG export of `texts`, each a type object, and how many times it laid type out again for its +/// reader advances. +fn export_layouts_again(texts: Vec) -> (String, usize) { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + for t in texts { + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + READER_LAYOUTS.with(|n| n.set(0)); + let svg = crate::export(&d, &crate::ExportOptions::default()); + (svg, READER_LAYOUTS.with(std::cell::Cell::get)) +} + +#[test] +fn latin_type_with_mojikumi_is_not_laid_out_again() { + assert_eq!(layouts_again(&point("Latin words, digits 2026 and (brackets)."), true), 0); + let (svg, again) = export_layouts_again(vec![point("Ab0"), point("Ab1"), point("Ab2")]); + assert_eq!(again, 0, "{svg}"); + assert!(svg.contains(">Ab1"), "{svg}"); +} + +#[test] +fn empty_and_one_character_type() { + assert_eq!(layouts_again(&point(""), true), 0); + assert_eq!(layouts_again(&point("A"), true), 0); + assert_eq!(layouts_again(&point("A"), false), 1); + let (svg, again) = export_layouts_again(vec![point(""), point("A")]); + assert_eq!(again, 0, "{svg}"); +} + +#[test] +fn japanese_type_with_mojikumi_is_laid_out_again() { + for text in ["「かな」、漢字とLatin。", "雅", "、"] { + assert_eq!(layouts_again(&point(text), true), 1, "{text}"); + } + // Without Mojikumi, a reader sets it as the layout does. + let mut none = point("「かな」、漢字とLatin。"); + none.para.mojikumi = Mojikumi::None; + assert_eq!(layouts_again(&none, true), 0); +} + +#[test] +fn a_japanese_run_or_paragraph_lays_the_whole_object_out_again() { + let mut runs = point("Latin "); + runs.runs.push(TextRun::new("漢字", style())); + assert_eq!(layouts_again(&runs, true), 1); + let paras = point("Latin\n漢字"); + assert_eq!(layouts_again(¶s, true), 1); +} + +#[test] +fn area_and_justified_type_is_laid_out_again() { + let mut area = point("aa bb cc dd ee ff"); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 160.0)) }; + area.para.justify = Justify::JustifyLeft; + assert_eq!(layouts_again(&area, true), 1); + let mut spaced = point("Latin words"); + spaced.para.justification = JustificationOptions { letter_spacing: [0.0, 5.0, 10.0], ..JustificationOptions::default() }; + assert_eq!(layouts_again(&spaced, true), 1); +} + +#[test] +fn unkerned_advances_lay_out_again_only_for_runs_without_manual_kerning() { + let mut wide = point("AVAV"); + wide.runs[0].style.h_scale = 150.0; + assert_eq!(layouts_again(&wide, false), 1); + wide.runs[0].style.kerning = Some(0.0); + assert_eq!(layouts_again(&wide, false), 0); +} + +#[test] +fn list_items_with_latin_markers_are_not_laid_out_again() { + let mut bullets = point("first\nsecond"); + bullets.para.list = Some(ParaList::bulleted(Bullet::Dot)); + assert_eq!(layouts_again(&bullets, true), 0); + let mut numbers = point("一つ\n二つ"); + numbers.para.list = Some(ParaList::numbered(vectorcraft_doc::text::NumberStyle::Arabic)); + assert_eq!(layouts_again(&numbers, true), 1); +} + +#[test] +fn a_mixed_document_lays_out_again_only_the_japanese_type() { + let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); + assert_eq!(again, 1, "{svg}"); +} 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/text/src/fontdb/build.rs b/crates/text/src/fontdb/build.rs index 128cd49b33..ba91aa999e 100644 --- a/crates/text/src/fontdb/build.rs +++ b/crates/text/src/fontdb/build.rs @@ -136,5 +136,10 @@ pub(super) fn style_italic(style: &str) -> bool { /// slant. The penalty is less than the weight gap between Regular and Bold (and Bold and Black), /// so Bold Italic asked of a family with Bold and Italic faces only gets the Bold (#2491). pub(super) fn style_distance(face: &FontFace, weight: f32, italic: bool) -> f32 { - (face.weight - weight).abs() + if face.italic != italic { 250.0 } else { 0.0 } + weight_distance(face.weight, face.italic, weight, italic) +} + +/// [`style_distance`] for a face known only by its weight and slant (a cataloged face). +pub(super) fn weight_distance(face_weight: f32, face_italic: bool, weight: f32, italic: bool) -> f32 { + (face_weight - weight).abs() + if face_italic != italic { 250.0 } else { 0.0 } } diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 1b14dd6dcb..226ad7832d 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -218,6 +218,30 @@ impl FontDb { v.into_iter().map(|t| t.2).collect() } + /// The style a style-less request gets for `family`: its face nearest Regular upright, by the + /// catalog's or the loaded faces' metadata. Unlike [`FontDb::face`] it reads no font files, so + /// the closest styles of many families cost little. + pub fn closest_style(&self, family: &str) -> Option { + let (family, _) = self.canonical(family, ""); + let family = family.as_str(); + let mut best: Option<(f32, String)> = None; + let consider = |best: &mut Option<(f32, String)>, weight: f32, italic: bool, style: &str| { + let d = super::build::weight_distance(weight, italic, 400.0, false); + if best.as_ref().is_none_or(|(b, _)| d < *b) { + *best = Some((d, style.to_string())); + } + }; + for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) { + consider(&mut best, f.weight, f.italic, &f.style); + } + if let Some(c) = self.read_catalog().get(&family.to_ascii_lowercase()) { + for cf in &c.faces { + consider(&mut best, cf.weight, cf.italic, &cf.style); + } + } + best.map(|(_, style)| style) + } + /// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or /// every face was already present). pub fn add_font(&self, bytes: Vec) -> usize { diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index 16aa674ca6..bcf758706d 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -7,6 +7,11 @@ //! Preferences › Hyphenation › Exceptions (comma separated) override the points for named words: //! `typography` never breaks, `ty-pog-ra-phy` breaks only where the hyphens mark. See //! [`set_hyphenation_exceptions`]. +//! +//! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English is +//! the only language with break points so far: text in any other language, or in a language a +//! file names that isn't known, doesn't hyphenate, apart from the words in the Exceptions list +//! ([`language_has_patterns`]). use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -144,6 +149,12 @@ fn onset_pair(a: char, b: char) -> bool { ) } +/// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for +/// the default, English: USA) has break points of its own. +pub fn language_has_patterns(language: Option<&str>) -> bool { + language.is_none_or(|l| l.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("en")) && matches!(l.as_bytes().get(2), None | Some(b'-'))) +} + /// Allowed hyphenation points in `word`, as char indices (a hyphen goes *before* the char), with /// the default Hyphenation options. pub fn hyphen_points(word: &str) -> Vec { @@ -157,12 +168,21 @@ pub fn hyphen_points(word: &str) -> Vec { /// (other than a trailing apostrophe) are not hyphenated. Preferences exceptions override the /// pattern and these options for a matching word. pub fn hyphen_points_with(word: &str, opts: &HyphenationOptions) -> Vec { + hyphen_points_in(word, opts, true) +} + +/// [`hyphen_points_with`] for a word in a language with or without break points of its own +/// ([`language_has_patterns`]): without them, only a word in the Exceptions list breaks. +pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) -> Vec { if let Some(ex) = exception_for(word) { return match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; } + if !patterns { + return vec![]; + } let c: Vec = word.chars().collect(); let n = c.len(); let longer_than = usize::try_from(opts.words_longer_than).unwrap_or(usize::MAX); @@ -235,6 +255,31 @@ mod tests { with_hyphenation_exceptions_for_test(source, f); } + /// #394: English in any region has break points; other languages, and a tag from a file that + /// isn't a known language, have none. + #[test] + fn only_english_has_break_points() { + for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { + assert!(language_has_patterns(l), "{l:?}"); + } + for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + assert!(!language_has_patterns(l), "{l:?}"); + } + } + + /// #394: a language without break points leaves words whole, but the Exceptions list is the + /// user's own and applies in every language. + #[test] + fn a_language_without_break_points_keeps_only_the_exceptions() { + let opts = HyphenationOptions::default(); + assert_eq!(hyphen_points_in("typography", &opts, true), vec![4, 7]); + assert!(hyphen_points_in("typography", &opts, false).is_empty()); + with_exceptions("ty-pog-ra-phy, happen", || { + assert_eq!(hyphen_points_in("typography", &opts, false), vec![2, 5, 7]); + assert!(hyphen_points_in("happen", &opts, false).is_empty()); + }); + } + /// #394 Preferences › Hyphenation › Exceptions contract (parse + override). #[test] fn hyphenation_exceptions_override_the_pattern() { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index b814506e6d..50e1ce0b27 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -14,7 +14,7 @@ use vectorcraft_geom::{ArcPath, PathData}; use crate::GlyphBend; use crate::composer::{Breakpoint, Params, compose}; use crate::fontdb::FontDb; -use crate::hyphen::hyphen_points_with; +use crate::hyphen::hyphen_points_in; use crate::justify::{Flex, LineFit, apply_desired, fit_line, is_word_space}; use crate::kashida; use crate::shape::{ diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 54d8941e83..90d6555a00 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -1,7 +1,7 @@ use super::region::Region; use super::{ Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, LeadingModel, SGlyph, hyphen_glyph, - hyphen_points_with, no_line_end, no_line_start, soft_line_start, + hyphen_points_in, no_line_end, no_line_start, soft_line_start, }; /// Vertical metrics of a line: (ascent, descent, leading, cap height, x height). @@ -518,7 +518,8 @@ fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() { } } -/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`. +/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`, in the +/// language of the word's first letter. fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &HyphenationOptions) -> Vec { // Strip leading/trailing punctuation (quotes, commas). let (mut a, mut b) = (ws, we); @@ -542,7 +543,7 @@ fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyphenat starts.entry(g[k].byte).or_insert(k); } } - hyphen_points_with(word, opts).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() + hyphen_points_in(word, opts, g[a].hyphenates).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() } /// Break candidates for the every-line composer: hyphenation points under `hyphenate` (the diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 372c70b2fd..15a4338c15 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -145,6 +145,17 @@ fn is_japanese_letter(c: char) -> bool { && punct(c).is_none() } +impl TextLayout { + /// Whether Line-end Punctuation Half Width (Mojikumi) can set type laid out as this layout + /// differently from Mojikumi None: `text`, the type's plain text, or one of the layout's list + /// markers holds Japanese punctuation or a Japanese letter, the only characters it spaces. + /// When it holds neither, the type lays out the same with either setting. + pub fn mojikumi_applies(&self, text: &str) -> bool { + let spaced = |c: char| punct(c).is_some() || is_japanese_letter(c); + text.chars().any(spaced) || self.markers.iter().any(|m| m.text.chars().any(spaced)) + } +} + /// A Latin letter or digit (or another script's letter), set proportionally. fn is_latin_letter(c: char) -> bool { c.is_alphanumeric() && !is_cjk(c) diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 9f1a048b38..cdf5855390 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -39,6 +39,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { no_break: false, vertical_roman: false, cursive: false, + hyphenates: true, }) .collect() } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 54333a83cf..9763ea4b6d 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -813,6 +813,12 @@ pub fn paragraph_is_rtl(text: &str, direction: Option, at: usize) -> bool { + layout::para_bidi(text, direction).is_some_and(|info| info.levels.get(at).is_some_and(|level| level.is_rtl())) +} + /// Text stored in visual order (as PDF content draws it, each glyph where it is drawn), back in /// logical order: the order of its characters (indices into `visual.chars()`) and whether its /// paragraph runs right to left; laid out that way, it reads as drawn. `None` when nothing in it is diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 6ecd515db3..f37c7443ec 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -80,6 +80,8 @@ pub(crate) struct SGlyph { /// decided for the whole segment it was shaped in ([`joins`]): on a curved path it is bent /// along the path so its joins meet. pub cursive: bool, + /// The glyph's language has hyphenation break points ([`crate::hyphen::language_has_patterns`]). + pub hyphenates: bool, } /// Does `script` join its letters (a cursive script, whose neighbouring glyphs touch)? @@ -947,6 +949,7 @@ fn inline_glyph( no_break: st.no_break, vertical_roman: false, cursive: false, + hyphenates: false, } } @@ -1327,6 +1330,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe no_break: gst.no_break, vertical_roman: gst.standard_vertical_roman, cursive, + hyphenates: crate::hyphen::language_has_patterns(gst.language.as_deref()), }); } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 085bd6f0de..ebdd085738 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -423,6 +423,112 @@ pub fn half_form_font(half: bool) -> Option> { Some(builder.build()) } +/// The family of [`conjunct_font`]. +pub const CONJUNCT_FAMILY: &str = "Conjuncttest Sans"; + +/// A test-only cmap over bundled Source Sans 3: Devanagari Ka uses K, the halant uses a period and +/// the vowel sign I (drawn before its syllable) uses i. The `GSUB` table's `dev2` script has an +/// `aalt` single substitution of K by k and a `salt` one of K by i, which list k and the vowel +/// sign's glyph as alternates of Ka, and a `half` ligature of K and the period into k (Ka's half +/// form). Family [`CONJUNCT_FAMILY`]. `None` when it can't be built. +pub fn conjunct_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + use write_fonts::tables::gsub::{ + Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList, + }; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('क', 'K'), ('\u{094D}', '.'), ('\u{093F}', 'i')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = CONJUNCT_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Conjuncttest Sans Regular"), (6, "ConjuncttestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let ka = gid('K')?; + let aalt = SingleSubstFormat2::new(CoverageFormat1::new(vec![ka]).into(), vec![gid('k')?]); + let half = + LigatureSubstFormat1::new(CoverageFormat1::new(vec![ka]).into(), vec![LigatureSet::new(vec![Ligature::new(gid('k')?, vec![gid('.')?])])]); + let salt = SingleSubstFormat2::new(CoverageFormat1::new(vec![ka]).into(), vec![gid('i')?]); + // Features sorted by tag, as OpenType requires: `aalt`, `half`, then `salt`. + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(b"aalt"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"half"), Feature::new(None, vec![1])), + FeatureRecord::new(Tag::new(b"salt"), Feature::new(None, vec![2])), + ]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![aalt.into()])), + SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![half])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![salt.into()])), + ]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]))]); + builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + +/// The family of [`matra_font`]. +pub const MATRA_FAMILY: &str = "Matratest Sans"; + +/// A test-only cmap over bundled Source Sans 3: Devanagari Ka uses a, the vowel sign I (drawn +/// before its consonant) uses i and the nukta uses the period. The `GSUB` table's `dev2` script has +/// a `nukt` ligature of Ka and the nukta into N, and a `salt` single substitution of Ka by b. +/// Family [`MATRA_FAMILY`]. `None` when it can't be built. +pub fn matra_font() -> Option> { + use write_fonts::tables::cmap::Cmap; + use write_fonts::tables::gsub::{ + Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList, + }; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mapping = [('क', 'a'), ('\u{093F}', 'i'), ('\u{093C}', '.')]; + let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32())))); + let cmap = Cmap::from_mappings(mappings.collect::>>()?).ok()?; + let family = MATRA_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Matratest Sans Regular"), (5, "Version 1.000"), (6, "MatratestSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let ka = gid('a')?; + let ligature = LigatureSet::new(vec![Ligature::new(gid('N')?, vec![gid('.')?])]); + let nukt = LigatureSubstFormat1::new(CoverageFormat1::new(vec![ka]).into(), vec![ligature]); + let salt = SingleSubstFormat2::new(CoverageFormat1::new(vec![ka]).into(), vec![gid('b')?]); + // Features sorted by tag, as OpenType requires: `nukt`, then `salt`. + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(b"nukt"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"salt"), Feature::new(None, vec![1])), + ]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![nukt])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![salt.into()])), + ]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), Script::new(Some(LangSys::new(vec![0, 1])), vec![]))]); + builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`lam_alef_font`] whose lam-alef ligature is in `feature`. pub fn lam_alef_family(feature: &[u8; 4]) -> &'static str { match feature { diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index f92ce67a6a..478bc9c97b 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1013,6 +1013,33 @@ fn hyphenation_rules() { } } +/// #394: each run hyphenates in its own language. English breaks words, a language without break +/// points doesn't, and text saved without a language breaks as it always did. +#[test] +fn each_run_hyphenates_in_its_own_language() { + let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let hyphens = |language: Option<&str>| { + let st = CharStyle { language: language.map(str::to_string), ..style(14.0) }; + let mut t = area(text, st, frame, Justify::Left); + t.para.hyphenate = true; + layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count() + }; + let saved_without_one = hyphens(None); + assert!(saved_without_one > 0, "some words hyphenated"); + assert_eq!(hyphens(Some("en-GB")), saved_without_one); + assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); + + // both in one paragraph: the English run breaks and the German one doesn't + let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); + t.para.hyphenate = true; + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + let l = layout(db(), &t); + let at: Vec = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index c0a2b5e13f..35e8260da3 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -688,6 +688,37 @@ fn mojikumi_spaces_japanese_from_latin_by_a_quarter_em() { assert!(on.glyphs.iter().zip(&off.glyphs).all(|(a, b)| (a.advance - b.advance).abs() < 0.01)); } +/// Mojikumi applies to type holding Japanese punctuation or a Japanese letter; type without either +/// lays out the same with Line-end Punctuation Half Width as with Mojikumi None, across lines and +/// list markers too. +#[test] +fn mojikumi_applies_only_to_japanese_punctuation_and_letters() { + use vectorcraft_doc::Mojikumi; + use vectorcraft_doc::text::{Bullet, ParaList}; + let styled = |text: &str, m: Mojikumi| { + let mut t = TextObject::point(Point::ZERO, text, CharStyle { size: 20.0, ..CharStyle::default() }); + t.xf = Affine::IDENTITY; + t.para.mojikumi = m; + t + }; + let placed = |l: &TextLayout| l.glyphs.iter().map(|g| (g.byte, g.advance, g.origin, g.xf)).collect::>(); + for text in ["", "A", "Latin words, digits 2026 and (brackets).", "first\nsecond"] { + let on = styled(text, Mojikumi::LineEndHalf); + let lay = layout(FontDb::global(), &on); + assert!(!lay.mojikumi_applies(&on.plain_text()), "{text:?}"); + let off = layout(FontDb::global(), &styled(text, Mojikumi::None)); + assert_eq!(placed(&lay), placed(&off), "{text:?}"); + assert_eq!(lay.bounds, off.bounds, "{text:?}"); + } + let mut listed = styled("first\nsecond", Mojikumi::LineEndHalf); + listed.para.list = Some(ParaList::bulleted(Bullet::Dot)); + assert!(!layout(FontDb::global(), &listed).mojikumi_applies(&listed.plain_text())); + for text in ["、", "「A」", "雅", "々", "Latin 漢字"] { + let t = styled(text, Mojikumi::LineEndHalf); + assert!(layout(FontDb::global(), &t).mojikumi_applies(&t.plain_text()), "{text:?}"); + } +} + /// Mojikumi (JLREQ 3.1.5): with Line-end Punctuation Half Width, an opening bracket starting a /// wrapped line is set flush with the line's start (the space before it goes), giving the line half /// an em more room; at the start of a paragraph too, so its face starts at the first-line indent diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index 42643538ed..e88721b04e 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -3,6 +3,8 @@ //! 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; pub mod extend_path; @@ -28,14 +30,19 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ /// Smart Pen's tool, a flyout group of its own. pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; +pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; + 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")]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(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]; +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> { @@ -54,6 +61,8 @@ pub fn create(id: &str) -> Option> { slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), 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, }) } @@ -74,6 +83,8 @@ mod tests { assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); 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/addons/contour.rs b/crates/tools/src/addons/contour.rs new file mode 100644 index 0000000000..e77bb29eed --- /dev/null +++ b/crates/tools/src/addons/contour.rs @@ -0,0 +1,254 @@ +//! The Contour tool: drag away from a selected shape's edge to grow a live copy of it, or toward the +//! inside to shrink it (`addon.contour.set`). The copy is the original's outline offset by the distance +//! the pointer has moved from the edge, previewed while the button is down and kept as one undo step +//! on release. Nothing is baked: the copy carries a live Offset Path effect, so it keeps being +//! editable (a second drag on a selected Contour changes its distance instead of nesting another), +//! and Expand Appearance bakes it. While a Contour is selected the tool draws the outline the +//! shape had before as a dashed guide. +//! +//! The distance is how far the pointer has moved from the shape's edge since the press, so a press +//! anywhere changes nothing until the pointer moves, and a Contour that already stands at some +//! distance continues from there. Shift rounds the distance to whole points. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, Point, hit}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "contour"; + +/// The live effect a Contour is made of (the one `addon.contour.set` applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest distance, in points, `addon.contour.set` accepts. +const MAX_OFFSET: f64 = 1e5; +/// The guide showing the shape a Contour was made from. +const GUIDE: [u8; 3] = [0x1e, 0x88, 0xe5]; + +/// A selected shape's outline, in the document. +struct Base { + path: BezPath, + rule: FillRule, +} + +fn base_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, rule, .. } => Some(Base { path: path.to_bezpath(), rule: *rule }), + NodeKind::Compound { children, rule } => { + let mut path = BezPath::new(); + for c in children { + if let Some(p) = c.path_data() { + path.extend(p.to_bezpath().elements().iter().copied()); + } + } + Some(Base { path, rule: *rule }) + } + _ => None, + } +} + +/// The Offset Path distance of a Contour (a shape that carries the effect). +fn contour_offset(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + Some(e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0)) +} + +/// The corner style and miter limit of a Contour's Offset Path effect, as `addon.contour.set` takes +/// them. +fn contour_style(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + let mut style = json!({ "corners": corners }); + if let Some(m) = e.params.get("miterLimit").and_then(Value::as_f64) { + style["miterLimit"] = json!(m); + } + Some(style) +} + +/// How far `p` is from the nearest of `bases`' edges: positive outside, negative inside. +fn signed_distance(bases: &[Base], p: Point) -> Option { + let mut nearest = f64::INFINITY; + let mut inside = false; + for b in bases { + nearest = nearest.min(hit::distance_to_outline(&b.path, p)); + inside |= hit::fill_contains(&b.path, b.rule, p); + } + nearest.is_finite().then_some(if inside { -nearest } else { nearest }) +} + +/// A press in progress. +struct Drag { + bases: Vec, + /// Where the pointer stood against the edge at the press. + pressed_at: f64, + /// The Contour's distance at the press (0 for a shape that is not one yet). + start: f64, + /// The corner style and miter limit every preview carries: the pressed Contour's own, else the + /// tool's options. + style: Value, + /// The distance last previewed. + last: Option, + /// Where the pointer is, for the distance label. + pos: Point, +} + +#[derive(Default)] +pub struct ContourTool { + drag: Option, + corners: Corners, + miter_limit: Option, +} + +/// How a Contour treats the corners of the shape. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Corners { + /// Pointed (mitered) corners. + #[default] + Sharp, + Round, + /// Corners cut off flat. + Square, +} + +impl Corners { + fn id(self) -> &'static str { + match self { + Corners::Sharp => "sharp", + Corners::Round => "round", + Corners::Square => "square", + } + } + + fn parse(s: &str) -> Option { + [Corners::Sharp, Corners::Round, Corners::Square].into_iter().find(|c| c.id().eq_ignore_ascii_case(s)) + } +} + +impl ContourTool { + /// The corner style and miter limit of a new Contour: the tool's options. + fn style(&self) -> Value { + let mut p = json!({ "corners": self.corners.id() }); + if let Some(m) = self.miter_limit { + p["miterLimit"] = json!(m); + } + p + } +} + +/// The selected shapes a Contour can be made of. +fn selected_shapes<'a>(cx: &'a ToolContext) -> Vec<&'a Node> { + cx.selection + .objects + .iter() + .filter_map(|id| cx.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect() +} + +fn round_distance(v: f64, mods: Mods) -> f64 { + let v = if mods.shift { v.round() } else { (v * 100.0).round() / 100.0 }; + v.clamp(-MAX_OFFSET, MAX_OFFSET) +} + +impl Tool for ContourTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Down => { + let shapes = selected_shapes(cx); + let start = shapes.first().and_then(|n| contour_offset(n)).unwrap_or(0.0); + // A Contour keeps its own corners; a new one takes the tool's. + let style = shapes.first().and_then(|n| contour_style(n)).unwrap_or_else(|| self.style()); + let bases: Vec = shapes.into_iter().filter_map(base_of).collect(); + let Some(pressed_at) = signed_distance(&bases, ev.pos) else { return vec![] }; + self.drag = Some(Drag { bases, pressed_at, start, style, last: None, pos: ev.pos }); + vec![Action::Begin("Contour".into())] + } + PointerKind::Drag => { + let Some(drag) = self.drag.as_mut() else { return vec![] }; + drag.pos = ev.pos; + let Some(now) = signed_distance(&drag.bases, ev.pos) else { return vec![] }; + let offset = round_distance(drag.start + now - drag.pressed_at, ev.mods); + // Nothing is previewed until the distance has left where it started: a drag along + // the edge (or one Shift rounds back) would otherwise leave an unchanged copy. + if !offset.is_finite() || drag.last == Some(offset) || (drag.last.is_none() && offset == drag.start) { + return vec![]; + } + drag.last = Some(offset); + let mut params = drag.style.clone(); + params["offset"] = json!(offset); + vec![Action::Preview("addon.contour.set".into(), params)] + } + PointerKind::Up => match self.drag.take() { + Some(d) if d.last.is_some() => vec![Action::Commit], + Some(_) => vec![Action::Cancel], + None => vec![], + }, + _ => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape if self.drag.take().is_some() => vec![Action::Cancel], + _ => vec![], + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + // The outline each selected Contour was made from. + for n in selected_shapes(cx) { + if contour_offset(n).is_none() { + continue; + } + if let Some(b) = base_of(n) { + // A white halo under the dashes, so the guide shows over any fill. + out.push(Overlay::Path { path: b.path.clone(), color: [255, 255, 255], width: 3.0, dashed: false }); + out.push(Overlay::Path { path: b.path, color: GUIDE, width: 1.0, dashed: true }); + } + } + if let Some(d) = &self.drag + && let Some(offset) = d.last + { + out.push(Overlay::Measure { p: d.pos, text: format!("{offset:+.2} pt") }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({"corners": self.corners.id(), "miterLimit": self.miter_limit.unwrap_or(4.0)}) + } + + fn set_option(&mut self, key: &str, value: &Value) { + match key { + "corners" => { + if let Some(c) = value.as_str().and_then(Corners::parse) { + self.corners = c; + } + } + "miterLimit" => { + if let Some(m) = value.as_f64().filter(|m| m.is_finite()) { + self.miter_limit = Some(m.clamp(1.0, 500.0)); + } + } + _ => {} + } + } + + fn busy(&self) -> bool { + self.drag.is_some() + } +} 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..71f0c1983b 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -215,8 +215,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 @@ -1159,6 +1159,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 +1189,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..47a1dac0e1 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -755,11 +755,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 +819,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/draw2.rs b/crates/tools/src/draw2.rs index 23e61e602c..123082aa25 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -26,10 +26,14 @@ pub use gesture::GestureTool; /// Colour of tool feedback (Illustrator's selection blue). pub const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; -/// The lowest Fidelity (points) the Pencil and Paintbrush take (#3328); the Smooth tool keeps -/// [`SMOOTH_MIN_FIDELITY`]. +/// The lowest Fidelity the Pencil and Paintbrush take (#3328; screen pixels, points for the Blob +/// Brush); the Smooth tool keeps [`SMOOTH_MIN_FIDELITY`]. pub const MIN_FIDELITY: f64 = 0.01; +/// The finest tolerance (points) `path.freehand` fits a Pencil or Paintbrush stroke at: the lowest +/// Fidelity at the highest zoom (64000 %), whose screen pixels the tools send in points (#5729). +pub const MIN_FIT_TOLERANCE: f64 = MIN_FIDELITY / 640.0; + /// The lowest Fidelity (points) the Smooth tool takes. pub const SMOOTH_MIN_FIDELITY: f64 = 0.05; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index fbf0d88ca5..dba48fe2c5 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -66,7 +66,9 @@ pub struct GestureTool { /// Pencil/Paintbrush starting on a selected path away from its ends: (path, Edit Selected /// Paths' distance in points); the stroke redraws the section it ends on (#2850). redraw: Option<(NodeId, f64)>, - /// Fit tolerance in points (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"). + /// Fit tolerance (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"): in screen pixels for the + /// Pencil and the Paintbrush, so a stroke keeps as many points at any zoom (#5729), in points + /// for the others. pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, @@ -453,11 +455,12 @@ impl GestureTool { self.draws_path() && !self.smoothing && !self.straight && self.extend.is_none() && self.redraw.is_none() && self.ends_near_start(cx, end) } - /// Parameters of `path.freehand` for the current stroke. - pub fn freehand_params(&self, closed: bool) -> Value { + /// Parameters of `path.freehand` for the current stroke, fitted at Fidelity on screen. Only the + /// Pencil and the Paintbrush (`draws_path`) send it; the Blob Brush's Fidelity stays in points. + pub fn freehand_params(&self, cx: &ToolContext, closed: bool) -> Value { let mut v = json!({ "points": self.stroke_json(), - "fidelity": self.fidelity, + "fidelity": cx.tol(self.fidelity), "closed": closed, "style": if self.id == "paintbrush" { "brush" } else { "pencil" }, "fill": self.fill, @@ -473,16 +476,17 @@ impl GestureTool { /// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that /// redraws a selected path is shown as it is drawn, joined at its start to the point of the - /// path nearest to it, with no fill, and leaves the path as it is: where the stroke ends is - /// only known at the release, which redraws the path (`finish`). + /// path nearest to it, with no fill, and leaves the path and the selection as they are: where + /// the stroke ends is only known at the release, which redraws the path (`finish`). fn drawing_params(&self, cx: &ToolContext) -> Value { - let mut v = self.freehand_params(false); + let mut v = self.freehand_params(cx, false); let Some((id, _)) = self.redraw else { return v }; if let Some(o) = v.as_object_mut() { o.remove("redraw"); } v["fill"] = json!(false); v["keepSelected"] = json!(false); + v["leaveSelection"] = json!(true); let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3); if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) { pts.insert(0, json!([on.x, on.y])); @@ -513,7 +517,7 @@ impl GestureTool { let near = pts.last().is_some_and(|&end| self.ends_near_start(cx, end)); // A straight line has two points: closing it would draw it back over itself. let closed = !self.straight && ((m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || (self.extend.is_none() && near)); - let mut params = self.freehand_params(closed); + let mut params = self.freehand_params(cx, closed); // A Pencil stroke that continues a selected path and ends on an open end of another // path selected at the press connects the two. let connect = pts.last().and_then(|&end| self.find_end(cx, end, &self.connect_to)); @@ -669,8 +673,8 @@ impl Tool for GestureTool { // With the Pencil's Live preview off a thin line shows instead (`overlays`). if self.previews() && crate::previews_at(self.points.len()) { let mut v = self.drawing_params(cx); - let fidelity = self.fidelity.max(cx.tol(PREVIEW_FIDELITY_PX)); - v["fidelity"] = json!(fidelity); + let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX); + v["fidelity"] = json!(cx.tol(fidelity)); // A preview fitted coarser than the stroke kept is stale (`deactivate`). self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() }; if !self.live_fit { @@ -767,14 +771,14 @@ impl Tool for GestureTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.tip_at = None; } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { let began = self.began; self.tip_at = None; // Drags past the last preview are in the stroke kept, too, with Live curve fitting off the // stroke kept is fitted, and a stroke that redraws a path redraws it (`drawing_params`). let stale = (began && (self.previewed != self.points.len() || !self.live_fit || self.redraw.is_some()) && self.draws_path() && !self.smoothing) - .then(|| Action::Preview("path.freehand".into(), self.freehand_params(false))); + .then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false))); self.snap.clear(); self.active = false; self.near_start = false; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index de93afaae2..a95c20a14d 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -154,7 +154,8 @@ fn pencil_with_live_curve_fitting_off_previews_the_stroke_unfitted() { /// A stroke whose Fidelity is finer than half a screen pixel previews fitted at half a pixel, which /// looks the same at a fraction of the fit's cost (#4565); the release, and another tool chosen -/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. +/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. Fidelity +/// is in screen pixels, so the stroke is fitted in points at Fidelity / zoom (#5729). #[test] fn fine_fidelity_previews_at_half_a_pixel() { let (d, _) = doc_with_rect(); @@ -166,26 +167,83 @@ fn fine_fidelity_previews_at_half_a_pixel() { acts.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect() }; for id in ["pencil", "paintbrush"] { - for (zoom, fidelity, drawn) in [(1.0, 0.01, 0.5), (4.0, 0.01, 0.125), (1.0, 1.5, 1.5)] { + for (zoom, fidelity, drawn, kept) in [(1.0, 0.01, 0.5, 0.01), (4.0, 0.01, 0.125, 0.0025), (1.0, 1.5, 1.5, 1.5), (4.0, 1.5, 0.375, 0.375)] { cx.zoom = zoom; let mut t = GestureTool::new(id); t.set_option("fidelity", &json!(fidelity)); let acts = drag(&mut t, &cx, &stroke, Mods::default()); let (release, during) = acts.split_last().unwrap(); - assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} pt"); - assert_eq!(fidelities(release), [fidelity], "{id} at {zoom}x, {fidelity} pt: the release"); + assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} px"); + assert_eq!(fidelities(release), [kept], "{id} at {zoom}x, {fidelity} px: the release"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); for &(x, y) in &stroke[1..] { t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); } let acts = t.deactivate(&cx); - let kept = if drawn > fidelity { [fidelity].to_vec() } else { vec![] }; - assert_eq!(fidelities(&acts), kept, "{id} at {zoom}x, {fidelity} pt: another tool chosen"); + let stale = if drawn > kept { [kept].to_vec() } else { vec![] }; + assert_eq!(fidelities(&acts), stale, "{id} at {zoom}x, {fidelity} px: another tool chosen"); assert_eq!(acts.last(), Some(&Action::Commit)); } } } +/// #5729: the Pencil's and the Paintbrush's Fidelity is in screen pixels. The same stroke drawn on +/// screen at 1x and at 4x is fitted at the same tolerance on screen, so it keeps as many points +/// whatever the zoom (another tool chosen mid-stroke: `fine_fidelity_previews_at_half_a_pixel`). +#[test] +fn fidelity_is_in_screen_pixels_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let screen = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for id in ["pencil", "paintbrush"] { + let on_screen = |cx: &ToolContext, zoom: f64| { + let pts: Vec<_> = screen.iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, cx, &pts, Mods::default()); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + v["fidelity"].as_f64().unwrap() * zoom + }; + cx.zoom = 1.0; + let at_1 = on_screen(&cx, 1.0); + cx.zoom = 4.0; + let at_4 = on_screen(&cx, 4.0); + assert_eq!(at_1, 1.5, "{id}"); + assert_eq!(at_4, at_1, "{id}: fidelity in screen px at 1x vs 4x"); + } +} + +/// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its +/// stroke, and another tool chosen while it is drawn, send it as set at any zoom. +#[test] +fn blob_brush_fidelity_stays_in_points_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let stroke = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for zoom in [1.0, 4.0] { + cx.zoom = zoom; + let mut t = GestureTool::new("blobBrush"); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let sent: Vec<_> = acts + .concat() + .into_iter() + .filter_map(|a| if let Action::Exec(_, v) | Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }) + .collect(); + assert_eq!(sent, [1.5], "at {zoom}x"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + for &(x, y) in &stroke[1..] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + let acts = t.deactivate(&cx); + assert!(!acts.iter().any(|a| matches!(a, Action::Preview(id, _) if id == "path.freehand")), "at {zoom}x: {acts:?}"); + } +} + /// Keep selected is on by default, and every Pencil and Paintbrush preview sends it. #[test] fn pencil_and_paintbrush_send_keep_selected() { @@ -643,7 +701,7 @@ fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() { let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect(); assert!(!previews.is_empty(), "{acts:?}"); for v in previews { - assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false, "{v}"); + assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}"); assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}"); assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}"); } diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 36947c9314..6fed43337e 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -964,7 +964,14 @@ impl Targets { /// ([`Self::for_move`]) is spaced evenly along an axis that lines up with nothing /// ([`Self::even_spacing`]). Returns the shift and the guides. pub fn snap_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec) { + let (d, ov, _) = self.snap_rects_axes(rects, tol); + (d, ov) + } + + /// [`Self::snap_rects`], also saying which axes (x, y) lined up or were spaced evenly. + pub(crate) fn snap_rects_axes(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec, [bool; 2]) { let (mut d, mut ov, aligned) = self.align_rects(rects, tol); + let mut taken = aligned; if let [r] = rects && !self.boxes.is_empty() { @@ -973,6 +980,7 @@ impl Targets { for (x, lined_up) in [true, false].into_iter().zip(aligned) { if let Some((shift, _)) = self.even_spacing(moved, x, tol).filter(|_| !lined_up) { *(if x { &mut d.x } else { &mut d.y }) += shift; + taken[usize::from(!x)] = true; spaced = true; } } @@ -985,7 +993,7 @@ impl Targets { } } } - (d, ov) + (d, ov, taken) } /// Spacing Guides along the x axis (`x`) or the y axis for the moved rectangle `r`, among the @@ -1088,6 +1096,50 @@ impl Targets { (d, ov, [best_x.is_some(), best_y.is_some()]) } + /// Snap a selection grabbed at `p` and moved as a whole, its bounds now `r`, to the ruler + /// guides: the grabbed point goes into line with a guide running within `tol` of it + /// ([`Self::snap_point`]), and on an axis where none does and that is not `taken` (x, y) + /// already, the edge or centre of `r` nearest a guide running past it within `tol` goes onto it + /// (#5746). Returns the shift, the guides (none when nothing lines up) and whether a guide held + /// the grabbed point. + pub(crate) fn snap_moved_to_rulers(&self, p: Point, r: Option, tol: f64, taken: [bool; 2]) -> (Vec2, Vec, bool) { + let near = |vertical: bool| { + let v = if vertical { p.x } else { p.y }; + self.rulers.iter().any(|g| g.vertical == vertical && (g.pos - v).abs() <= tol && g.line_at(p, tol).is_some()) + }; + let held = [near(true), near(false)]; + let (q, mut ov) = if held.contains(&true) { self.snap_point(p, tol) } else { (p, vec![]) }; + let mut d = q - p; + let Some(r) = r.map(|r| r + d) else { return (d, ov, held.contains(&true)) }; + // The guide upright (`vertical`) or level nearest one of `vs`, running past `r` across. + let nearest = |vertical: bool, vs: [f64; 3]| { + let (c, half) = + if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; + self.rulers + .iter() + .filter(|g| g.vertical == vertical) + .filter_map(|g| g.line_at(c, tol + half)) + .flat_map(|(t, from, _)| vs.into_iter().map(move |v| (t - v, t, from))) + .filter(|(s, ..)| s.abs() <= tol) + .min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())) + }; + let hx = if held[0] || taken[0] { None } else { nearest(true, [r.x0, r.center().x, r.x1]) }; + let hy = if held[1] || taken[1] { None } else { nearest(false, [r.y0, r.center().y, r.y1]) }; + let shift = Vec2::new(hx.map_or(0.0, |h| h.0), hy.map_or(0.0, |h| h.0)); + let (r, lined) = (r + shift, hx.is_some() || hy.is_some()); + d += shift; + if let Some((_, x, from)) = hx { + ov.extend(self.line(Point::new(x, from.y.min(r.y0)), Point::new(x, from.y.max(r.y1)))); + } + if let Some((_, y, from)) = hy { + ov.extend(self.line(Point::new(from.x.min(r.x0), y), Point::new(from.x.max(r.x1), y))); + } + if lined && !held.contains(&true) { + ov.extend(self.label(p + d, "align")); + } + (d, ov, held.contains(&true)) + } + /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for /// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own /// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page 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/params.rs b/crates/tools/src/params.rs index 8c3565ba2a..49a5a9a3c1 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -25,6 +25,9 @@ pub fn stops_json(stops: &[GradientStop]) -> Value { if let Some(n) = &s.swatch { v["swatch"] = json!(n); v["tint"] = json!(s.tint * 100.0); + if let Some(p) = s.plates { + v["plates"] = json!(p); + } } v }) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 572c667e4b..d132763156 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -206,7 +206,7 @@ pub(crate) struct MoveSnap { copy_targets: Option, copy_points: Option, /// With Smart Guides on, the ruler guides View › Snap to Point still pulls the grabbed point - /// onto (#1534); `points` holds them with Smart Guides off. + /// onto (#1534), and lines the bounds up with (#5746); `points` holds them with Smart Guides off. rulers: Option, } @@ -245,6 +245,8 @@ impl MoveSnap { d = q - start; guides = ov; } + // The axes (x, y) Smart Guides already put in line with other art. + let mut taken = [false; 2]; if let (Some(t), Some(b)) = (targets, self.bounds) { // The point the selection was grabbed by, near another object's anchor or centre, // lands on it, rather than the bounds lining up a little beside it (#955). @@ -252,18 +254,26 @@ impl MoveSnap { let (q, ov) = t.snap_point(start + d, cx.snap_tol()); d = q - start; guides = ov; + taken = [true; 2]; } else { - let (adj, ov) = t.snap_rect(b + d, cx.snap_tol()); + let (adj, ov, axes) = t.snap_rects_axes(&[b + d], cx.snap_tol()); d += adj; guides = ov; + taken = axes; } } - // A ruler guide within reach of the grabbed point wins over lining the bounds up. + // A ruler guide within reach of the grabbed point wins over lining the bounds up; on an + // axis without one that Smart Guides left free, the bounds line up with the ruler guides + // (#5746), alongside the Smart Guides. if let Some(t) = &self.rulers { - let (q, ov) = t.snap_point(start + d, cx.tol(cx.snap_tolerance)); - if q != start + d { - d = q - start; - guides = ov; + let (adj, ov, held) = t.snap_moved_to_rulers(start + d, self.bounds.map(|b| b + d), cx.tol(cx.snap_tolerance), taken); + if adj != Vec2::ZERO { + d += adj; + if held { + guides = ov; + } else { + guides.extend(ov); + } } } if cx.snap_to_pixel @@ -369,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. @@ -394,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(), @@ -456,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 @@ -550,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 d9c86240ad..6cacf1c0d6 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -3,11 +3,14 @@ pub mod arrange; pub mod cleanup; pub mod color; +pub mod compounds; +pub mod contour; pub mod document; pub mod enclosing_lasso; pub mod pathtools; pub mod pen; pub mod select; +pub mod shapes; pub mod typetools; use crate::menus::Item; @@ -15,9 +18,12 @@ 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()), + Item::Sub("Compound Shapes", compounds::menu()), + Item::Sub("Contour", contour::menu()), Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Path Precision Tools", pathtools::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/compounds.rs b/crates/ui-egui/src/addons/compounds.rs new file mode 100644 index 0000000000..00336013a8 --- /dev/null +++ b/crates/ui-egui/src/addons/compounds.rs @@ -0,0 +1,19 @@ +//! Compound Shapes in the interface: its submenu (Object › Plug-ins › Compound Shapes) puts Make, +//! Release and Expand Compound Shape (also in the Pathfinder panel's menu) in the menus, and holds the +//! setting that makes the Pathfinder panel's Shape Mode buttons make compound shapes on a click. It +//! acts through `object.compoundShape.*` and `window.pathfinder.compoundShapes`; nothing else +//! about the Pathfinder panel changes. + +use serde_json::{Value, json}; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![ + Item::Cmd("Make Compound Shape", "object.compoundShape.make", json!({})), + Item::Cmd("Release Compound Shape", "object.compoundShape.release", json!({})), + Item::Cmd("Expand Compound Shape", "object.compoundShape.expand", json!({})), + Item::Sep, + Item::Cmd("Shape Mode Buttons Make Compound Shapes", "window.pathfinder.compoundShapes", Value::Null), + ] +} diff --git a/crates/ui-egui/src/addons/contour.rs b/crates/ui-egui/src/addons/contour.rs new file mode 100644 index 0000000000..084a8b98c1 --- /dev/null +++ b/crates/ui-egui/src/addons/contour.rs @@ -0,0 +1,12 @@ +//! The Contour add-on in the interface: its submenu (Object › Plug-ins › Contour), which selects the +//! Contour tool. The Contour bar (`canvas/contour_bar.rs`) shows over the selection while the tool is +//! active. Everything acts through `addon.contour.set` and Expand Appearance. + +use serde_json::json; +use vectorcraft_tools::addons::contour; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![Item::Cmd("Contour Tool", "tool.select", json!({"tool": contour::ID}))] +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2e5306677b..f59984ccdc 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,5 +1,5 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), -//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Divide into +//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into //! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel @@ -8,6 +8,7 @@ pub mod corner; pub mod dashes; +pub mod set_corners; pub mod shape; pub mod shared_edge; @@ -56,6 +57,7 @@ pub fn menu() -> Vec { tool("Measure & Inspect Tool", measure_inspect::ID), tool("Parametric Shape Tool", parametric_shape::ID), Item::Cmd("Corner Tool", corner::COMMAND, json!({})), + Item::Cmd("Set Corners…", set_corners::COMMAND, Value::Null), tool("Slide Anchor Along Path", slide_anchor::ID), Item::Cmd("Shared Edge Merge Tool", shared_edge::COMMAND, json!({})), Item::Sep, diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index dce1363359..36ee1bd1c9 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners -//! the selection holds, and Apply (`addon.pathtools.cornerSet`). +//! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which +//! can also take every other anchor, or only the corners in an angle range). use egui::Ui; use serde_json::{Value, json}; @@ -55,10 +56,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { }); let width = ui.available_width(); let apply = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Apply to Selected Anchors"), width).clicked()).inner; + let dialog = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Set Corners…"), width).clicked()).inner; if let Some(values) = set { run(app, "tool.setOption", json!({ "tool": ID, "values": values })); } if apply { run(app, "addon.pathtools.cornerSet", json!({ "radius": radius, "kind": kind })); } + if dialog { + crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); + } } diff --git a/crates/ui-egui/src/addons/pathtools/set_corners.rs b/crates/ui-egui/src/addons/pathtools/set_corners.rs new file mode 100644 index 0000000000..59ba7035a2 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/set_corners.rs @@ -0,0 +1,150 @@ +//! Set Corners in the interface: its dialog (radius, corner kind, which anchors: all, the +//! odd-numbered or the even-numbered ones, and the range of corner angles to round), which +//! previews on the canvas and runs `addon.pathtools.cornerSet` on OK, one undo step. It opens on +//! the Corner Tool's radius and kind, every corner angle (0° to 180°). + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_tools::addons::corner_tool::{ID, MAX_RADIUS, RADIUS}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.cornerSet"; +pub const KIND: &str = "setCorners"; +/// The corner kinds, as the command names them, and their labels. +const KINDS: [(&str, &str); 3] = [("round", "Round"), ("invertedRound", "Inverted Round"), ("chamfer", "Chamfer")]; +/// Which anchors, as the command's `every` names them, and their labels. +const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered Anchors"), ("even", "Even-Numbered Anchors")]; +const LABEL_W: f32 = 64.0; +const FIELD_W: f32 = 170.0; +const ANGLE_W: f32 = 64.0; +/// The corner angles the command takes (degrees). +const ANGLES: std::ops::RangeInclusive = 0.0..=180.0; + +/// The dialog's fields to start with: the Corner Tool's radius and kind, every anchor, Preview on. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let options = app.session.tool_options_of(ID); + let radius = options["radius"].as_f64().unwrap_or(RADIUS); + let kind = options["kind"].as_str().unwrap_or("round").to_string(); + json!({ "radius": radius, "kind": kind, "every": "all", "minAngle": 0.0, "maxAngle": 180.0, "preview": true }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Set Corners").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + form::length_within(ui, d, "radius", unit, FIELD_W, Some(0.0..=MAX_RADIUS)); + }); + form::choice(ui, d, "kind", tl!("Corner:"), (LABEL_W, FIELD_W), &KINDS); + form::choice(ui, d, "every", tl!("Anchors:"), (LABEL_W, FIELD_W), &EVERY); + // Only the corners whose sides meet at an angle in this range: small for a sharp spike, near + // 180° for a shallow bend. Typing one end past the other moves the other along. + let (min, max) = (d.f64("minAngle", 0.0), d.f64("maxAngle", 180.0)); + widgets::label_row(ui, tl!("Angle:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field_named(ui, "set-corners-min-angle", Some(tl!("Minimum angle")), min, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("minAngle".into(), json!(v)); + if v > max { + d.fields.insert("maxAngle".into(), json!(v)); + } + } + ui.label(tl!("to")); + if let Some(v) = widgets::range_field_named(ui, "set-corners-max-angle", Some(tl!("Maximum angle")), max, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("maxAngle".into(), json!(v)); + if v < min { + d.fields.insert("minAngle".into(), json!(v)); + } + } + }); + form::preview(app, ui, d, "Set Corners", COMMAND, form::params(d)); + false +} + +/// OK: keep the preview (or run the command) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + /// The anchor indices of `id`'s uncut outline with a corner drawn. + fn cut(app: &VectorcraftApp, id: u64) -> Vec { + let doc = &app.session.doc().unwrap().doc; + let lc = LiveCorners::of(doc.node(NodeId(id)).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() + } + + #[test] + fn set_corners_opens_from_the_menu_previews_odd_anchors_and_commits_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}, {"x": -50, "y": 50}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Set Corners…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Set Corners", "Radius:", "Corner:", "Anchors:", "All Anchors", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(cut(&app, id), vec![0, 1, 2, 3, 4], "all previewed"); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("every".into(), json!("odd")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("Odd-Numbered Anchors"), "{shown}"); + assert_eq!(cut(&app, id), vec![0, 2, 4], "odd previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(cut(&app, id), Vec::::new(), "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("every".into(), json!("even")); + d.fields.insert("radius".into(), json!(6)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![1, 3]); + } + + #[test] + fn set_corners_previews_only_the_corners_in_its_angle_range() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // A house: square corners at 0, 1 and 3, the roof's 135° corners at 2 and 4. + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 50, "y": 150}, {"x": 0, "y": 100}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + menus::invoke(&mut app, super::COMMAND, json!({})); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Angle:", "to", "0°", "180°"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let n = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("minAngle".into(), json!(120)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![2, 4], "the roof previewed"); + app.ui.dialog.as_mut().unwrap().fields.insert("maxAngle".into(), json!(100)); + app.ui.dialog.as_mut().unwrap().fields.insert("minAngle".into(), json!(80)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![0, 1, 3], "the square corners previewed"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![0, 1, 3]); + } +} 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/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index f9bfa3ca36..859c69fa3d 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -34,9 +34,18 @@ const SEEDS: u64 = 1_000_000; const LABEL_W: f32 = 90.0; const FIELD_W: f32 = 90.0; +/// Release Type on a Path's command. Its menu item opens the generic command dialog +/// (`ui.paramDialog`) on these options, with a Preview (`dialogs::command`). +pub const RELEASE: &str = "addon.type.releasePath"; +/// Release Type on a Path › Keep: what the command's `mode` takes, by name. +pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path Only", "path"), ("Text Only", "text")]; + /// Object › Plug-ins › Type Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Text Tweaker…", COMMAND, Value::Null)] + vec![ + Item::Cmd("Text Tweaker…", COMMAND, Value::Null), + Item::Cmd("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})), + ] } /// The attribute row of param `key` (the first, Font Size, for an unknown one). diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs index 36e3ef2f31..e7118de082 100644 --- a/crates/ui-egui/src/addons/typetools/tests.rs +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -60,3 +60,69 @@ fn another_attribute_starts_from_its_own_values() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.fields["from"].clone(), d.fields["to"].clone()), (json!(0.0), json!(30.0))); } + +/// The kind of object `id` is, and whether it is type on a path. +fn on_path(app: &VectorcraftApp, id: NodeId) -> Option { + match &app.session.doc().unwrap().doc.node(id)?.kind { + NodeKind::Text(t) => Some(matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })), + _ => None, + } +} + +/// #5532: Object › Plug-ins › Type Tools › Release Type on a Path… opens the command dialog on +/// Text and Path, Keep Original off, with Preview off. With Preview on the canvas shows the +/// release while the dialog is open; Cancel puts the type back with no step of history, and OK +/// keeps it as one step. +#[test] +fn release_type_on_a_path_previews_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let path = app.run("path.create", json!({"d": "M100 200 C200 100 400 100 500 200"})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Release me"})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Type Tools"] && e.label == "Release Type on a Path…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::RELEASE.to_string(), "Release Type on a Path".to_string())); + assert_eq!((d.str("mode"), d.bool("keepOriginal"), d.bool("preview")), ("both".to_string(), false, false)); + assert!(crate::dialogs::accepts_field(d, "preview")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Release Type on a Path", "Mode:", "Text and Path", "Keep Original", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(on_path(&app, id), Some(true), "no preview without the checkbox"); + + // Preview on: the type is released on the canvas; another mode replaces that preview. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), Some(false), "previewed as point type"); + app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("path")); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), None, "path only: the type is gone in the preview"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel restores the type"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step, the released objects selected. + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(on_path(&app, id), Some(false)); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "the path and the text are selected"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, start); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7826cdfe32..4698856dfd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -54,11 +54,13 @@ impl VectorcraftApp { // ([`place::place_from_cursor`]). session.place_cursor_requests = true; let views = session.documents().iter().map(View::of).collect(); + let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); Self { session, ui: UiState::default(), views, + view_uids, services, canvas: CanvasCache { renderer: vectorcraft_render::Renderer::new(), @@ -102,6 +104,8 @@ impl VectorcraftApp { clipboard_publishing: Default::default(), pending_url: None, control_rx: None, + deferred_control: None, + synthetic_dropped_before: 0, pending_screenshots: vec![], queued_screenshots: vec![], screenshot_token: 0, @@ -192,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)))); } @@ -276,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 @@ -311,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 bbdf60befc..2f64432821 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -9,7 +9,30 @@ impl VectorcraftApp { let Some(rx) = self.control_rx.take() else { return }; let mut handled = 0; while handled < control::MAX_CONTROL_REQUESTS_PER_FRAME { - let Ok(req) = rx.try_recv() else { break }; + let Some(req) = self.deferred_control.take().or_else(|| rx.try_recv().ok()) else { break }; + // 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; + } // Its caller stopped waiting (the app was busy or its window not drawn for too long) // and was told it won't run: an edit applied now would come from nowhere (#1725). if !req.claim() { 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 6b5db4fb5b..9895149917 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -4,13 +4,29 @@ impl VectorcraftApp { /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and /// 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 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.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() + .map(|d| { + self.view_uids.iter().position(|u| *u == d.uid).and_then(|k| old.get_mut(k)).and_then(Option::take).unwrap_or_else(|| View::of(d)) + }) + .collect(); + } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); for (view, doc) in self.views.iter_mut().zip(docs) { 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 06a9f488d3..f99c524f12 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -17,6 +17,7 @@ use crate::{CacheKey, VectorcraftApp, now_ms, widgets}; mod artboards; mod context; +mod contour_bar; mod cursor; mod drag; mod fill; @@ -360,6 +361,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.task_bar && !revolve_edit && !dragging && app.ui.screen_mode < 3 && !strip { task_bar(app, ui, &xf); } + if app.ui.screen_mode < 3 { + contour_bar::contour_bar(app, ui, &xf); + } if app.ui.screen_mode < 3 { crate::free_transform::show(app, ui, xf.rect); } @@ -460,11 +464,12 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin } Some(hp) if custom - && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused)) + && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused), app.services.no_cursor_theme) && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => { - // No cursor theme (Wayland): the glyph is painted, the system pointer stays (#2450). - if crate::cursors::hide_system_pointer(app.services.no_cursor_theme) { egui::CursorIcon::None } else { cursor_icon(c) } + // The painted glyph stands in for the hidden system pointer. Without a cursor theme + // (Wayland) none is painted: the system pointer can't be hidden there (#2450). + egui::CursorIcon::None } _ => cursor_icon(c), } diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs new file mode 100644 index 0000000000..4b560eeba6 --- /dev/null +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -0,0 +1,133 @@ +//! The Contour bar: a floating bar above the selection while the Contour tool is active. It has the +//! Contour's distance in a number box, its corner style (Sharp, Round or Square) and Bake, which +//! turns the live Contour into plain paths. It acts through `addon.contour.set` and +//! `effect.expandAppearance`, so everything it does is a command with its own undo step. + +use serde_json::Value; +use vectorcraft_doc::{Node, NodeKind}; + +use super::{CornerRadius, Stroke, Tokens, Ui, VectorcraftApp, Xf, json, pos2, vec2}; + +/// The live effect a Contour is made of. +const EFFECT: &str = "path.offsetPath"; + +fn bar_id() -> egui::Id { + egui::Id::unique("contour-bar") +} + +/// Where the Contour bar was last drawn (none while it isn't shown). +#[cfg(test)] +pub(super) fn bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// A selected Contour's distance and corner style, read from its Offset Path effect. +struct Standing { + offset: f64, + corners: &'static str, +} + +fn standing(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let offset = e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0); + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + Some(Standing { offset, corners }) +} + +/// The Contour bar, over the selection's top edge (under it when the top is off the canvas). +pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + if app.session.tool_id() != "contour" { + return; + } + let Some(b) = app.selection_bounds() else { return }; + let Some(st) = app.session.active() else { return }; + let shapes: Vec<&Node> = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect(); + if shapes.is_empty() { + return; + } + let stand = shapes.first().and_then(|n| standing(n)); + drop(shapes); + let tool_corners = app.session.tool_options().get("corners").and_then(Value::as_str).unwrap_or("sharp").to_string(); + let corners = stand.as_ref().map_or(tool_corners.as_str(), |s| s.corners); + let shown = stand.as_ref().map_or(0.0, |s| s.offset); + // A grown Contour reaches past the outline it was made from: keep the bar clear of it. + let b = b.inflate(shown.max(0.0), shown.max(0.0)); + + let t = Tokens::get(ui.ctx()); + let quad = xf.quad(b); + let top = quad.iter().map(|c| c.y).fold(f32::INFINITY, f32::min); + let bottom = quad.iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); + let size = egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size).unwrap_or(vec2(330.0, 40.0)); + let area = xf.rect.shrink(8.0); + let above = top - size.y - 12.0; + let y = if above >= area.top() { above } else { bottom + 12.0 }; + let at = pos2(xf.to_screen(b.center()).x - size.x / 2.0, y); + let at = at.clamp(area.min, (area.max - size).max(area.min)); + + let mut run: Option<(&str, Value)> = None; + let mut corner_pick: Option<&str> = None; + egui::Area::new(bar_id()).order(egui::Order::Middle).fixed_pos(at).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: egui::Color32::from_black_alpha(70) }) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(egui::RichText::new(tl!("Contour")).color(t.text_strong)); + // The distance: a drag or typed value is applied when it ends, as one step. + let key = egui::Id::unique("contour-bar-offset"); + let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or(shown); + let resp = ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt")); + if resp.dragged() || resp.has_focus() { + ui.data_mut(|d| d.insert_temp(key, v)); + } + if resp.drag_stopped() || resp.lost_focus() { + ui.data_mut(|d| d.remove_temp::(key)); + if (v - shown).abs() > 1e-9 { + run = Some(("addon.contour.set", json!({"offset": v, "corners": corners}))); + } + } + for (label, id) in [(tl!("Sharp"), "sharp"), (tl!("Round"), "round"), (tl!("Square"), "square")] { + if ui.selectable_label(corners == id, label).clicked() { + corner_pick = Some(id); + } + } + let bake = ui.add_enabled(stand.is_some(), egui::Button::new(tl!("Bake"))); + if bake.on_hover_text(tl!("Turn the Contour into plain paths")).clicked() { + run = Some(("effect.expandAppearance", json!({}))); + } + }); + }); + }); + if let Some(id) = corner_pick { + // The tool keeps the style for the next Contour; a selected Contour changes now. + let mut result = app.run("tool.setOption", json!({"key": "corners", "value": id})); + if result.is_ok() + && let Some(s) = &stand + { + result = app.run("addon.contour.set", json!({"offset": s.offset, "corners": id})); + } + if let Err(e) = result { + app.ui.status = e; + } + } + if let Some((cmd, params)) = run + && let Err(e) = app.run(cmd, params) + { + app.ui.status = e; + } +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b98e186481..d2b2bcfb68 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -90,12 +90,17 @@ 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(); + let show_box = (app.session.tool_id() == "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 +255,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 +293,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/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e6579d8f31..b5f8dac668 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -48,7 +48,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let Some(b) = (if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }) else { return }; let Some(st) = app.session.active() else { return }; let n = st.selection.len(); - let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let is_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { .. })); let is_image = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Image(_))); let is_clip_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { clip: true, .. })); @@ -72,13 +72,15 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Selection tool: its properties take the place of Lock, as in the reference app // (). use vectorcraft_doc::LiveShape; - let shape = first.clone().filter(|f| { - n == 1 - && st.selection.anchors.is_empty() - && app.session.tool_id() == "selection" - && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } - if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) - }); + let shape = first + .filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }) + .cloned(); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index edfeebca41..cf8d3635ba 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 { @@ -8988,3 +9124,77 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra assert_eq!(set_count, 1, "settled frame 10 is uploaded to texture"); assert_eq!(app.canvas.key.as_ref().unwrap().revision, 10, "settled frame 10 is uploaded"); } + +/// The labels the Contour bar draws in a headless frame, with their rects; none while it isn't +/// shown. +fn contour_bar_labels(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { + egui_extras::install_image_loaders(ctx); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let Some(bar) = contour_bar::bar_rect(ctx) else { return vec![] }; + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) if bar.contains(t.visual_bounding_rect().center()) => Some((t.galley.text().to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect() +} + +/// A click on the centre of the label `name` of the Contour bar, laid out by one frame before it. +fn click_contour_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let labels = contour_bar_labels(app, ctx, vec![]); + let at = labels.iter().find(|(t, _)| t == name).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{name}` in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + contour_bar_labels(app, ctx, vec![egui::Event::PointerMoved(at)]); + contour_bar_labels(app, ctx, vec![button(true), button(false)]); +} + +/// The Contour bar shows with the Contour tool and a shape selected: Sharp, Round and Square set the +/// corner style (of a selected Contour at once, else of the next one), and Bake turns a Contour into +/// plain paths. +#[test] +fn the_contour_bar_sets_corners_and_bakes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + + // Only the Contour tool shows it. + app.select_tool("selection"); + assert!(contour_bar_labels(&mut app, &ctx, vec![]).is_empty()); + app.select_tool("contour"); + contour_bar_labels(&mut app, &ctx, vec![]); + let names: Vec = contour_bar_labels(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for want in ["Contour", "Sharp", "Round", "Square", "Bake"] { + assert!(names.iter().any(|n| n == want), "{want} in {names:?}"); + } + let offsets = |app: &VectorcraftApp| { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(e) = n.appearance.effects.iter().find(|e| e.id == "path.offsetPath") { + found.push(e.params["joins"].as_str().unwrap_or_default().to_string()); + } + }); + found + }; + + // No Contour yet: Round is kept for the next one, and Bake does nothing. + let steps = app.session.active().unwrap().history.undo.len(); + click_contour_bar(&mut app, &ctx, "Round"); + assert_eq!(app.session.tool_options()["corners"], json!("round")); + click_contour_bar(&mut app, &ctx, "Bake"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "nothing to bake"); + assert!(offsets(&app).is_empty()); + + // A Contour made now has round corners; Square changes the selected Contour in place. + app.session.execute("addon.contour.set", &json!({"offset": 8, "corners": "round"})).unwrap(); + assert_eq!(offsets(&app), ["round"]); + click_contour_bar(&mut app, &ctx, "Square"); + assert_eq!(offsets(&app), ["bevel"], "the selected Contour changed, none was added"); + + // Bake: the live effect is gone and the art stays. + click_contour_bar(&mut app, &ctx, "Bake"); + assert!(offsets(&app).is_empty(), "baked"); +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index eecaa22fd3..41d73ffaef 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -28,7 +28,7 @@ pub use status_bar::status_bar; #[cfg(test)] use status_bar::{StatusReadoutWidths, status_readouts}; #[cfg(test)] -use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; +use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index df58c1be7a..018a4e2d94 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -203,9 +203,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let sel = st.selection.objects.clone(); let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = sel.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); - let label = match &first { + let label = match first { _ if app.session.tool_id() == "artboard" => tl!("Artboard"), Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { tl!("Anchor Point") @@ -222,6 +222,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } _ => tl!(crate::panels::appearance::object_label(app)), }; + let has_first = first.is_some(); ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text)); // With the Artboard tool in use, the bar shows the active artboard's controls in place // of the object controls. @@ -238,7 +239,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::toolbar::control_bar_options(app, ui); crate::dialogs::envelope::control_bar(app, ui); crate::panels::symbols::control_bar(app, ui); - let opacity = if first.is_some() { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; + let opacity = if has_first { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; if !image { let shown_stroke = crate::panels::current_stroke(app); let mixed = crate::panels::stroke_mixed(app, ui.ctx()); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index d81e2fb973..4d5f75821b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -79,6 +79,40 @@ fn tear_off(ui: &Ui, resp: &egui::Response, strip: egui::Rect) -> Option Vec<(usize, egui::Rangef)> { + let mut groups: Vec<(usize, egui::Rangef)> = vec![]; + for &(i, r) in slots { + match groups.last_mut() { + Some((d, span)) if *d == i => span.max = span.max.max(r.right()), + _ => groups.push((i, egui::Rangef::new(r.left(), r.right()))), + } + } + groups +} + +/// Where document `from`'s tabs, dragged along the strip to `x`, go among the other documents' +/// tabs in `groups` ([`tab_groups`]): before the first whose middle is right of `x`, else after +/// the last. → the document's new index among all the open documents (floating ones and those +/// whose tabs don't fit included) and the x of the gap the drop goes in; `None` when the drop +/// leaves the document where it is, or there is no other tab to drop beside. +pub(super) fn tab_drop(groups: &[(usize, egui::Rangef)], from: usize, x: f32) -> Option<(usize, f32)> { + let others: Vec<&(usize, egui::Rangef)> = groups.iter().filter(|(d, _)| *d != from).collect(); + let slot = others.iter().filter(|(_, span)| span.center() < x).count(); + let (to, gap) = match others.get(slot) { + // Before document `d`: it shifts left by one when `from` was before it. + Some(&&(d, span)) => (if from < d { d - 1 } else { d }, span.min), + // After the last tab shown. + None => { + let &&(d, span) = others.last()?; + (if from < d { d } else { d + 1 }, span.max) + } + }; + (to != from).then_some((to, gap)) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -100,7 +134,9 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] -/// above or below the strip floats its view in a window under the pointer. +/// above or below the strip floats its view in a window under the pointer; one dragged along the +/// strip moves its document among the others (`document.move`, #5663), a line marking where it +/// will go. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -133,6 +169,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut close = None; let mut float = None; let mut hovering_art = false; + // The tabs shown, by document and rect, and the document whose tab is dragged (and whether + // the drag just ended), for moving it along the strip. + let mut slots: Vec<(usize, egui::Rect)> = vec![]; + let mut dragged = None; for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { if x + w > strip.left() + room && Some(k) != active { break; @@ -142,6 +182,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag()); + slots.push((i, r)); + if resp.dragged() || resp.drag_stopped() { + dragged = Some((i, resp.drag_stopped())); + } if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -166,6 +210,25 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); + // A tab dragged along the strip (not off it, which floats it) moves its document: a line marks + // the gap it goes in, and the release moves it there. Artwork dragged over the tabs never does. + let mut reorder = None; + if let Some((from, released)) = dragged + && !crate::document_drag::carrying_artwork(ui.ctx()) + && let Some(p) = ui.input(|i| i.pointer.interact_pos().or(i.pointer.latest_pos())) + && !crate::doc_windows::torn_off(strip, p) + { + let drop = tab_drop(&tab_groups(&slots), from, p.x); + if released { + reorder = drop.map(|(to, _)| (from, to)); + } else { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if let Some((_, gap)) = drop { + let gap = gap.clamp(strip.left() + 1.0, strip.right() - 1.0); + ui.painter().vline(gap, strip.y_range().shrink(4.0), Stroke::new(2.0, t.accent)); + } + } + } // The » button: every window, floating ones included, the current one checked. The list // scrolls once it reaches the bottom of the window, so every document of a large session stays // reachable (#4017). @@ -197,6 +260,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "view": n, "at": [at.x, at.y]})) { app.status(e); } + } else if let Some((from, to)) = reorder { + if let Err(e) = app.run("document.move", json!({"from": from, "to": to})) { + app.status(e); + } } else if let Some(w) = activate { crate::doc_windows::show_window(app, w); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index c9109a17fc..710f3ba0c0 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -7,6 +7,56 @@ fn the_active_tab_stays_in_view() { assert_eq!(super::first_tab_shown(&widths, None, 350.0), 0); assert_eq!(super::first_tab_shown(&widths, Some(4), 50.0), 4, "a tab wider than the room still shows"); } + +/// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). +fn slots(docs: &[usize]) -> Vec<(usize, egui::Rect)> { + docs.iter().enumerate().map(|(k, &d)| (d, egui::Rect::from_min_size(egui::pos2(k as f32 * 100.0, 0.0), egui::vec2(100.0, 30.0)))).collect() +} + +/// A document's view tabs make one group, which moves as one (#5663). +#[test] +fn a_documents_view_tabs_make_one_group() { + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + let spans: Vec<(usize, f32, f32)> = groups.iter().map(|(d, s)| (*d, s.min, s.max)).collect(); + assert_eq!(spans, vec![(0, 0.0, 100.0), (1, 100.0, 300.0), (2, 300.0, 400.0)]); + assert!(super::tab_groups(&[]).is_empty()); +} + +/// A dragged tab drops past the middles of the tabs it crossed, as an index among all the open +/// documents (#5663). +#[test] +fn a_dragged_tab_drops_past_the_middles_it_crossed() { + let groups = super::tab_groups(&slots(&[0, 1, 2, 3])); + let drop = |from, x| super::tab_drop(&groups, from, x); + assert_eq!(drop(0, 40.0), None, "still over itself"); + assert_eq!(drop(0, 140.0), None, "not yet past the next tab's middle"); + assert_eq!(drop(0, 160.0), Some((1, 200.0)), "past the second tab's middle: between it and the third"); + assert_eq!(drop(0, 900.0), Some((3, 400.0)), "past the end: last"); + assert_eq!(drop(3, -50.0), Some((0, 0.0)), "before the start: first"); + assert_eq!(drop(3, 120.0), Some((1, 100.0)), "between the first two"); + assert_eq!(drop(2, 260.0), None, "between its neighbours: where it is"); + assert_eq!(super::tab_drop(&super::tab_groups(&slots(&[0])), 0, 500.0), None, "no other tab"); + assert_eq!(super::tab_drop(&[], 0, 500.0), None); +} + +/// Documents without a tab on the strip (floating, or past its end) keep their places in the +/// documents' order; the drop names an index among all of them (#5663). +#[test] +fn a_drop_counts_the_documents_the_strip_does_not_show() { + // Documents 0, 2 and 5 have tabs; 1, 3 and 4 float. + let groups = super::tab_groups(&slots(&[0, 2, 5])); + let drop = |from, x| super::tab_drop(&groups, from, x).map(|(to, _)| to); + assert_eq!(drop(0, 260.0), Some(5), "after document 5: last, as 0 leaves its place"); + assert_eq!(drop(0, 160.0), Some(4), "between 2 and 5: just before 5, which is index 4 once 0 has left its place"); + assert_eq!(drop(5, -10.0), Some(0), "before document 0"); + assert_eq!(drop(5, 60.0), Some(2), "before document 2: index 2, the floating document 1 stays before it"); + assert_eq!(drop(2, 260.0), Some(5), "after document 5"); + // With view tabs: document 1 has two, side by side; it moves as one. + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + assert_eq!(super::tab_drop(&groups, 1, 20.0), Some((0, 0.0)), "both views' document goes first"); + assert_eq!(super::tab_drop(&groups, 0, 220.0), Some((1, 300.0)), "past document 1's middle, which both its tabs span"); + assert_eq!(super::tab_drop(&groups, 0, 190.0), None, "not yet past it"); +} use std::sync::Arc; use super::{StatusReadoutWidths, status_readouts}; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d25a08f94d..fccfbedab5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -10,7 +10,8 @@ //! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened //! - `ui.tool.select {tool}`, `ui.tool.list` //! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: -//! drive the active tool through the same path as the mouse +//! drive the active tool through the same path as the mouse, after the synthetic input sent +//! before it was applied //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input //! - `ui.move {x, y}` / `ui.click {x, y, button?, count?, shift?…}` / `ui.drag {x, y, toX, toY, steps?}`: //! real egui pointer input in screen points (reaches every widget: panels, flyouts, dialogs) @@ -33,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}; @@ -100,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; @@ -123,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. @@ -131,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() @@ -539,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, @@ -565,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/cursors.rs b/crates/ui-egui/src/cursors.rs index 44377a2c84..eda747fc8f 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -702,23 +702,17 @@ pub fn os_cursors(build: bool, wayland: bool) -> bool { build && !wayland } -/// Does the canvas hide the system pointer to show a painted tool glyph alone? Not when there is no -/// cursor theme on Wayland ([`crate::Services::no_cursor_theme`]): winit sets no pointer then, and a -/// hidden one would not come back over the panels (#2450). The system pointer stays beside the glyph. -pub fn hide_system_pointer(no_cursor_theme: bool) -> bool { - !no_cursor_theme -} - /// Does the window hide the pointer only while it is the key window? macOS does: winit hides it with /// a cursor rect holding a transparent cursor, and macOS applies the rect only in the key window. /// Over a window behind another app or under a sheet, the system pointer shows (#2020). pub const HIDES_ONLY_WHEN_KEY: bool = cfg!(target_os = "macos"); -/// Does the window paint the glyphs over a hidden pointer, `focused` or not? Not where the system -/// shows its pointer over a window without the focus ([`HIDES_ONLY_WHEN_KEY`]): the system pointer -/// shows alone there. -pub fn paint_glyphs(hides_only_when_key: bool, focused: bool) -> bool { - focused || !hides_only_when_key +/// Does the window paint a glyph over a hidden pointer? Not where it cannot hide the system pointer +/// (no cursor theme on Wayland, [`crate::Services::no_cursor_theme`]: winit sets no pointer then, +/// and a hidden one would not come back over the panels, #2450), or where the system shows its pointer without the focus +/// ([`HIDES_ONLY_WHEN_KEY`]): the system pointer shows alone there. +pub fn paint_glyphs(hides_only_when_key: bool, focused: bool, no_cursor_theme: bool) -> bool { + !no_cursor_theme && (focused || !hides_only_when_key) } /// The cursor bitmaps handed to the OS, by (cursor, pixels per point): each glyph is rasterized diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index ece8895b44..e70f7d488a 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -387,8 +387,6 @@ fn a_wayland_window_paints_the_tool_cursor() { /// Without a cursor theme the canvas keeps the system pointer visible (#2450). #[test] fn no_cursor_theme_keeps_the_system_pointer() { - assert!(!hide_system_pointer(true)); - assert!(hide_system_pointer(false)); let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, no_cursor_theme: true, ..Default::default() }); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = egui::Context::default(); @@ -472,9 +470,10 @@ fn wayland_windows_paint_the_glyphs() { #[test] fn macos_windows_paint_the_glyphs_only_with_the_focus() { - assert!(paint_glyphs(true, true), "macOS with the focus"); - assert!(!paint_glyphs(true, false), "macOS without the focus: the system pointer shows (#2020)"); - assert!(paint_glyphs(false, true) && paint_glyphs(false, false), "Wayland, the web: painted with the focus or without"); + assert!(paint_glyphs(true, true, false), "macOS with the focus"); + assert!(!paint_glyphs(true, false, false), "macOS without the focus: the system pointer shows (#2020)"); + assert!(paint_glyphs(false, true, false) && paint_glyphs(false, false, false), "Wayland, the web: painted with the focus or without"); + assert!(!paint_glyphs(false, true, true), "without a cursor theme, use the system pointer alone"); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 099d6db583..c0f900f67c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -211,6 +211,9 @@ pub(crate) struct DialogSpec { pub ok_label: Option &'static str>, /// Can OK (or Enter) apply the dialog as it is? None: always. The body says why not. pub ok_enabled: Option bool>, + /// What a dialog draws at the left end of its button row, level with the buttons, instead of + /// in its body (Transform Each's Preview checkbox). + pub footer_left: Option, } impl DialogSpec { @@ -240,6 +243,7 @@ impl DialogSpec { passes: |_, _| false, ok_label: None, ok_enabled: None, + footer_left: None, }; /// A dialog that draws its own window and confirms through its module. @@ -413,10 +417,12 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, 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), } @@ -504,10 +510,14 @@ pub(crate) fn parent(d: &Dialog) -> Option { } /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), and a change +/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog. +/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { + transform_each::field_set(app, field, old); + return Ok(()); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), @@ -719,6 +729,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space(28.0); discard = widgets::secondary_button(ui, label).clicked(); } + // The row runs right to left: a left-to-right layout in the room left of the buttons + // puts its control at the row's left end. + if let Some(left) = spec.footer_left { + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| left(ui, &mut d)); + } }); }); let rejected = ctx.data_mut(|d| d.remove_temp::(widgets::dialog_reject_commit_flag())).unwrap_or(false); 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/command.rs b/crates/ui-egui/src/dialogs/command.rs index 2dc8efd064..0a722cbcf8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -21,7 +21,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { // Area Type Options: a Row Gutter still as it opened, on rows without a gutter of their own, // follows the Gutter as it is changed. let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter"); - form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &rank, app.session.general_unit()); + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); + let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); + form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); if linked && d.fields.get("rowGutter") == d.fields.get("__rowGutterLinked") && let Some(g) = d.fields.get("gutter").cloned() @@ -61,12 +63,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does -/// too (#5360), as public tutorials of the dialog show. (Cancel rolls a preview back whichever -/// dialog started it.) +/// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path +/// works the same way (#5532). (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), - "type.pathOptions" => true, + "type.pathOptions" | crate::addons::typetools::RELEASE => true, _ => false, } } @@ -114,6 +116,7 @@ fn order(command: &str) -> &'static [&'static str] { // The public Trap options' order. "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], + crate::addons::typetools::RELEASE => &["mode", "keepOriginal"], _ => &[], } } @@ -123,6 +126,7 @@ fn choices(command: &str, key: &str) -> Option { match (command, key) { ("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS), ("type.pathOptions", "alignToPath") => Some(PATH_ALIGN), + (crate::addons::typetools::RELEASE, "mode") => Some(crate::addons::typetools::RELEASE_MODES), ("text.areaOptions", "fit") => Some(AREA_FIT), ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), @@ -136,6 +140,19 @@ fn choices(command: &str, key: &str) -> Option { } } +/// Object › Rasterize › Color Model: the values `object.rasterize` takes, the document's own +/// colour model first (#5660). +fn rasterize_color_models(command: &str, key: &str, cmyk: bool) -> Option { + match (command, key) { + ("object.rasterize", "colorModel") => Some(if cmyk { RASTERIZE_CMYK } else { RASTERIZE_RGB }), + _ => None, + } +} + +/// Object › Rasterize › Color Model in an RGB and in a CMYK document. +const RASTERIZE_RGB: form::Choices = &[("RGB", "rgb"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; +const RASTERIZE_CMYK: form::Choices = &[("CMYK", "cmyk"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; + /// Type on a Path Options › Align to Path. const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")]; @@ -285,6 +302,61 @@ mod tests { assert_eq!(t.area.flow, vectorcraft_doc::TextFlow::Rows); } + /// Object › Rasterize › Color Model is a dropdown of the models `object.rasterize` takes, the + /// document's own first (#5660): every value runs, and picking Grayscale rasterizes in grays. + #[test] + fn rasterize_color_model_is_a_dropdown_of_the_models_the_command_takes() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + for (mode, own) in [("rgb", "RGB"), ("cmyk", "CMYK")] { + let models = rasterize_color_models("object.rasterize", "colorModel", mode == "cmyk").unwrap(); + assert_eq!(models.first(), Some(&(own, mode)), "the document's own model first"); + for (_, value) in models { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": mode})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72, "colorModel": value})).unwrap_or_else(|e| panic!("{mode} {value}: {e}")); + } + } + assert!(rasterize_color_models("object.rasterize", "background", false).is_none()); + assert!(rasterize_color_models("document.rasterEffectsSettings", "colorModel", false).is_none()); + let mut app = VectorcraftApp::new(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": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, "object.rasterize", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "rgb"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + assert!(h.query_by_role_and_label(Role::TextInput, "Color Model:").is_none(), "not a text field"); + h.get_by_role_and_label(Role::ComboBox, "Color Model:").click(); + h.run_steps(3); + h.get_by_label("Grayscale").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().str("colorModel"), "grayscale"); + let app = h.state_mut(); + crate::dialogs::confirm(app).unwrap(); + let st = app.session.active().unwrap(); + let key = st.selection.objects.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(i)) => Some(i.key.clone()), + _ => None, + }); + let img = image::load_from_memory(&st.doc.images[&key.expect("the rectangle became an image")].bytes).unwrap().to_rgba8(); + let p = img.get_pixel(img.width() / 2, img.height() / 2).0; + assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); + } + /// Graph Type › Value Axis is a dropdown of the values `graph.setType` takes, and OK puts the /// value axis on the side picked. #[test] 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 004a964903..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; @@ -64,6 +65,24 @@ pub(crate) fn length_within( true } +/// [`length_within`] for a value the selected objects may not share: with no value the field reads +/// `empty` ("Mixed"), and typing a distance sets it. +pub(crate) fn length_mixed( + ui: &mut egui::Ui, + d: &mut Dialog, + key: &str, + unit: Unit, + width: f32, + range: Option>, + empty: &str, +) -> bool { + let value = d.fields.contains_key(key).then(|| d.f64(key, 0.0)); + let bounds = range.unwrap_or(crate::widgets::ANY); + let Some(v) = crate::widgets::num_field_within_empty(ui, ("dlg-len", key), value, empty, unit, width, bounds) else { return false }; + d.fields.insert(key.into(), json!(v)); + true +} + /// What [`length`] shows for `d.fields[key]`, as the screen-reader value of a rail over `range` /// (in points) beside it: the number in `unit` and the field's text. `None` while the field is /// blank. @@ -150,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() @@ -385,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(); @@ -409,6 +449,16 @@ pub(super) fn param_fields( changed |= length_within(ui, d, &k, unit, 140.0, range); return; } + // A size in pixels of the raster effects resolution (Color Halftone's Max Radius) + // stays in pixels whatever the document's units, within its documented range. + if let Some(range) = vectorcraft_effects::raster_px_range(&d.str("__effect"), &k) { + let x = v.as_f64().unwrap_or(*range.start()); + if let Some(x) = crate::widgets::range_field_named(ui, ("fx-px", &k), None, x, range, &unit_suffix("px"), 2, 140.0) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + return; + } if let Some(options) = choices(&k) { let cur = v.as_str().unwrap_or_default(); let label = options.iter().find(|(_, value)| *value == cur).map_or(cur, |(l, _)| choice_label(l)); @@ -452,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 => { @@ -475,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 } @@ -883,15 +960,30 @@ pub(super) fn preview_result( cmd: &str, params: Value, ) -> Option { - const LAST: &str = PREVIEWED; ui.add_space(8.0); - let mut on = d.bool("preview"); + preview_check(ui, d); + preview_or_rollback(app, d, label, cmd, params) +} + +/// The Preview checkbox (field `preview`), for a dialog that draws it in its button row +/// (`DialogSpec::footer_left`) instead of through [`preview`]. +pub(crate) fn preview_check(ui: &mut egui::Ui, d: &mut Dialog) { + let on = d.bool("preview"); if crate::widgets::check(ui, tl!("Preview"), on, true) { - on = !on; - d.fields.insert("preview".into(), json!(on)); + d.fields.insert("preview".into(), json!(!on)); } - if !on { - if d.fields.remove(LAST).is_some() { +} + +/// [`preview`] without its checkbox, which the dialog draws itself ([`preview_check`]): the preview +/// runs while the field is on and rolls back when it is off. +pub(crate) fn preview_without_check(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) { + let _ = preview_or_rollback(app, d, label, cmd, params); +} + +/// [`preview_now`] while Preview is on; off, it rolls the preview back. +fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { + if !d.bool("preview") { + if d.fields.remove(PREVIEWED).is_some() { let _ = app.session.cancel_interaction(); } return None; diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 7660287753..f2eb124776 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -3,7 +3,8 @@ //! preferences. OK sets them with `tool.setOption {tool, values}`. The Pencil also has `liveFit` //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! -//! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush, Smooth and Blob Brush), `fill` (Pencil and +//! Fields: `tool`; `fidelity` (screen pixels for the Pencil and Paintbrush, points for Smooth and +//! Blob Brush), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows @@ -166,16 +167,19 @@ fn blob_size(ui: &mut egui::Ui, d: &mut Dialog) { fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let v = d.f64("fidelity", 1.5); - let rail = (vectorcraft_tools::draw2::min_fidelity(&d.str("tool")), FIDELITY_MAX); + let tool = d.str("tool"); + let rail = (vectorcraft_tools::draw2::min_fidelity(&tool), FIDELITY_MAX); + // The Pencil's and the Paintbrush's Fidelity is on screen, the same at any zoom (#5729). + let unit = if matches!(tool.as_str(), "pencil" | "paintbrush") { "px" } else { "pt" }; let rail_w = label_w(ui); let mut new = None; ui.label(egui::RichText::new(tl!("Fidelity:")).size(12.5).color(t.text)); ui.horizontal(|ui| { - let shown = widgets::SliderValue::field(v, rail.0..=rail.1, "pt", 2).with_step(fidelity_step); + let shown = widgets::SliderValue::field(v, rail.0..=rail.1, unit, 2).with_step(fidelity_step); let (x, _, keyed) = widgets::color_slider_stepped(ui, "freehand-fidelity", tl!("Fidelity:"), Some(shown), fidelity_at(v, rail), rail_w, &|_| t.input_border); new = x.map(|x| fidelity_from(x, rail)).or(keyed); - if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, "pt", 2, FIELD_W, fidelity_step) { + if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, unit, 2, FIELD_W, fidelity_step) { new = Some(x); } }); 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.rs b/crates/ui-egui/src/dialogs/tests.rs index c8b0bf6e21..c2a7aa2b1d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -724,14 +724,16 @@ fn a_dialog_opens_with_its_first_field_focused_so_typing_and_enter_apply() { assert!(app.ui.dialog.is_none()); let after = bounds(&app); assert!((after.x0 - before.x0 - 15.0).abs() < 1e-6 && (after.y0 - before.y0).abs() < 1e-6, "{before:?} → {after:?}"); - // Transform Each, then the Transform effect: Scale › Horizontal, a plain number, comes first. - let before = bounds(&app); + // Transform Each, then the Transform effect: Scale › Horizontal, a plain number, comes first, + // and it scales the object's own width, turned with it (this one is on its side). + let own = |app: &VectorcraftApp| app.session.doc().unwrap().doc.oriented_bounds(&[vectorcraft_doc::NodeId(id)], false).unwrap().rect; + let before = own(&app); crate::menus::invoke(&mut app, "object.transformEach", json!({})); frame(&mut app, vec![]); frame(&mut app, vec![egui::Event::Text("50".into())]); frame(&mut app, vec![enter()]); assert!(app.ui.dialog.is_none()); - let after = bounds(&app); + let after = own(&app); assert!((after.width() - before.width() / 2.0).abs() < 1e-6 && (after.height() - before.height()).abs() < 1e-6, "{before:?} → {after:?}"); app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); frame(&mut app, vec![]); @@ -1047,6 +1049,399 @@ fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_aga /// Drop Shadow's dialog has Color and Darkness as radio buttons, each with its field; a click on /// Darkness previews the shadow with it and OK applies it. +/// The Transform Each panel lists its sections in the documented order: Scale (with the Relative +/// and Absolute radio buttons under its sliders), Move, Rotate, then the Options in two columns +/// (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, +/// Reflect Y, Random) and the Reference Point below them, above Preview. +#[test] +fn transform_each_lists_scale_move_rotate_options_and_the_reference_point() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("no {s:?} in {text}")); + // Scale, its sliders and the Relative / Absolute pair, then Move and Rotate. + let [scale, horizontal, vertical, relative, absolute, mv, rotate, options] = + ["Scale", "Horizontal:", "Vertical:", "Relative", "Absolute", "Move", "Rotate", "Options"].map(at); + assert!( + scale < horizontal && horizontal < vertical && vertical < relative && relative < absolute && absolute < mv && mv < rotate && rotate < options, + "{text}" + ); + // Options: the object and scale options, then the reflections and Random, then the reference + // point. + let [objects, patterns, strokes, corners, reflect_x, reflect_y, random, reference] = [ + "Transform Objects", + "Transform Patterns", + "Scale Strokes & Effects", + "Scale Corners", + "Reflect X", + "Reflect Y", + "Random", + "Reference Point", + ] + .map(at); + assert!( + options < objects + && objects < patterns + && patterns < strokes + && strokes < corners + && corners < reflect_x + && reflect_x < reflect_y + && reflect_y < random + && random < reference + && reference < at("Preview"), + "{text}" + ); +} + +/// The Scale section's Relative and Absolute radio buttons: Absolute shows the width and height the +/// selected objects share, OK sends `relative: false` with the sizes typed, and Relative keeps its +/// own percentages. +#[test] +fn transform_each_switches_between_relative_and_absolute_scale() { + use egui::accesskit::Role; + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let mode = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Transform Each is open").fields["relative"].clone(); + let scale = |app: &VectorcraftApp, h: &str, v: &str| { + let d = app.ui.dialog.as_ref().expect("Transform Each is open"); + (d.f64(h, f64::NAN), d.f64(v, f64::NAN)) + }; + assert_eq!(mode(&app), json!(true), "Relative at first"); + assert_eq!(scale(&app, "scaleH", "scaleV"), (100.0, 100.0)); + let click = |f: &mut Frames, app: &mut VectorcraftApp, label: &str| { + let at = f.control(app, label, Role::RadioButton); + f.press(app, at, true); + f.press(app, at, false); + f.run(app, vec![]); + }; + click(&mut f, &mut app, "Absolute"); + assert_eq!((mode(&app), scale(&app, "absH", "absV")), (json!(false), (60.0, 20.0)), "the size the rectangle has"); + // Exact sizes: 40 × 30 pt about the centre, as Absolute takes them. + app.ui.dialog.as_mut().unwrap().fields.extend([("absH".to_string(), json!(40)), ("absV".to_string(), json!(30))]); + f.run(&mut app, vec![]); + confirm(&mut app).unwrap(); + let b = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (20.0, 5.0, 60.0, 35.0)); + let (cmd, p) = app.session.journal.last().unwrap(); + assert_eq!((cmd.as_str(), &p["relative"], &p["scaleH"], &p["scaleV"]), ("object.transformEach", &json!(false), &json!(40.0), &json!(30.0))); + // The dialog opens on Absolute again, with the size the objects have now; Relative keeps its own + // percentages. + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + f.run(&mut app, vec![]); + assert_eq!((mode(&app), scale(&app, "absH", "absV")), (json!(false), (40.0, 30.0)), "Absolute is kept, at the size they have"); + click(&mut f, &mut app, "Relative"); + assert_eq!((mode(&app), scale(&app, "scaleH", "scaleV")), (json!(true), (100.0, 100.0)), "the percentages are the dialog's own"); +} + +/// Switching to Absolute with Preview on shows the size the objects have without the preview, not +/// the size it has scaled them to. +#[test] +fn transform_each_switching_to_absolute_ignores_the_preview() { + use egui::accesskit::Role; + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + app.ui.dialog.as_mut().unwrap().fields.extend([("scaleH".to_string(), json!(50)), ("preview".to_string(), json!(true))]); + f.run(&mut app, vec![]); + let width = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap().width(); + assert_eq!(width(&app), 30.0, "the preview scaled it"); + let at = f.control(&mut app, "Absolute", Role::RadioButton); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + f.run(&mut app, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["relative"].clone(), d.f64("absH", 0.0), d.f64("absV", 0.0)), (json!(false), 60.0, 20.0), "the size before the preview"); +} + +/// `ui.dialog.set` switching to Absolute shows the size the objects share, and the Absolute sizes a +/// request sets after the mode stay as set. +#[test] +fn transform_each_control_set_of_relative_keeps_the_sizes_after_it() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let set = |app: &mut VectorcraftApp, field: &str, value: serde_json::Value| { + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), field.into(), value); + field_set(app, field, old.as_ref()).unwrap(); + }; + set(&mut app, "relative", json!(false)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (60.0, 20.0), "the size the rectangle has"); + for (field, value) in [("absH", json!(40)), ("absV", json!(30))] { + set(&mut app, field, value); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["relative"].clone(), d.f64("absH", 0.0), d.f64("absV", 0.0)), (json!(false), 40.0, 30.0)); +} + +/// With the link on, switching to Absolute keeps the proportions the fields then show, and a scale +/// set over the control channel follows the link as a typed one does. +#[test] +fn transform_each_scale_link_follows_a_mode_switch_and_control_sets() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let set = |app: &mut VectorcraftApp, field: &str, value: serde_json::Value| { + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), field.into(), value); + field_set(app, field, old.as_ref()).unwrap(); + }; + set(&mut app, "__constrain", json!(true)); + set(&mut app, "relative", json!(false)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (60.0, 20.0), "the size the rectangle has"); + // The link keeps the 3 : 1 the fields show: 30 wide is 10 high. + set(&mut app, "absH", json!(30)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (30.0, 10.0)); +} + +/// The Scale link: while it is on, changing one scale sets the other, so the two keep the +/// proportions they had when it was turned on; it is kept with the dialog's other values. +#[test] +fn transform_each_scale_link_keeps_the_proportions() { + use egui::accesskit::Role; + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let set = |app: &mut VectorcraftApp, k: &str, v: serde_json::Value| { + app.ui.dialog.as_mut().expect("Transform Each is open").fields.insert(k.into(), v); + }; + let scale = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().expect("Transform Each is open"); + (d.f64("scaleH", f64::NAN), d.f64("scaleV", f64::NAN)) + }; + set(&mut app, "scaleH", json!(100)); + set(&mut app, "scaleV", json!(200)); + let at = f.control(&mut app, "Constrain Width and Height Proportions", Role::Button); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + f.run(&mut app, vec![]); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.bool("__constrain")), "the link is on"); + // A quarter of the way along the Horizontal slider: Vertical follows at twice it. + let slider = f.control(&mut app, "Horizontal:", Role::Slider); + let at = slider + egui::vec2(-form::SLIDER_WIDTH / 4.0, 0.0); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + f.run(&mut app, vec![]); + let (h, v) = scale(&app); + assert!(h < 100.0, "the slider moved: {h}"); + assert!((v - 2.0 * h).abs() < 1e-9, "{h} × 2 is {v}"); + // The link is kept with the dialog's other values, and it stays off when it was off. + confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.bool("__constrain"))); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("__constrain".into(), json!(false)); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + assert!(app.ui.dialog.as_ref().is_some_and(|d| !d.bool("__constrain"))); +} + +/// Transform Each's Preview checkbox sits at the left of the button row, level with Copy, Cancel +/// and OK, and turning it on previews the transform. +#[test] +fn transform_each_preview_is_level_with_the_buttons() { + use crate::widgets::accessibility_tests::tree; + use egui::accesskit::Role; + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let shown = tree(|ui| show(&mut app, ui.ctx())); + let centre_y = |label: &str| { + let node = shown.iter().find(|n| n.label() == Some(label)).unwrap_or_else(|| panic!("no {label:?}")); + let b = node.bounds().expect("bounds"); + (b.y0 + b.y1) / 2.0 + }; + let preview = centre_y("Preview"); + for button in ["Copy", "Cancel", "OK"] { + assert!((centre_y(button) - preview).abs() <= 1.0, "{button} is not level with Preview: {} vs {preview}", centre_y(button)); + } + // The checkbox in the footer still runs the preview. + let mut f = Frames::new(); + let at = f.control(&mut app, "Preview", Role::CheckBox); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + f.run(&mut app, vec![]); + f.run(&mut app, vec![]); + assert!(app.session.in_interaction(), "Preview starts the preview"); +} + +/// Absolute reads the size the selected objects share, not the bounds of the selection: two +/// rectangles of the same size show it, and a size typed makes every object that size. +#[test] +fn transform_each_absolute_shows_the_size_the_objects_share() { + let mut app = app(); + for x in [10, 120] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 60, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), "relative".into(), json!(false)); + field_set(&mut app, "relative", Some(&json!(true))).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (60.0, 20.0), "not the 170 pt the two together span"); +} + +/// Each object is measured by its own box, as the Transform panel and the Control bar show it: +/// rotated circles of one size read as that size, though their axis-aligned bounds differ by a +/// hair (a rotated Bezier circle's bounding box runs slightly larger than the circle). +#[test] +fn transform_each_absolute_measures_each_object_its_own_way() { + let mut app = app(); + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + let size = 11.8 * 72.0 / 25.4; + for (x, angle) in [(10.0, 0.0), (100.0, 30.0)] { + let id = app.run("shape.ellipse", json!({"x": x, "y": 10, "width": size, "height": size})).unwrap()["id"].as_u64().unwrap(); + if angle != 0.0 { + app.run("select.none", json!({})).unwrap(); + app.run("select.add", json!({"ids": [id]})).unwrap(); + app.run("object.rotate", json!({"angle": angle})).unwrap(); + } + } + app.run("select.all", json!({})).unwrap(); + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (size, size), "11.8 mm each"); +} + +/// Objects of different sizes read "Mixed", and a size typed sets every one of them to it. +#[test] +fn transform_each_absolute_reads_mixed_and_sets_every_object() { + let mut app = app(); + let small = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let large = app.run("shape.rectangle", json!({"x": 120, "y": 10, "width": 40, "height": 80})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + // The dialog opens in Absolute, as it was last confirmed. + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields.get("absH"), d.fields.get("absV")), (None, None), "no size they share"); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_eq!(text.lines().filter(|l| *l == "Mixed").count(), 2, "both fields read Mixed: {text}"); + // The first field takes the keyboard as the dialog opens: typing a width sets every object to + // it, and the side left Mixed keeps its size. + f.run(&mut app, vec![]); + f.run(&mut app, vec![egui::Event::Text("50".into())]); + f.key(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(app.ui.dialog.is_none(), "Enter applies it"); + let size = |id: u64| app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + assert_eq!((size(small).width(), size(small).height()), (50.0, 20.0)); + assert_eq!((size(large).width(), size(large).height()), (50.0, 80.0)); +} + +/// A line's height of 0 reads Mixed, as the command refuses a scale of 0: the dialog can still move +/// or rotate it, and typing a height sets it. +#[test] +fn transform_each_absolute_reads_mixed_for_a_side_of_zero() { + let mut app = app(); + let id = app.run("path.create", json!({"anchors": [{"x": 10, "y": 50}, {"x": 110, "y": 50}], "closed": false})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", -1.0), d.fields.get("absV")), (100.0, None), "its width, and Mixed for its height"); + app.ui.dialog.as_mut().unwrap().fields.insert("moveH".into(), json!(10)); + confirm(&mut app).unwrap(); + let b = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0, b.x1), (20.0, 50.0, 120.0)); +} + +/// `ui.dialog.set` takes an Absolute size as text in a unit ("10 mm"), as the dialog's fields do, +/// and reaches the fields while they read Mixed. +#[test] +fn transform_each_control_set_takes_a_size_in_units() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("shape.rectangle", json!({"x": 120, "y": 10, "width": 40, "height": 80})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("absH"), None, "Mixed"); + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), "absH".into(), json!("10 mm")); + confirm(&mut app).unwrap(); + let b = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + assert!((b.width() - 10.0 * 72.0 / 25.4).abs() < 1e-6, "10 mm wide: {}", b.width()); +} + +/// Absolute measures the objects the command transforms: a compound path's member stands for its +/// compound, so the size shown is the compound's. +#[test] +fn transform_each_absolute_measures_the_compound_a_member_stands_for() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 100})).unwrap(); + let inner = app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("select.add", json!({"ids": [inner]})).unwrap(); + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("absH", 0.0), d.f64("absV", 0.0)), (100.0, 100.0), "the compound's size, not the member's"); +} + +/// The link keeps the proportions of sizes given as text in a unit ("10 mm"), as the dialog's own +/// fields read them. +#[test] +fn transform_each_link_reads_sizes_in_units() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.ui.transform_each = json!({"relative": false}); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + for (field, value) in [("absH", json!("10 mm")), ("absV", json!("20 mm"))] { + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), field.into(), value); + } + set_field(app.ui.dialog.as_mut().expect("Transform Each is open"), "__constrain".into(), json!(true)); + field_set(&mut app, "__constrain", Some(&json!(false))).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.f64("__ratio", 0.0), 2.0, "20 mm is twice 10 mm"); +} + +/// The Transform effect has no link between its two scales: it scales in percentages only. +#[test] +fn the_transform_effect_has_no_scale_link() { + use crate::widgets::accessibility_tests::tree; + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); + let shown = tree(|ui| show(&mut app, ui.ctx())); + assert!(!shown.iter().any(|n| n.label() == Some("Constrain Width and Height Proportions")), "no scale link in the Transform effect"); +} + +/// The Transform effect keeps its percentage scales: no Relative or Absolute radio buttons. +#[test] +fn the_transform_effect_scales_in_percentages_only() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(!text.lines().any(|l| l == "Relative" || l == "Absolute"), "{text}"); +} + #[test] fn drop_shadow_chooses_color_or_darkness() { let mut app = app(); @@ -1589,7 +1984,7 @@ fn dialog_sliders_report_the_numbers_their_fields_show() { app.run("tool.options", json!({"tool": "pencil"})).unwrap(); set(&mut app, "fidelity", json!(2.5)); let shown = tree(|ui| show(&mut app, ui.ctx())); - assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5pt")); + assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5px"), "the Pencil's Fidelity is on screen (#5729)"); // The Smooth tool's rail starts at its own lowest Fidelity. app.ui.dialog = None; app.run("tool.options", json!({"tool": "smooth"})).unwrap(); @@ -1949,9 +2344,10 @@ fn transform_each_sliders_step_the_numbers_their_fields_show() { set(&mut app, "scaleH", json!(300)); f.key(&mut app, ArrowLeft, M::NONE); assert_eq!(get(&app, "scaleH"), 199.0); - // Tab goes through the Scale fields and sliders to the Move slider. + // Tab goes through the Scale fields and sliders, the link between them, the Relative and + // Absolute radio buttons and their two fields to the Move slider. set(&mut app, "moveH", json!(0)); - for _ in 0..4 { + for _ in 0..7 { f.key(&mut app, Tab, M::NONE); } f.key(&mut app, ArrowRight, M::NONE); @@ -2728,11 +3124,11 @@ fn artboard_options_selected_fit_spans_other_boards_and_off_board_art() { } /// An effect dialog keeps a distance typed outside the effect's range to the range, so the field -/// shows what the effect applies: Color Halftone's Max Radius below 4 pt is 4 pt (#4637). +/// shows what the effect applies: Crystallize's Cell Size below 3 pt is 3 pt (#4637). #[test] fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { let enter = || egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - for (typed, applied) in [("1 pt", 4.0), ("0.5 px", 4.0), ("200 pt", 127.0), ("10 pt", 10.0)] { + for (typed, applied) in [("1 pt", 3.0), ("0.5 px", 3.0), ("400 pt", 300.0), ("10 pt", 10.0)] { let mut app = app(); let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -2743,21 +3139,23 @@ fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { out.textures_delta.clear(); }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); - // Max Radius, the first field, is focused: type over it and press Enter. + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); + // Cell Size, the only field, is focused: type over it and press Enter. frame(&mut app, vec![]); frame(&mut app, vec![egui::Event::Text(typed.into())]); frame(&mut app, vec![enter()]); assert!(app.ui.dialog.is_none(), "{typed}"); let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); - assert_eq!(node.appearance.effects.last().map(|e| e.params["maxRadius"].clone()), Some(json!(applied)), "{typed}"); + assert_eq!(node.appearance.effects.last().map(|e| e.params["cellSize"].clone()), Some(json!(applied)), "{typed}"); } } /// #4638: typing invalid input in an effect length field does not silently revert to a sub-minimum /// or out-of-range value; sub-minimum input is clamped immediately and invalid input clears cleanly. +/// (Crystallize's Cell Size, 3 to 300 pt: Color Halftone's Max Radius, which #4638 was found on, is +/// in pixels since #3260.) #[test] -fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { +fn effect_length_invalid_input_does_not_revert_to_sub_minimum_value() { let mut app = app(); let _id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -2769,20 +3167,20 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { out }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut app, vec![]); - // 1. Enter 0.5 px (sub-minimum): clamped immediately to 4 pt on commit + // 1. Enter 0.5 px (sub-minimum): clamped immediately to 3 pt on commit frame(&mut app, vec![egui::Event::Text("0.5 px".into())]); frame(&mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); let s1 = frame(&mut app, vec![]); let shows_clamped_text = s1.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_text, "rendered field must show clamped '4 pt' text after sub-minimum commit"); + assert!(shows_clamped_text, "rendered field must show clamped '3 pt' text after sub-minimum commit"); - // 2. Return focus to Max Radius with Shift+Tab, type invalid text, and commit with Enter + // 2. Return focus to Cell Size with Shift+Tab, type invalid text, and commit with Enter frame( &mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT }], @@ -2792,9 +3190,9 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { &mut app, vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - // Dialog remains open and retains the clamped 4.0 pt rather than reverting to 0.5 px + // Dialog remains open and retains the clamped 3.0 pt rather than reverting to 0.5 px assert!(app.ui.dialog.is_some(), "dialog must remain open on invalid Enter commit"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); // The field paints with rejection highlight (width 1.5, accent_strong) let next_out = frame(&mut app, vec![]); @@ -2802,12 +3200,12 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { egui::Shape::Rect(r) => (r.stroke.width - 1.5).abs() < 1e-3 && r.stroke.color.a() > 0, _ => false, }); - assert!(has_rejection_highlight, "Max Radius must display rejection highlight after invalid input"); + assert!(has_rejection_highlight, "Cell Size must display rejection highlight after invalid input"); let shows_clamped_after_invalid = next_out.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_after_invalid, "rendered field must retain '4 pt' text after invalid input rejection"); + assert!(shows_clamped_after_invalid, "rendered field must retain '3 pt' text after invalid input rejection"); } #[test] @@ -2824,13 +3222,43 @@ fn bounded_field_with_inches_does_not_clamp_point_bounds_to_inch_numbers() { out.textures_delta.clear(); }; test_app.run("select.all", json!({})).unwrap(); - test_app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + test_app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut test_app, vec![]); - // Type 1 in: 72 pt is within 4..127 pt range and must not clamp to ~1.76 pt + // Type 1 in: 72 pt is within 3..300 pt range and must not clamp to ~4.17 pt frame(&mut test_app, vec![egui::Event::Text("1 in".into())]); frame( &mut test_app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(72.0)); + assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(72.0)); +} + +/// Color Halftone's Max Radius is in pixels of the raster effects resolution whatever the +/// document's units (#3260): in a document in centimetres it still shows and takes pixels, within +/// the documented 4 to 127 px. +#[test] +fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() { + let tab = || egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for (typed, applied, shown) in [("10", 10.0, "10 px"), ("2", 4.0, "4 px"), ("500", 127.0, "127 px"), ("4.5 px", 4.5, "4.5 px")] { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("document.setup", json!({"units": "Centimeters"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text(typed.into())]); + frame(&mut app, vec![tab()]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"].as_f64(), Some(applied), "{typed}"); + let out = frame(&mut app, vec![]); + let shows = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text().trim() == shown)); + assert!(shows, "{typed} shows as {shown}, not in centimetres"); + } } 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/dialogs/transform.rs b/crates/ui-egui/src/dialogs/transform.rs index 5bf48a7395..4f576b561a 100644 --- a/crates/ui-egui/src/dialogs/transform.rs +++ b/crates/ui-egui/src/dialogs/transform.rs @@ -166,7 +166,17 @@ fn scale_option(app: &VectorcraftApp, d: &Dialog, field: &str) -> bool { /// The Scale Corners and Scale Strokes & Effects checkboxes (fields `corners` and `strokes`), /// starting from the preferences. pub(super) fn scale_options(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - for (field, _, label) in SCALE_OPTIONS { + scale_options_ordered(app, ui, d, false); +} + +/// [`scale_options`], with `strokes_first` putting Scale Strokes & Effects above Scale Corners as +/// Transform Each lists them. +pub(super) fn scale_options_ordered(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, strokes_first: bool) { + let mut options = SCALE_OPTIONS; + if strokes_first { + options.reverse(); + } + for (field, _, label) in options { let on = scale_option(app, d, field); d.fields.insert(field.into(), Value::Bool(on)); form::check(ui, d, field, tl!(label)); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 71f5145a22..dd32fe8539 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -3,14 +3,16 @@ //! Corners and Scale Strokes & Effects (`object.transformEach`), previewed live on the canvas. Its Scale and Move sliders, Rotate dial //! and reflection, reference point and Random options are the Transform effect's too. //! -//! Fields: `scaleH`, `scaleV` (%), `moveH`, `moveV` (pt), `rotate` (°), `reflectX`, `reflectY`, -//! `random`, `reference` (0..8, the 9-point grid), `copy` (set by the Copy button, which confirms), -//! `objects`, `patterns`, `corners`, `strokes` (the last two default to the preferences, which OK -//! updates) and `preview`. It opens on the values it was last confirmed with, Copy aside (#1732). +//! Fields: `scaleH`, `scaleV` (percentages, or with Absolute each object's width and height in pt), +//! `relative` (Relative or Absolute scaling), `moveH`, `moveV` (pt), `rotate` (°), `reflectX`, +//! `reflectY`, `random`, `reference` (0..8, the 9-point grid), `copy` (set by the Copy button, which +//! confirms), `objects`, `patterns`, `corners`, `strokes` (the last two default to the preferences, +//! which OK updates) and `preview`; `__constrain` is the link that keeps the two scales in +//! proportion. It opens on the values it was last confirmed with, Copy aside (#1732). use serde_json::{Value, json}; -use super::transform::{add_object_options, add_scale_options, object_options, scale_options, with_scale_options}; +use super::transform::{add_object_options, add_scale_options, object_options, scale_options_ordered, with_scale_options}; use super::{DialogSpec, form}; use crate::VectorcraftApp; use crate::state::Dialog; @@ -31,18 +33,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec { alternate: Some(("Copy", "copy")), preview: true, min_width: 360.0, - inputs: |_| &["objects", "patterns", "corners", "strokes"], + inputs: |_| &["relative", "absH", "absV", "objects", "patterns", "corners", "strokes"], + // Preview sits at the left of the button row, level with Copy, Cancel and OK. + footer_left: Some(form::preview_check), ..DialogSpec::FORM }; /// The fields a fresh dialog starts with. pub fn fields() -> Value { - json!({"scaleH": 100, "scaleV": 100, "moveH": 0, "moveV": 0, "rotate": 0, "reflectX": false, "reflectY": false, "random": false, "reference": 4, "copy": false}) + json!({"scaleH": 100, "scaleV": 100, "relative": true, "moveH": 0, "moveV": 0, "rotate": 0, "reflectX": false, "reflectY": false, "random": false, "reference": 4, "copy": false, "__constrain": false}) } /// The fields kept from the last OK or Copy (`UiState::transform_each`): all but Copy, Transform -/// Patterns (the preference it starts from) and the scale options (preferences too). -const REMEMBERED: [&str; 11] = ["scaleH", "scaleV", "moveH", "moveV", "rotate", "reflectX", "reflectY", "random", "reference", "objects", "preview"]; +/// Patterns (the preference it starts from), the scale options (preferences too) and the Absolute +/// targets (`absH`, `absV`), which the dialog sets from the selection every time it opens. +const REMEMBERED: [&str; 13] = + ["scaleH", "scaleV", "relative", "moveH", "moveV", "rotate", "reflectX", "reflectY", "random", "reference", "objects", "preview", LINK]; /// The fields the menu item opens with: [`fields`], with the values it was last confirmed with. /// A kept value of the wrong kind (a hand-edited file) is left out. @@ -55,48 +61,353 @@ pub fn open_fields(app: &VectorcraftApp) -> Value { _ => {} } } + let relative = out.get("relative").and_then(Value::as_bool).unwrap_or(true); + // Absolute shows the size the selected objects share, so a dialog that opens in it has it. + if !relative { + let (w, h) = shared_size(app, app.session.general_unit()); + for (key, v) in [("absH", w), ("absV", h)] { + if let Some(v) = v { + out[key] = json!(v); + } + } + } + // A link that opens on keeps the proportions of the scales it opens on, so a scale set before + // the first frame (`ui.dialog.set`) follows it. + if out.get(LINK).and_then(Value::as_bool) == Some(true) + && let Some(ratio) = out.as_object().and_then(|f| link_ratio(f, relative)) + { + out[RATIO] = json!(ratio); + } out } -/// The command's parameters without the scale options. +/// The command's parameters without the scale options. The scales are the percentages with +/// Relative and the Absolute targets with Absolute, where a side the objects don't share (Mixed) is +/// left out, so each object keeps that side. fn params(d: &Dialog) -> Value { let f = |k: &str, v: f64| d.f64(k, v); - json!({ - "scaleH": f("scaleH", 100.0), "scaleV": f("scaleV", 100.0), "moveH": f("moveH", 0.0), "moveV": f("moveV", 0.0), + let mut p = json!({ + "relative": relative(d), + "moveH": f("moveH", 0.0), "moveV": f("moveV", 0.0), "rotate": f("rotate", 0.0), "reflectX": d.bool("reflectX"), "reflectY": d.bool("reflectY"), "random": d.bool("random"), "reference": f("reference", 4.0).clamp(0.0, 8.0) as u64, "copy": d.bool("copy"), - }) + }); + let (h, v) = scale_keys(d); + for (key, field) in [("scaleH", h), ("scaleV", v)] { + // A field the dialog doesn't hold is Mixed; one kept as text ("10 mm") parses as the + // dialog's own fields read it. + if d.fields.contains_key(field) { + p[key] = json!(d.f64(field, 100.0)); + } + } + p +} + +/// The two Scale fields the dialog edits: the percentages with Relative, the Absolute targets with +/// Absolute (`absH` and `absV`, absent when the objects differ). +fn scale_keys(d: &Dialog) -> (&'static str, &'static str) { + if relative(d) { ("scaleH", "scaleV") } else { ("absH", "absV") } +} + +/// The proportions the link keeps for the scales `fields` show (vertical ÷ horizontal): none while +/// a side is Mixed. +fn link_ratio(fields: &serde_json::Map, relative: bool) -> Option { + let (h, v) = if relative { ("scaleH", "scaleV") } else { ("absH", "absV") }; + let ratio = field_number(fields, v)? / field_number(fields, h)?; + (ratio.is_finite() && ratio != 0.0).then_some(ratio) +} + +/// The number `fields[key]` holds: a number, or a distance in text ("10 mm"), as the dialog's own +/// fields read them; none when the field is absent (Mixed). +fn field_number(fields: &serde_json::Map, key: &str) -> Option { + match fields.get(key)? { + Value::Number(n) => n.as_f64(), + Value::String(s) => vectorcraft_doc::Unit::Points.parse(s), + _ => None, + } +} + +/// Relative scaling (field `relative`, on until switched off): percentages of each object's size, +/// rather than the width and height it becomes (Absolute). +fn relative(d: &Dialog) -> bool { + d.fields.get("relative").and_then(Value::as_bool).unwrap_or(true) } /// Width of the label column and the value fields of [`sections`]. const LABEL_W: f32 = 72.0; -const FIELD_W: f32 = 70.0; +const FIELD_W: f32 = 78.0; +/// Width of the Angle field: the dial leaves it room to be wider than a Scale or Move field. +const ANGLE_FIELD_W: f32 = 94.0; +/// Width of the Constrain Width and Height Proportions link's column, at the right of the Scale +/// rows. +const LINK_W: f32 = 22.0; /// Largest scale (%) the fields take (as `object.transformEach` and the Transform effect). const MAX_SCALE: f64 = 100_000.0; +/// Largest width or height (pt) the Scale fields take with Absolute (as `object.transformEach`). +const MAX_ABSOLUTE: f64 = 1.0e7; +/// The Scale sliders' rails: percentages, and points with Absolute (the fields take values past +/// the rails). +const SCALE_RAIL: std::ops::RangeInclusive = 0.0..=200.0; +const ABSOLUTE_RAIL: std::ops::RangeInclusive = 0.0..=1000.0; -/// The Scale, Move and Rotate sections of Transform Each and the Transform effect: sliders for -/// `scaleH` and `scaleV` (rails 0–200 %) and for `moveH` and `moveV` (rails ±1000 pt, fields in -/// `units`), and an angle dial for `rotate` (counter-clockwise). The fields take values past the -/// rails. -pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool) { +/// The dialog fields of the Scale link, as the shape dialogs' Width and Height link: its state, the +/// state the dialog last applied (a change by its button or from outside shows as a difference +/// from it) and the proportions it keeps (vertical ÷ horizontal). +const LINK: &str = "__constrain"; +const APPLIED: &str = "__constrainApplied"; +const RATIO: &str = "__ratio"; + +/// The Scale section: a slider and a field for `scaleH` and for `scaleV`, percentages of each +/// object's size, or with `absolute` the width and height it becomes, in `units` (Transform Each +/// alone: the Transform effect scales in percentages), and the link that keeps them in proportion. +fn scale_section(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, absolute: bool) { + widgets::subheader(ui, tl!("Scale")); + link_changed(d); + if let Some(rows) = scale_rows(ui, d, units, false, absolute, true) { + scale_link(ui, d, rows); + } +} + +/// The two Scale rows, and with `link` the column at their right that [`scale_link`] fills. Returns +/// the two rows' bounds. While the link is on, a scale that changes sets the other. +fn scale_rows(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool, absolute: bool, link: bool) -> Option { let rail = Tokens::get(ui.ctx()).input_border; let track = move |_| rail; let axes = |h, v| [(h, tl!("Horizontal:")), (v, tl!("Vertical:"))]; - widgets::subheader(ui, tl!("Scale")); - for (key, label) in axes("scaleH", "scaleV") { - widgets::label_row(ui, label, LABEL_W, |ui| { - let shown = widgets::SliderValue::field(d.f64(key, 100.0).clamp(-MAX_SCALE, MAX_SCALE), 0.0..=200.0, "%", 2); - form::slider_rail_valued(ui, d, key, label, 0.0..=200.0, Some(shown), &track); - let value = if live { - widgets::range_field_live(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) - } else { - widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) - }; - if let Some(n) = value { - d.fields.insert(key.into(), json!(n)); - } - }); + let mut rows: Option = None; + for (key, label) in axes(if absolute { "absH" } else { "scaleH" }, if absolute { "absV" } else { "scaleV" }) { + let before = d.f64(key, 100.0); + let row = ui + .scope(|ui| { + widgets::label_row(ui, label, LABEL_W, |ui| { + if absolute { + // A side the objects don't share reads "Mixed" until a size is typed. + let shown = form::length_value(d, key, units, ABSOLUTE_RAIL); + form::slider_rail_valued(ui, d, key, label, ABSOLUTE_RAIL, shown, &track); + form::length_mixed(ui, d, key, units, FIELD_W, Some(-MAX_ABSOLUTE..=MAX_ABSOLUTE), tl!("Mixed")); + } else { + let shown = widgets::SliderValue::field(d.f64(key, 100.0).clamp(-MAX_SCALE, MAX_SCALE), SCALE_RAIL, "%", 2); + form::slider_rail_valued(ui, d, key, label, SCALE_RAIL, Some(shown), &track); + let value = if live { + widgets::range_field_live(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + } else { + widgets::range_field(ui, ("te", key), d.f64(key, 100.0), -MAX_SCALE..=MAX_SCALE, "%", 2, FIELD_W) + }; + if let Some(n) = value { + d.fields.insert(key.into(), json!(n)); + } + } + if link { + ui.add_space(LINK_W + ui.spacing().item_spacing.x); + } + }); + }) + .response + .rect; + if d.f64(key, 100.0) != before { + follow_link(d, key); + } + rows = Some(rows.map_or(row, |rows| rows.union(row))); } + rows +} + +/// The Constrain Width and Height Proportions link, drawn over the two Scale rows' right end as the +/// shape dialogs' link is over theirs (field [`LINK`]). +fn scale_link(ui: &mut egui::Ui, d: &mut Dialog, rows: egui::Rect) { + let rect = egui::Rect::from_center_size(egui::pos2(rows.right() - LINK_W / 2.0, rows.center().y), egui::vec2(LINK_W, LINK_W)); + let resp = ui.interact(rect, ui.scope_id().with("te-scale-link"), egui::Sense::click()); + let on = d.bool(LINK); + let icon = if on { "link" } else { "link-2-off" }; + if widgets::paint_icon_button(ui, resp, icon, "Constrain Width and Height Proportions", on).clicked() { + d.fields.insert(LINK.into(), json!(!on)); + link_changed(d); + } +} + +/// When the link's state differs from the one the dialog last applied (or none was applied yet), +/// apply it and return it: turned on, the link keeps the proportions of the scales the dialog shows +/// then; turned off, it forgets them. A scale of zero when it turns on leaves nothing to keep, so +/// typing changes only the side typed until the link is turned off and on again. +fn link_changed(d: &mut Dialog) -> Option { + let on = d.bool(LINK); + if d.fields.get(APPLIED).and_then(Value::as_bool) == Some(on) { + return None; + } + d.fields.insert(APPLIED.into(), json!(on)); + keep_link_proportions(d); + Some(on) +} + +/// The link keeps the proportions of the scales the dialog shows now (none while a side is Mixed). +fn keep_link_proportions(d: &mut Dialog) { + match link_ratio(&d.fields, relative(d)).filter(|_| d.bool(LINK)) { + Some(ratio) => { + d.fields.insert(RATIO.into(), json!(ratio)); + } + None => { + d.fields.remove(RATIO); + } + } +} + +/// After the scale `typed` ("scaleH" or "scaleV") changed with the link on, set the other one from +/// the proportions the link keeps, within the range its field takes (so the field shows what the +/// command applies at the limits). +fn follow_link(d: &mut Dialog, typed: &str) { + let ratio = d.f64(RATIO, 0.0); + let (h, v) = scale_keys(d); + if !d.bool(LINK) || !ratio.is_finite() || ratio == 0.0 || (typed != h && typed != v) { + return; + } + let (other, value) = if typed == h { (v, d.f64(h, 100.0) * ratio) } else { (h, d.f64(v, 100.0) / ratio) }; + let limit = if relative(d) { MAX_SCALE } else { MAX_ABSOLUTE }; + if value.is_finite() { + d.fields.insert(other.into(), json!(value.clamp(-limit, limit))); + } +} + +/// The Scale section's Relative and Absolute radio buttons, under its sliders (field `relative`). +/// Absolute shows the size the selected objects share, set again each time it is chosen. +fn scale_mode_radios(ui: &mut egui::Ui, d: &mut Dialog, app: &VectorcraftApp, units: vectorcraft_doc::Unit) { + let relative = relative(d); + ui.horizontal(|ui| { + ui.add_space(LABEL_W + ui.spacing().item_spacing.x); + for (label, on) in [(tl!("Relative"), true), (tl!("Absolute"), false)] { + if widgets::radio(ui, label, relative == on, true) && relative != on { + d.fields.insert("relative".into(), json!(on)); + if on { + keep_link_proportions(d); + } else { + let size = shared_size(app, units); + set_absolute_targets(d, size); + } + } + } + }); +} + +/// `ui.dialog.set` changed a field the Scale section reads: a switch to Absolute shows the size the +/// objects share, and the link (`__constrain`) and its two scales follow as a click or a typed +/// value does. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) { + match field { + "relative" => { + let size = shared_size(app, app.session.general_unit()); + let Some(d) = app.ui.dialog.as_mut() else { return }; + let mode = relative(d); + if old.and_then(Value::as_bool) != Some(mode) { + if mode { + keep_link_proportions(d); + } else { + set_absolute_targets(d, size); + } + } + } + LINK => { + if let Some(d) = app.ui.dialog.as_mut() { + link_changed(d); + } + } + "scaleH" | "scaleV" | "absH" | "absV" => { + if let Some(d) = app.ui.dialog.as_mut() { + follow_link(d, field); + } + } + _ => {} + } +} + +/// The Absolute targets (`absH`, `absV`) for the selection's [`shared_size`]: the width and height +/// its objects share, and none (the fields read "Mixed") when they differ. +fn set_absolute_targets(d: &mut Dialog, (w, h): (Option, Option)) { + for (key, v) in [("absH", w), ("absV", h)] { + match v { + Some(v) => { + d.fields.insert(key.into(), json!(v)); + } + None => { + d.fields.remove(key); + } + } + } + keep_link_proportions(d); +} + +/// The objects a transform of `ids` acts on, as the command's own selection roots: a compound +/// path's member stands for its compound, and layers and objects a listed object holds are left +/// out. +fn transform_roots(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> Vec { + let roots: Vec = ids + .iter() + .map(|id| match doc.parent_of(*id).and_then(|p| doc.node(p)) { + Some(parent) if matches!(parent.kind, vectorcraft_doc::NodeKind::Compound { .. }) => parent.id, + _ => *id, + }) + .collect(); + let listed: std::collections::HashSet = roots.iter().copied().collect(); + roots.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| !n.is_layer()) && !held_by_listed(doc, *id, &listed)).collect() +} + +/// Whether an object `listed` holds is above `id` (one walk up, not one per pair of objects: a +/// selection can be tens of thousands of objects). +fn held_by_listed(doc: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, listed: &std::collections::HashSet) -> bool { + let mut cur = id; + while let Some(parent) = doc.parent_of(cur) { + if listed.contains(&parent) { + return true; + } + cur = parent; + } + false +} + +/// The size `sizes` share, or none when they differ: sizes the panels show alike +/// ([`Unit::number`], four decimals, trailing zeros trimmed) count as the same, and the first is +/// the one shown, so the fields read the same number the Transform panel and the Control bar give +/// each object. A side of 0 (a line's height) is none too: the command refuses a scale of 0, and +/// the objects keep that side anyway. +fn shared_side(unit: vectorcraft_doc::Unit, sizes: impl Iterator) -> Option { + let mut sizes = sizes; + let first = sizes.next()?; + if first.abs() <= 1.0e-9 { + return None; + } + let shown = unit.number(first); + sizes.all(|size| unit.number(size) == shown).then_some(first) +} + +/// The width and height the selected objects share (each `None` when they differ), measured on +/// their own geometric bounds and without a preview: with Preview on, the document holds the +/// transform the dialog has shown so far. +fn shared_size(app: &VectorcraftApp, unit: vectorcraft_doc::Unit) -> (Option, Option) { + // The objects the command transforms (a compound path's member stands for its compound), each + // measured by its own box, rotated with it, as the Transform panel and the Control bar show it: + // a rotated circle's axis-aligned bounds run a hair larger than the circle. + let measure = |doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]| -> Vec<(f64, f64)> { + // One symbol cache for all of them: many instances of one symbol measure its art once. + let symbols = doc.symbol_boxes(); + transform_roots(doc, ids) + .iter() + .filter_map(|id| doc.oriented_bounds_with(&[*id], false, &symbols)) + .map(|b| (b.rect.width(), b.rect.height())) + .collect() + }; + let bounds = match app.session.active().and_then(|st| st.interaction.as_ref()) { + Some(it) => measure(&it.doc, &it.selection.objects), + None => app.session.doc().ok().map(|st| measure(&st.doc, &st.selection.objects)).unwrap_or_default(), + }; + let shared = |side: fn(&(f64, f64)) -> f64| shared_side(unit, bounds.iter().map(side)); + (shared(|b| b.0), shared(|b| b.1)) +} + +/// The Move and Rotate sections of Transform Each and the Transform effect: sliders for `moveH` +/// and `moveV` (rails ±1000 pt, fields in `units`), and an angle dial for `rotate` +/// (counter-clockwise). The fields take values past the rails. +fn move_and_rotate(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool) { + let rail = Tokens::get(ui.ctx()).input_border; + let track = move |_| rail; + let axes = |h, v| [(h, tl!("Horizontal:")), (v, tl!("Vertical:"))]; widgets::subheader(ui, tl!("Move")); for (key, label) in axes("moveH", "moveV") { widgets::label_row(ui, label, LABEL_W, |ui| { @@ -116,9 +427,9 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc let angle = d.f64("rotate", 0.0); let dialed = widgets::angle_dial(ui, "te-dial", angle, 28.0); let typed = if live { - widgets::plain_field_live(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + widgets::plain_field_live(ui, ("te", "rotate"), angle, "°", 2, ANGLE_FIELD_W) } else { - widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, FIELD_W) + widgets::plain_field(ui, ("te", "rotate"), angle, "°", 2, ANGLE_FIELD_W) }; if let Some(a) = typed.or(dialed) { d.fields.insert("rotate".into(), json!(a)); @@ -126,11 +437,25 @@ pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc }); } -/// The Reflect X, Reflect Y, reference point and Random options of Transform Each and the -/// Transform effect. -pub(super) fn reflect_options(ui: &mut egui::Ui, d: &mut Dialog) { +/// The Scale, Move and Rotate sections of Transform Each and the Transform effect: sliders for +/// `scaleH` and `scaleV` (rails 0–200 %), sliders for `moveH` and `moveV` (rails ±1000 pt, fields +/// in `units`), and an angle dial for `rotate` (counter-clockwise). The Transform effect has no +/// link between its two scales. +pub(super) fn sections(ui: &mut egui::Ui, d: &mut Dialog, units: vectorcraft_doc::Unit, live: bool) { + widgets::subheader(ui, tl!("Scale")); + scale_rows(ui, d, units, live, false, false); + move_and_rotate(ui, d, units, live); +} + +/// The Reflect X, Reflect Y and Random options of Transform Each and the Transform effect. +pub(super) fn reflect_checks(ui: &mut egui::Ui, d: &mut Dialog) { form::check(ui, d, "reflectX", tl!("Reflect X")); form::check(ui, d, "reflectY", tl!("Reflect Y")); + form::check(ui, d, "random", tl!("Random")); +} + +/// The reference point locator (field `reference`) and its label. +pub(super) fn reference_point_row(ui: &mut egui::Ui, d: &mut Dialog) { ui.horizontal(|ui| { let cur = d.f64("reference", 4.0).clamp(0.0, 8.0) as usize; if let Some(i) = widgets::reference_point(ui, cur) { @@ -138,26 +463,44 @@ pub(super) fn reflect_options(ui: &mut egui::Ui, d: &mut Dialog) { } widgets::dim_label(ui, tl!("Reference Point")); }); +} + +/// The Reflect X, Reflect Y, reference point and Random options of the Transform effect. +pub(super) fn reflect_options(ui: &mut egui::Ui, d: &mut Dialog) { + form::check(ui, d, "reflectX", tl!("Reflect X")); + form::check(ui, d, "reflectY", tl!("Reflect Y")); + reference_point_row(ui, d); form::check(ui, d, "random", tl!("Random")); } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let units = app.session.general_unit(); - ui.horizontal_top(|ui| { - ui.vertical(|ui| sections(ui, d, units, false)); - ui.add_space(16.0); - ui.vertical(|ui| { - widgets::subheader(ui, tl!("Options")); - ui.add_space(4.0); - object_options(app, ui, d); - scale_options(app, ui, d); - reflect_options(ui, d); + // The rows scroll when the window is shorter than they are, so the heading, Preview and the + // buttons stay in view. + super::modal::scrolled_rows(ui, "transform-each-rows", |ui| { + scale_section(ui, d, units, !relative(d)); + scale_mode_radios(ui, d, app, units); + move_and_rotate(ui, d, units, false); + widgets::subheader(ui, tl!("Options")); + ui.add_space(4.0); + // The options in two columns: the object and scale options, then the reflections and + // Random, which start where the Scale and Move fields do. + let fields_x = LABEL_W + 2.0 * ui.spacing().item_spacing.x + form::SLIDER_WIDTH; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(fields_x - ui.spacing().item_spacing.x); + object_options(app, ui, d); + scale_options_ordered(app, ui, d, true); + }); + ui.vertical(|ui| reflect_checks(ui, d)); }); + ui.add_space(6.0); + reference_point_row(ui, d); }); let mut p = params(d); add_object_options(app, d, &mut p); add_scale_options(app, d, &mut p); - form::preview(app, ui, d, "Transform Each", CMD, p); + form::preview_without_check(app, d, "Transform Each", CMD, p); false } @@ -167,7 +510,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let p = with_scale_options(app, d, p)?; let mut kept = serde_json::Map::new(); for k in REMEMBERED { - let v = if k == "preview" { json!(d.bool("preview")) } else { p[k].clone() }; + let v = match k { + "preview" | LINK => json!(d.bool(k)), + // The percentages stay the dialog's own, whichever mode the scales were applied in. + "scaleH" | "scaleV" => json!(d.f64(k, 100.0)), + _ => p[k].clone(), + }; kept.insert(k.into(), v); } let r = form::commit_preview(app, CMD, p)?; @@ -232,6 +580,17 @@ mod tests { assert_eq!(Value::Object(d.fields.clone()), fields()); } + /// A dialog that opens with the link on keeps the proportions of the scales it opens on, so a + /// scale set before the first frame (`ui.dialog.set`) follows it. + #[test] + fn a_link_that_opens_on_keeps_the_proportions_it_opens_on() { + let (mut app, _) = square_app(); + app.ui.transform_each = json!({"scaleH": 100, "scaleV": 200, "__constrain": true}); + assert_eq!(open(&mut app).f64("__ratio", 0.0), 2.0); + app.ui.transform_each = json!({"scaleH": 100, "scaleV": 200, "__constrain": false}); + assert_eq!(open(&mut app).fields.get("__ratio"), None); + } + /// #1732: the dialog opens on the values it was last confirmed with (as Move and Offset Path /// do), but never on Copy. #[test] @@ -240,6 +599,7 @@ mod tests { let d = open(&mut app); for (k, v) in [ ("scaleH", json!(150)), + ("relative", json!(false)), ("moveH", json!(20)), ("rotate", json!(15)), ("reflectX", json!(true)), @@ -257,6 +617,7 @@ mod tests { for (k, v) in [ ("scaleH", json!(150.0)), ("scaleV", json!(100.0)), + ("relative", json!(false)), ("moveH", json!(20.0)), ("rotate", json!(15.0)), ("reflectX", json!(true)), diff --git a/crates/ui-egui/src/document_drag.rs b/crates/ui-egui/src/document_drag.rs index e85e95ae78..2784f29eef 100644 --- a/crates/ui-egui/src/document_drag.rs +++ b/crates/ui-egui/src/document_drag.rs @@ -44,6 +44,12 @@ fn activated_at_id() -> Id { Id::unique("document-drag-activated-at") } +/// Whether a Selection drag is carrying artwork across the document tabs, which then switch +/// documents and never move along the strip. +pub(crate) fn carrying_artwork(ctx: &Context) -> bool { + egui::DragAndDrop::payload::(ctx).is_some() +} + /// Record the Selection drag source and grab point, clearing any previous tab-hover timer. pub(crate) fn begin(app: &VectorcraftApp, ctx: &Context, grab: Point) { ctx.data_mut(|d| { diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 85309507f8..b467f05552 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -529,10 +529,24 @@ fn drop_targets_follow_the_buttons_edges() { 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, - ["anchorEraserBrush", "extendPath", "measureInspect", "parametricShape", "cornerTool", "slideAnchor", "sharedEdge", "smartPen", enclosing] + [ + "anchorEraserBrush", + "extendPath", + "measureInspect", + "parametricShape", + "cornerTool", + "slideAnchor", + "sharedEdge", + "smartPen", + enclosing, + contour, + box3d + ] ); for advanced in [false, true] { if advanced { @@ -546,7 +560,9 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); - for tool in ["extendPath", "smartPen", enclosing] { + assert_eq!(listed(contour), Some(("Contour", vec![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 588869226e..e73d787364 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -6,10 +6,10 @@ use egui::Ui; use serde_json::{Value, json}; +use crate::VectorcraftApp; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; -use crate::{VectorcraftApp, font_menu}; /// Open the dialog. pub fn open(app: &mut VectorcraftApp) { @@ -26,9 +26,14 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { /// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen, and /// System's font ([`system_family`]) to change to. fn open_at(app: &mut VectorcraftApp, selected: usize) { + let used = fonts(app); + let source = "system"; + let rows = replacement_rows(app, source, &used); + let family = system_family(); + let style = rows.iter().find(|r| r.family.eq_ignore_ascii_case(&family)).map(|r| r.style.clone()).unwrap_or_default(); app.ui.dialog = Some(Dialog::new( "findFont", - json!({ "selected": selected, "family": system_family(), "style": "", "selectionOnly": false, "replaceFrom": "system" }), + json!({ "selected": selected, "family": family, "style": style, "selectionOnly": false, "replaceFrom": source, "rows": rows_json(&rows) }), )); } @@ -71,6 +76,95 @@ fn replacement_families(app: &VectorcraftApp, source: &str, used: &[Value]) -> O Some(out) } +/// A row of Replace With Font: a family and one of its styles (`""` is the family's closest style), +/// so one click picks both. +#[derive(Clone, Debug, PartialEq)] +struct Row { + family: String, + style: String, +} + +/// What the row says: the family and its style, or the family alone for its closest style. +fn row_label(family: &str, style: &str) -> String { + if style.is_empty() { family.to_string() } else { format!("{family} {style}") } +} + +/// Does a row match the search `query` (lower case): its family and style, as typed. +fn row_matches(family: &str, style: &str, query: &str) -> bool { + query.is_empty() || format!("{family} {style}").to_lowercase().contains(query) +} + +/// Replace With Font's rows for `source` ([`SOURCES`]). Document lists the family and style pairs +/// `text.fonts` names, once each, in its order; Recent and System list their families with each +/// family's closest style and then its styles. +fn replacement_rows(app: &VectorcraftApp, source: &str, used: &[Value]) -> Vec { + let db = vectorcraft_text::FontDb::global(); + let mut rows: Vec = vec![]; + match source { + "document" => { + for f in used { + let (family, style) = (f["family"].as_str().unwrap_or_default(), f["style"].as_str().unwrap_or_default()); + if rows.iter().any(|r| r.family.eq_ignore_ascii_case(family) && r.style.eq_ignore_ascii_case(style)) { + continue; + } + rows.push(Row { family: family.to_string(), style: style.to_string() }); + } + } + "recent" => { + for family in replacement_families(app, "recent", used).unwrap_or_default() { + push_family(&mut rows, db, &family); + } + } + _ => { + for family in db.menu_family_list().iter() { + push_family(&mut rows, db, family); + } + } + } + rows +} + +/// Add `family` to `rows`: each style once, the closest style first, every row naming its style. +fn push_family(rows: &mut Vec, db: &vectorcraft_text::FontDb, family: &str) { + if family.is_empty() { + return; + } + let mut styles = db.styles(family); + // The style a style-less request picks comes first, by its own name, not again without one. Its + // name comes from the catalog's metadata: the rows of every family would otherwise have to read + // the family's font files. + if let Some(closest) = db.closest_style(family) + && let Some(i) = styles.iter().position(|s| s.eq_ignore_ascii_case(&closest)) + { + let style = styles.remove(i); + styles.insert(0, style); + } + if styles.is_empty() { + rows.push(Row { family: family.to_string(), style: String::new() }); + return; + } + for style in styles { + rows.push(Row { family: family.to_string(), style }); + } +} + +/// `rows` as the dialog stores them (`{"family": …, "style": …}`). +fn rows_json(rows: &[Row]) -> Value { + Value::Array(rows.iter().map(|r| json!({ "family": r.family, "style": r.style })).collect()) +} + +/// Can the replacement name that very face: `family` and `style` both exist, no stand-in. A row of +/// an unavailable style stays listed, but only a font with that style is chosen as the replacement. +fn exact(family: &str, style: &str) -> bool { + !family.is_empty() && vectorcraft_text::FontDb::global().resolve(family, style).is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact) +} + +/// Can a row be chosen as the replacement: its family is installed and the style is the font's own +/// (or the family names no styles, and its closest style stands for them). +fn listed(row: &Row) -> bool { + installed(&row.family) && (row.style.is_empty() || exact(&row.family, &row.style)) +} + /// Is `family` installed: it resolves to a face of its own, as `text.replaceFont` requires. fn installed(family: &str) -> bool { !family.is_empty() @@ -81,6 +175,10 @@ fn installed(family: &str) -> bool { /// and it is one of the list Replace With Font From shows (System's list is the font menu). fn can_replace(d: &Dialog, families: Option<&[String]>) -> bool { let family = d.str("family"); + let style = d.str("style"); + if !style.is_empty() && !exact(&family, &style) { + return false; + } match families { Some(list) => can_replace_in(&family, installed, list), None => can_replace_in(&family, installed, &vectorcraft_text::FontDb::global().menu_family_list()), @@ -97,16 +195,19 @@ fn can_replace_in(family: &str, is_installed: impl Fn(&str) -> bool, list: &[Str /// its closest style. System chooses [`system_family`]. fn set_source(app: &VectorcraftApp, d: &mut Dialog, source: &str, used: &[Value]) { d.fields.insert("replaceFrom".into(), json!(source)); - let families = replacement_families(app, source, used); - if can_replace(d, families.as_deref()) { + let rows = replacement_rows(app, source, used); + d.fields.insert("rows".into(), rows_json(&rows)); + // The chosen font stays only when the new list has that family and style; otherwise the family + // and the style both come from a row the list shows, so Change replaces with what is listed. + let (family, style) = (d.str("family"), d.str("style")); + if rows.iter().any(|r| r.family.eq_ignore_ascii_case(&family) && r.style.eq_ignore_ascii_case(&style) && listed(r)) { return; } - let family = match families { - Some(l) => l.into_iter().find(|f| installed(f)), - None => Some(system_family()), - }; - d.fields.insert("family".into(), json!(family.unwrap_or_default())); - d.fields.insert("style".into(), json!("")); + let system = if source == "system" { system_family() } else { String::new() }; + let pick = + rows.iter().find(|r| !system.is_empty() && r.family.eq_ignore_ascii_case(&system) && listed(r)).or_else(|| rows.iter().find(|r| listed(r))); + d.fields.insert("family".into(), json!(pick.map(|r| r.family.clone()).unwrap_or_default())); + d.fields.insert("style".into(), json!(pick.map(|r| r.style.clone()).unwrap_or_default())); } fn fonts(app: &mut VectorcraftApp) -> Vec { @@ -114,10 +215,22 @@ fn fonts(app: &mut VectorcraftApp) -> Vec { } pub fn confirm(app: &mut VectorcraftApp) -> Result { + if let Some(ctx) = app.ui_ctx.clone() { + clear_search(&ctx); + } app.ui.dialog = None; Ok(Value::Null) } +/// Forget the replacement search: the next open starts with an empty one. +fn clear_search(ctx: &egui::Context) { + let (source_key, query_id) = (egui::Id::unique("ff-search-source"), egui::Id::unique("ff-search")); + ctx.data_mut(|m| { + m.remove::(source_key); + m.remove::(query_id); + }); +} + /// Replace the selected document font with the chosen one (`all`: everywhere, else the selection). fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Result { let style = d.str("style"); @@ -129,13 +242,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); let list = fonts(app); - let sample = font_menu::sample_text(app); // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included. let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); let mut close = false; let mut find_in_folder = false; let mut act: Option<&str> = None; + // The replacement-font search, kept in egui memory: cleared when the dialog closes, and when + // the source changes. + let source_key = egui::Id::unique("ff-search-source"); + let query_id = egui::Id::unique("ff-search"); crate::dialogs::modal::show(ctx, tl!("Find Font"), egui::Id::unique("dialog-find-font"), -40.0, 22, |ui: &mut Ui| { ui.set_width(380.0); crate::dialogs::modal::heading(ui, tl!("Find Font")); @@ -145,7 +261,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { egui::Frame::NONE.fill(t.input).stroke(egui::Stroke::new(1.0, t.input_border)).inner_margin(egui::Margin::same(4)).show(ui, |ui| { ui.set_min_height(120.0); ui.set_width(ui.available_width()); - egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("ff-document-list").max_height(160.0).auto_shrink([false, true]).show(ui, |ui| { for (i, f) in list.iter().enumerate() { let (note, color) = font_note(f); let label = format!("{} {}{note} ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"]); @@ -172,34 +288,59 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); let families = replacement_families(app, &d.str("replaceFrom"), &list); - let fam = d.str("family"); - ui.horizontal(|ui| { - if let Some(families) = &families { - // Font names are shown as they are. - let names: Vec<&str> = families.iter().map(String::as_str).collect(); - if let Some(i) = widgets::dropdown_names_named(ui, "ff-family-list", Some(tl!("Replace With Font")), &fam, &names, 220.0) { - d.fields.insert("family".into(), json!(families[i])); - d.fields.insert("style".into(), json!("")); + // The rows Replace With Font lists for the source: one click picks the family and its style. + let rows: Vec<(String, String)> = d + .fields + .get("rows") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|r| (r["family"].as_str().unwrap_or_default().to_string(), r["style"].as_str().unwrap_or_default().to_string())) + .collect() + }) + .unwrap_or_default(); + let (fam, style) = (d.str("family"), d.str("style")); + // A search like the Character panel's font menu: the family and style are filtered as typed. + // A new source starts with an empty search. + let source = d.str("replaceFrom"); + if ui.data(|m| m.get_temp::(source_key).as_deref() != Some(source.as_str())) { + ui.data_mut(|m| { + m.insert_temp(source_key, source.clone()); + m.insert_temp(query_id, String::new()); + }); + } + let query = widgets::search_field(ui, query_id, tl!("Search")).to_lowercase(); + let shown: Vec<&(String, String)> = rows.iter().filter(|(f, s)| row_matches(f, s, &query)).collect(); + let mut picked: Option<(String, String, bool)> = None; + // Ten rows at a time, whichever height the rows get from the style. + let row = (ui.spacing().interact_size.y.max(ui.text_style_height(&egui::TextStyle::Body)) + ui.spacing().item_spacing.y).max(18.0); + egui::Frame::NONE.fill(t.input).stroke(egui::Stroke::new(1.0, t.input_border)).inner_margin(egui::Margin::same(4)).show(ui, |ui| { + ui.set_width(ui.available_width()); + let area = egui::ScrollArea::vertical() + .id_salt("ff-rows-list") + // Ten rows at most, and no taller than the rows there are: a search of three fonts + // leaves a list three rows tall. + .max_height((shown.len() as f32 * row).clamp(row, 10.0 * row)) + .auto_shrink([false, true]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible); + area.show_rows(ui, row, shown.len(), |ui, range| { + for i in range { + let Some((f, s)) = shown.get(i) else { continue }; + let is_selected = f.eq_ignore_ascii_case(&fam) && s.eq_ignore_ascii_case(&style); + let resp = ui.selectable_label(is_selected, row_label(f, s)); + if resp.clicked() { + picked = Some((f.clone(), s.clone(), resp.double_clicked())); + } } - } else { - // Picks the font only: nothing is previewed on the document. - let pick = font_menu::font_menu(ui, "ff-family", &fam, 220.0, sample.as_deref(), font_menu::MenuLook::of(app)); - if let Some((f, style)) = font_menu::picked(app, pick) { - d.fields.insert("family".into(), json!(f)); - d.fields.insert("style".into(), json!(style.unwrap_or_default())); - } - } - let styles = vectorcraft_text::FontDb::global().styles(&d.str("family")); - // "(closest)" is ours; the font's style names are shown as they are. - let closest = tl!("(closest)"); - let mut opts: Vec<&str> = vec![closest]; - opts.extend(styles.iter().map(String::as_str)); - let style = d.str("style"); - let cur = if style.is_empty() { closest } else { style.as_str() }; - if let Some(i) = widgets::dropdown_names(ui, "ff-style", cur, &opts, 120.0) { - d.fields.insert("style".into(), json!(if i == 0 { String::new() } else { styles[i - 1].clone() })); - } + }); }); + if let Some((f, s, twice)) = picked { + d.fields.insert("family".into(), json!(f)); + d.fields.insert("style".into(), json!(s)); + if twice && can_replace(&d, families.as_deref()) { + act = Some("change"); + } + } ui.add_space(14.0); // An empty list (Recent before any font was applied) leaves nothing to change to. let replace = sel < list.len() && can_replace(&d, families.as_deref()); @@ -228,12 +369,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { "change" => change(app, &d, from, false), _ => change(app, &d, from, true), }; - if let Err(e) = r { - app.ui.status = e; + match r { + // The rows are a snapshot: the document's fonts and the recent fonts have moved on. + Ok(_) if a != "find" => { + let used = fonts(app); + d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used))); + } + Ok(_) => {} + Err(e) => app.ui.status = e, } } if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { app.ui.dialog = None; + // The next open starts with an empty search. + clear_search(ctx); } else if app.ui.dialog.is_some() { app.ui.dialog = Some(d); } @@ -299,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}"); @@ -310,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(); @@ -370,6 +771,259 @@ mod tests { } } + /// One headless frame of the dialog: every text it painted, with where. + fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + fn collect(s: &egui::epaint::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::epaint::Shape::Text(t) => out.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let raw = egui::RawInput { events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + let mut texts = vec![]; + for c in &out.shapes { + collect(&c.shape, &mut texts); + } + out.textures_delta.clear(); + texts + } + + /// The texts of a [`frame`] that are in `labels`, in order. + fn painted(frame: &[(String, egui::Rect)], labels: &[String]) -> Vec { + frame.iter().map(|(t, _)| t.clone()).filter(|t| labels.contains(t)).collect() + } + + /// A click at `at`: the press on one frame, the release on the next. + fn click(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) { + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]); + frame(ctx, app, vec![button(false)]); + frame(ctx, app, vec![]); + } + + /// A document set in `families`, one text each. + fn many_font_document(families: &[&str]) -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (i, family) in families.iter().enumerate() { + app.session.execute("text.create", &json!({"x": 10, "y": 10.0 + i as f64 * 20.0, "text": "Hi", "font": family})).unwrap(); + } + app + } + + /// The catalog's closest style is the face a style-less request resolves to, and finding it reads + /// no font file. + #[test] + fn the_closest_style_is_the_face_a_style_less_request_gets() { + let db = vectorcraft_text::FontDb::global(); + for family in ["Source Sans 3", "Inter"] { + let closest = db.closest_style(family).unwrap_or_else(|| panic!("{family} is installed")); + let face = db.face(family, "").unwrap_or_else(|| panic!("{family} resolves")); + assert_eq!(closest, face.style, "{family}"); + } + } + + /// A document font drawn in a substitute style stays listed, but it is not chosen as the + /// replacement and Change stays off for it: only a style the font has can be the target. + #[test] + fn a_substituted_style_is_listed_but_not_chosen() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + // A style Source Sans 3 has none of: its closest style stands in. + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Sans 3", "style": "Black Wide"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Hi", "font": "Inter"})).unwrap(); + open(&mut app); + let used = fonts(&mut app); + assert!(used.iter().any(|f| f["family"] == "Source Sans 3" && f["style"] == "Black Wide" && f["status"] == "substitute"), "{used:?}"); + let rows = replacement_rows(&app, "document", &used); + let stand_in = Row { family: "Source Sans 3".into(), style: "Black Wide".into() }; + assert!(rows.contains(&stand_in), "the row stays listed: {rows:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "document", &used); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "the first font whose style it has"); + d.fields.insert("family".into(), json!("Source Sans 3")); + d.fields.insert("style".into(), json!("Black Wide")); + assert!(!can_replace(&d, replacement_families(&app, "document", &used).as_deref()), "Change stays off for the stand-in style"); + } + + /// A new source picks the family and the style from a row its list shows, so Change replaces with + /// what is listed rather than a closest style of its own choosing. + #[test] + fn a_new_source_picks_a_row_its_list_shows() { + let mut app = two_font_document(); + let used = fonts(&mut app); + let mut d = Dialog::new("findFont", json!({"family": "Inter", "style": "", "selected": 0, "replaceFrom": "system"})); + set_source(&app, &mut d, "document", &used); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "the document's own row"); + d.fields.insert("family".into(), json!("Inter")); + d.fields.insert("style".into(), json!("Black Wide")); + set_source(&app, &mut d, "document", &used); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Inter", "Regular"), "a pair the list lacks gives way"); + } + + /// Confirming the dialog with Enter forgets the replacement search, as Done and Escape do. + #[test] + fn confirming_the_dialog_clears_the_replacement_search() { + let mut app = two_font_document(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.ui_ctx = Some(ctx.clone()); + open(&mut app); + let query_id = egui::Id::unique("ff-search"); + ctx.data_mut(|m| m.insert_temp(query_id, "times".to_string())); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "the dialog closes"); + assert_eq!(ctx.data(|m| m.get_temp::(query_id)), None, "the search text is gone"); + } + + /// The rows follow a replacement: Change All in the Document source leaves the list showing the + /// document's fonts as they are now. + #[test] + fn the_rows_refresh_after_a_change() { + let mut app = two_font_document(); + open(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&ctx, &mut app, vec![]); + let used = fonts(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "document", &used); + d.fields.insert("family".into(), json!("Source Serif 4")); + d.fields.insert("style".into(), json!("")); + app.ui.dialog = Some(d); + frame(&ctx, &mut app, vec![]); + let texts = frame(&ctx, &mut app, vec![]); + let change_all = texts.iter().find(|(t, _)| t == "Change All").map(|(_, r)| r.center()).expect("Change All is shown"); + click(&ctx, &mut app, change_all); + assert!(fonts(&mut app).iter().all(|f| f["family"] == "Source Serif 4"), "the document changed"); + let rows = app.ui.dialog.as_ref().expect("the dialog stays open").fields["rows"].as_array().cloned().unwrap_or_default(); + let families: Vec<&str> = rows.iter().filter_map(|r| r["family"].as_str()).collect(); + assert!( + !families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), + "the rows list the document's fonts after the change: {families:?}" + ); + } + + /// Closing the dialog clears the replacement search: the next open starts with an empty one. + #[test] + fn closing_the_dialog_clears_the_replacement_search() { + let mut app = two_font_document(); + open(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&ctx, &mut app, vec![]); + let query_id = egui::Id::unique("ff-search"); + let source_id = egui::Id::unique("ff-search-source"); + ctx.data_mut(|m| { + m.insert_temp(query_id, "times".to_string()); + m.insert_temp(source_id, "system".to_string()); + }); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&ctx, &mut app, vec![escape]); + frame(&ctx, &mut app, vec![]); + assert!(app.ui.dialog.is_none(), "Escape closes the dialog"); + assert_eq!(ctx.data(|m| m.get_temp::(query_id)), None, "the search text is gone"); + assert_eq!(ctx.data(|m| m.get_temp::(source_id)), None, "the source it was typed under is gone"); + } + + /// The wheel over the rows scrolls them, and leaves the document's font list where it was: two + /// lists, two scrollbars. + #[test] + fn the_rows_list_scrolls_with_the_wheel_alone() { + let families = ["Arial", "Georgia", "Verdana", "Tahoma", "Courier New", "Times New Roman", "Consolas", "Impact"]; + let mut app = many_font_document(&families); + open(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&ctx, &mut app, vec![]); + let texts = frame(&ctx, &mut app, vec![]); + let used = fonts(&mut app); + let doc_labels: Vec = used + .iter() + .map(|f| { + let (note, _) = font_note(f); + format!("{} {}{note} ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"]) + }) + .collect(); + let rows = replacement_rows(&app, "system", &used); + let labels: Vec = rows.iter().map(|r| row_label(&r.family, &r.style)).collect(); + let at = |texts: &[(String, egui::Rect)], text: &str| texts.iter().find(|(t, _)| t == text).map(|(_, r)| *r); + let start = at(&texts, &labels[0]).expect("the rows start at their top"); + let (doc_before, rows_before) = (painted(&texts, &doc_labels), painted(&texts, &labels)); + assert!(!doc_before.is_empty(), "the document's fonts are listed: {doc_before:?}"); + assert!(!rows_before.is_empty(), "{rows_before:?}"); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -20.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(start.center()), wheel]); + for _ in 0..30 { + frame(&ctx, &mut app, vec![]); + } + let texts = frame(&ctx, &mut app, vec![]); + assert!(at(&texts, &labels[0]).is_none(), "the wheel scrolls the first rows out of view"); + assert_ne!(painted(&texts, &labels), rows_before, "the wheel scrolls the rows"); + assert_eq!(painted(&texts, &doc_labels), doc_before, "the document's font list stays where it was"); + } + /// The search filters the rows by family and style, whatever case was typed. + #[test] + fn the_search_filters_rows_by_family_and_style() { + assert!(row_matches("Arial", "Bold", ""), "no search lists every row"); + assert!(row_matches("Arial", "Bold", "arial")); + assert!(row_matches("Arial", "Bold", "rial b")); + assert!(row_matches("Source Sans 3", "Semibold", "sans 3 sem")); + assert!(!row_matches("Arial", "Bold", "times")); + assert!(!row_matches("Arial", "Bold", "bold italic")); + } + + /// Replace With Font's rows: Document lists the family and style pairs the document uses, once + /// each; Recent and System list each family with its closest style first and then its styles. + #[test] + fn replacement_rows_pick_a_family_and_its_style() { + let mut app = two_font_document(); + let used = fonts(&mut app); + let document = replacement_rows(&app, "document", &used); + assert_eq!( + document, + [Row { family: "Inter".into(), style: "Regular".into() }, Row { family: "Source Serif 4".into(), style: "Regular".into() }], + "one row per family and style the document uses" + ); + let db = vectorcraft_text::FontDb::global(); + let closest = db.closest_style("Inter").expect("Inter is installed"); + let recent = replacement_rows(&app, "recent", &used); + assert_eq!(recent.first(), Some(&Row { family: "Inter".into(), style: closest.clone() }), "the closest style comes first, by name"); + assert!(recent.iter().all(|r| r.family == "Inter"), "{recent:?}"); + assert_eq!(recent.len(), db.styles("Inter").len(), "each style once, the closest not repeated"); + assert!(recent.iter().all(|r| !r.style.is_empty()), "every row names its style: {recent:?}"); + let system = replacement_rows(&app, "system", &used); + assert!(system.iter().any(|r| r.family == "Source Sans 3" && r.style == "Regular"), "{system:?}"); + assert!(!system.iter().any(|r| r.family.starts_with('.')), "the font menu's hidden families stay out"); + assert!(system.iter().all(|r| !r.style.is_empty()), "no nameless rows: {system:?}"); + let menu = db.menu_family_list(); + let listed: std::collections::BTreeSet<&str> = system.iter().map(|r| r.family.as_str()).collect(); + assert_eq!(listed.len(), menu.len(), "every family the font menu shows is listed"); + let mut unique = system.clone(); + unique.dedup(); + assert_eq!(unique.len(), system.len(), "no family and style is listed twice"); + // The dialog stores the rows when it opens and when the source changes, and a picked row + // sets both fields Change then uses. + open(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["rows"].as_array().map(Vec::len), Some(system.len())); + let mut d = app.ui.dialog.clone().unwrap(); + set_source(&app, &mut d, "document", &used); + assert_eq!(d.fields["rows"].as_array().map(Vec::len), Some(document.len())); + d.fields.insert("family".into(), json!("Inter")); + d.fields.insert("style".into(), json!("Regular")); + let from = used.iter().find(|f| f["family"] == "Source Serif 4").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + assert!(fonts(&mut app).iter().all(|f| f["family"] == "Inter")); + } + #[test] fn change_all_replaces_with_a_font_from_the_document() { let mut app = two_font_document(); @@ -485,7 +1139,7 @@ mod tests { set_source(&app, &mut d, "recent", &used); assert_eq!(d.str("family"), ""); set_source(&app, &mut d, "system", &used); - assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Source Sans 3", "")); + assert_eq!((d.str("family").as_str(), d.str("style").as_str()), ("Source Sans 3", "Regular"), "the family's first listed style"); assert!(can_replace(&d, None)); } 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 284e70e095..a40240ba42 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4524,6 +4524,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 +5952,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` не е цвят @@ -6186,6 +6192,10 @@ breakText Glyphs Глифи Bow Дъга Spike Връх Skip Spaces Пропускане на интервалите + Release Type on a Path… Освобождаване на текст по пътя… + Release Type on a Path Освобождаване на текст по пътя + Text and Path Текст и път + Path Only Само път @msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6197,3 +6207,43 @@ breakText Glyphs Глифи Fully Outside Изцяло извън No artboards match. Няма съвпадащи работни области. Chosen: {n} of {total} Избрани: {n} от {total} + +# Contour add-on + Contour Очертание + Contour Tool Инструмент „Очертание“ + Sharp Заостряне + Bake Разшири + Turn the Contour into plain paths Превръща очертанието в обикновени пътища + Set Corners… Задаване на ъгли… + All Anchors Всички опорни точки + Odd-Numbered Anchors Нечетни опорни точки + Even-Numbered Anchors Четни опорни точки + 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 d6e1bdb8ef..a2464b8831 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4923,6 +4923,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 +6078,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 @@ -6220,6 +6226,11 @@ shape Open Otvoren Bow Luk Spike Šiljak Skip Spaces Preskoči razmake + Release Type on a Path… Oslobodi tekst na putanji… + Release Type on a Path Oslobodi tekst na putanji + Text and Path Tekst i putanja + Path Only Samo putanja + Text Only Samo tekst @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6231,3 +6242,43 @@ shape Open Otvoren Fully Outside Potpuno vani No artboards match. Nijedna radna ploča ne odgovara. Chosen: {n} of {total} Odabrano: {n} od {total} + +# Contour add-on + Contour Kontura + Contour Tool Alat kontura + Sharp Oštro + Bake Proširi + Turn the Contour into plain paths Pretvori konturu u obične putanje + Set Corners… Postavi uglove… + All Anchors Sva sidra + Odd-Numbered Anchors Neparna sidra + Even-Numbered Anchors Parna sidra + 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 75b6b4ca3a..fe905d5acf 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5055,6 +5055,7 @@ digits Malayalam Malaiàlam @msg damaged malmès @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La recuperació de dades no té cap lloc on guardar còpies: configureu Preferències → Gestió de fitxers → Recuperació de dades → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La recuperació de dades no pot guardar còpies a {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No es poden carregar complements des de {path}: {e} @msg data the program reads is damaged or cut short, or the program asks for a position in a file that has none les dades que llegeix el programa estan malmeses o tallades, o el programa demana una posició en un fitxer que no en té @msg decimals must be {_1}–{_2} (got {_3}) els decimals han de ser {_1}–{_2} (rebut {_3}) @msg Dimension point is outside the canvas El punt de dimensió és fora del llenç @@ -5180,6 +5181,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 @@ -6083,6 +6087,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 @@ -6321,6 +6328,10 @@ breakText Glyphs Glifs Bow Arc Spike Pic Skip Spaces Omet els espais + Release Type on a Path… Allibera el text sobre un traçat… + Release Type on a Path Allibera el text sobre un traçat + Text and Path Text i traçat + Path Only Només traçat @msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6332,3 +6343,43 @@ breakText Glyphs Glifs Fully Outside Totalment fora No artboards match. Cap tauler no coincideix. Chosen: {n} of {total} Triats: {n} de {total} + +# Contour add-on + Contour Contorn + Contour Tool Eina de contorn + Sharp Punxegut + Bake Expandeix + Turn the Contour into plain paths Converteix el contorn en traçats simples + Set Corners… Defineix les cantonades… + All Anchors Tots els ancoratges + Odd-Numbered Anchors Ancoratges senars + Even-Numbered Anchors Ancoratges parells + 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 4cb2257256..8231ee0f62 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4292,6 +4292,7 @@ imageTrace Outline Obrys @msg Create from Selection: the selection has no area Vytvořit z výběru: výběr nemá žádnou plochu @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Obnovení dat nemá kam ukládat kopie: nastavte Předvolby → Práce se soubory → Obnovení dat → Složka (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Obnovení dat nemůže ukládat kopie do {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Zásuvné moduly nelze načíst z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) nástrojem Přímý výběr vyberte kotevní body, kde se má cesta rozdělit (ne koncové body otevřených cest) @msg Divide Objects Below: select a path Rozdělit objekty pod: vyberte cestu @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu @@ -4980,6 +4981,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}) @@ -6099,6 +6103,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 @@ -6335,6 +6342,10 @@ breakText Glyphs Glyfy Bow Oblouk Spike Špička Skip Spaces Přeskočit mezery + Release Type on a Path… Uvolnit text na cestě… + Release Type on a Path Uvolnit text na cestě + Text and Path Text a cesta + Path Only Pouze cesta @msg The art is too large to copy as a picture: other apps get no PNG of it Kresba je příliš velká na zkopírování jako obrázek: ostatní aplikace z ní nedostanou PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6346,3 +6357,43 @@ breakText Glyphs Glyfy Fully Outside Zcela vně No artboards match. Žádná pracovní plocha neodpovídá. Chosen: {n} of {total} Zvoleno: {n} z {total} + +# Contour add-on + Contour Obrys + Contour Tool Nástroj Obrys + Sharp Ostrý + Bake Rozložit + Turn the Contour into plain paths Převést obrys na běžné cesty + Set Corners… Nastavit rohy… + All Anchors Všechny kotevní body + Odd-Numbered Anchors Liché kotevní body + Even-Numbered Anchors Sudé kotevní body + 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 3388daba92..1375be430b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4611,6 +4611,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 +5969,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 @@ -6202,6 +6208,10 @@ breakText Glyphs Glyffer Bow Bue Spike Spids Skip Spaces Spring mellemrum over + Release Type on a Path… Frigør tekst på kurve… + Release Type on a Path Frigør tekst på kurve + Text and Path Tekst og kurve + Path Only Kun kurve @msg The art is too large to copy as a picture: other apps get no PNG of it Grafikken er for stor til at blive kopieret som et billede: andre programmer får ingen PNG af den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6213,3 +6223,43 @@ breakText Glyphs Glyffer Fully Outside Helt udenfor No artboards match. Ingen tegneflader passer. Chosen: {n} of {total} Valgt: {n} af {total} + +# Contour add-on + Contour Kontur + Contour Tool Kontur-værktøj + Sharp Spids + Bake Udvid + Turn the Contour into plain paths Gør konturen til almindelige stier + Set Corners… Angiv hjørner… + All Anchors Alle ankre + Odd-Numbered Anchors Ulige ankre + Even-Numbered Anchors Lige ankre + 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 8010726abf..acc8fad4f4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3899,6 +3899,7 @@ theme Appearance Erscheinungsbild @msg Create from Selection: the selection has no area Aus Auswahl erstellen: Die Auswahl hat keine Fläche @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Die Datenwiederherstellung hat keinen Ort für ihre Kopien: Legen Sie Voreinstellungen → Dateihandhabung → Datenwiederherstellung → Ordner (recoveryFolder) fest @msg Data Recovery can't keep copies in {path}: {e} Die Datenwiederherstellung kann keine Kopien in {path} ablegen: {e} +@msg Plug-ins can't be loaded from {path}: {e} Aus {path} können keine Plug-ins geladen werden: {e} @msg direct-select anchor points to cut at (not the end points of open paths) wählen Sie mit der Direktauswahl die Ankerpunkte aus, an denen geschnitten werden soll (nicht die Endpunkte offener Pfade) @msg Divide Objects Below: select a path Darunterliegende Objekte aufteilen: Wählen Sie einen Pfad aus @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus @@ -4590,6 +4591,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}) @@ -5684,6 +5688,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 @@ -5921,6 +5928,10 @@ breakText Glyphs Glyphen Bow Bogen Spike Spitze Skip Spaces Leerzeichen überspringen + Release Type on a Path… Pfadtext zurückwandeln… + Release Type on a Path Pfadtext zurückwandeln + Text and Path Text und Pfad + Path Only Nur Pfad @msg The art is too large to copy as a picture: other apps get no PNG of it Das Bildmaterial ist zu groß, um es als Bild zu kopieren: Andere Apps erhalten kein PNG davon # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5932,3 +5943,43 @@ breakText Glyphs Glyphen Fully Outside Vollständig außen No artboards match. Keine Zeichenfläche passt. Chosen: {n} of {total} Gewählt: {n} von {total} + +# Contour add-on + Contour Umriss + Contour Tool Umriss-Werkzeug + Sharp Spitz + Bake Umwandeln + Turn the Contour into plain paths Wandelt den Umriss in einfache Pfade um + Set Corners… Ecken festlegen… + All Anchors Alle Ankerpunkte + Odd-Numbered Anchors Ungerade Ankerpunkte + Even-Numbered Anchors Gerade Ankerpunkte + 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 17f383fb8c..56467eee23 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2184,6 +2184,7 @@ axis Both Και τα δύο @msg Create from Selection: the selection has no area Δημιουργία από επιλογή: η επιλογή δεν έχει επιφάνεια @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Η ανάκτηση δεδομένων δεν διαθέτει θέση αποθήκευσης αντιγράφων: ορίστε Προτιμήσεις → Χειρισμός αρχείων → Ανάκτηση δεδομένων → Φάκελος (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Η ανάκτηση δεδομένων δεν μπορεί να αποθηκεύσει αντίγραφα στο {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Δεν είναι δυνατή η φόρτωση πρόσθετων από το {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) Επιλέξτε άμεσα τα σημεία αγκύρωσης όπου θα γίνει η αποκοπή (όχι τα τελικά σημεία ανοιχτών διαδρομών) @msg Divide Objects Below: select a path Διαίρεση αντικειμένων από κάτω: επιλέξτε μια διαδρομή @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή @@ -4623,6 +4624,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}) @@ -6050,6 +6054,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` δεν είναι χρώμα @@ -6287,6 +6294,10 @@ breakText Glyphs Γλύφοι Bow Τόξο Spike Αιχμή Skip Spaces Παράλειψη κενών + Release Type on a Path… Αποδέσμευση κειμένου σε διαδρομή… + Release Type on a Path Αποδέσμευση κειμένου σε διαδρομή + Text and Path Κείμενο και διαδρομή + Path Only Μόνο διαδρομή @msg The art is too large to copy as a picture: other apps get no PNG of it Το γραφικό είναι πολύ μεγάλο για αντιγραφή ως εικόνα: οι άλλες εφαρμογές δεν λαμβάνουν PNG του # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6298,3 +6309,43 @@ breakText Glyphs Γλύφοι Fully Outside Πλήρως εκτός No artboards match. Κανένας πίνακας σχεδίασης δεν ταιριάζει. Chosen: {n} of {total} Επιλεγμένοι: {n} από {total} + +# Contour add-on + Contour Παράλληλο περίγραμμα + Contour Tool Εργαλείο παράλληλου περιγράμματος + Sharp Οξεία + Bake Επέκταση + Turn the Contour into plain paths Μετατρέπει το παράλληλο περίγραμμα σε απλές διαδρομές + Set Corners… Ορισμός γωνιών… + All Anchors Όλα τα σημεία αγκύρωσης + Odd-Numbered Anchors Μονά σημεία αγκύρωσης + Even-Numbered Anchors Ζυγά σημεία αγκύρωσης + 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 29c0d06621..7f803f4682 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3984,6 +3984,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Crear a partir de la selección: la selección no tiene área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Recuperación de datos no tiene dónde guardar copias: configura Preferencias → Manejo de archivos → Recuperación de datos → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Recuperación de datos no puede guardar copias en {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No se pueden cargar plugins desde {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecciona con Selección directa los puntos de ancla en los que cortar (no los puntos finales de trazados abiertos) @msg Divide Objects Below: select a path Dividir objetos inferiores: selecciona un trazado @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado @@ -4674,6 +4675,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}) @@ -6041,6 +6045,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 @@ -6277,6 +6284,10 @@ breakText Glyphs Glifos Bow Arco Spike Pico Skip Spaces Omitir espacios + Release Type on a Path… Soltar texto en trazado… + Release Type on a Path Soltar texto en trazado + Text and Path Texto y trazado + Path Only Solo trazado @msg The art is too large to copy as a picture: other apps get no PNG of it La ilustración es demasiado grande para copiarla como imagen: las demás aplicaciones no reciben un PNG de ella # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6288,3 +6299,43 @@ breakText Glyphs Glifos Fully Outside Totalmente fuera No artboards match. Ninguna mesa de trabajo coincide. Chosen: {n} of {total} Elegidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Herramienta Contorno + Sharp Puntiaguda + Bake Expandir + Turn the Contour into plain paths Convierte el contorno en trazados simples + Set Corners… Definir esquinas… + All Anchors Todas las anclas + Odd-Numbered Anchors Anclas impares + Even-Numbered Anchors Anclas pares + 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 65f97fab17..899e4b14a5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4206,6 +4206,7 @@ imageTrace Outline Ääriviiva @msg Create from Selection: the selection has no area Luo valinnasta: valinnalla ei ole pinta-alaa @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Tietojen palautuksella ei ole paikkaa kopioille: määritä Asetukset → Tiedostojen käsittely → Tietojen palautus → Kansio (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Tietojen palautus ei voi tallentaa kopioita kansioon {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Laajennuksia ei voi ladata kansiosta {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) valitse suoravalinnalla ankkuripisteet, joista leikataan (ei avoimien polkujen päätepisteitä) @msg Divide Objects Below: select a path Jaa alla olevat objektit: valitse polku @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku @@ -4882,6 +4883,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}) @@ -6129,6 +6133,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 @@ -6365,6 +6372,10 @@ breakText Glyphs Merkit Bow Kaari Spike Piikki Skip Spaces Ohita välilyönnit + Release Type on a Path… Vapauta teksti polulta… + Release Type on a Path Vapauta teksti polulta + Text and Path Teksti ja polku + Path Only Vain polku @msg The art is too large to copy as a picture: other apps get no PNG of it Grafiikka on liian suuri kopioitavaksi kuvana: muut sovellukset eivät saa siitä PNG-kuvaa Check for Updates… Tarkista päivitykset… VectorCraft Updates VectorCraft-päivitykset @@ -6381,3 +6392,43 @@ breakText Glyphs Merkit Fully Outside Kokonaan ulkona No artboards match. Mikään piirtoalusta ei vastaa hakua. Chosen: {n} of {total} Valittu: {n}/{total} + +# Contour add-on + Contour Ääriviiva + Contour Tool Ääriviivatyökalu + Sharp Terävä + Bake Laajenna + Turn the Contour into plain paths Muuntaa ääriviivan tavallisiksi poluiksi + Set Corners… Aseta kulmat… + All Anchors Kaikki ankkurit + Odd-Numbered Anchors Parittomat ankkurit + Even-Numbered Anchors Parilliset ankkurit + 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 6734fd75ab..ba0a972278 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3974,6 +3974,7 @@ axis Both Les deux @msg Create from Selection: the selection has no area Créer d’après la sélection : la sélection n’a pas de surface @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La récupération des données n’a aucun emplacement où conserver les copies : définissez Préférences → Gestion des fichiers → Récupération des données → Dossier (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La récupération des données ne peut pas conserver de copies dans {path} ({e}) +@msg Plug-ins can't be loaded from {path}: {e} Impossible de charger les plug-ins depuis {path} ({e}) @msg direct-select anchor points to cut at (not the end points of open paths) sélectionnez avec l’outil Sélection directe les points d’ancrage où couper (pas les extrémités des tracés ouverts) @msg Divide Objects Below: select a path Diviser les objets inférieurs : sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé @@ -4662,6 +4663,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}) @@ -6094,6 +6098,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 @@ -6330,6 +6337,10 @@ breakText Glyphs Glyphes Bow Arc Spike Pointe Skip Spaces Ignorer les espaces + Release Type on a Path… Libérer le texte curviligne… + Release Type on a Path Libérer le texte curviligne + Text and Path Texte et tracé + Path Only Tracé uniquement @msg The art is too large to copy as a picture: other apps get no PNG of it L’illustration est trop grande pour être copiée en tant qu’image : les autres applications n’en reçoivent pas de PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6341,3 +6352,43 @@ breakText Glyphs Glyphes Fully Outside Entièrement à l’extérieur No artboards match. Aucun plan de travail ne correspond. Chosen: {n} of {total} Choisis : {n} sur {total} + +# Contour add-on + Contour Pourtour + Contour Tool Outil Pourtour + Sharp Pointu + Bake Décomposer + Turn the Contour into plain paths Transforme le pourtour en tracés simples + Set Corners… Définir les angles… + All Anchors Tous les points d’ancrage + Odd-Numbered Anchors Points d’ancrage impairs + Even-Numbered Anchors Points d’ancrage pairs + 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 8e67cbe935..9a0724c155 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4689,6 +4689,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 @@ -4775,6 +4778,7 @@ imageTrace Outline Körvonal @msg damaged sérült @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Az adat-helyreállításnak nincs hova mentenie a másolatokat: állítsd be a Beállítások → Fájlkezelés → Adat-helyreállítás → Mappa értéket (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Az adat-helyreállítás nem tud másolatokat menteni ide: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Innen nem tölthetők be bővítmények: {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) a tizedesjegyek száma {_1}–{_2} lehet (kapott érték: {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) jelöld ki közvetlen kijelöléssel a vágási horgonypontokat (nyitott útvonal végpontja nem lehet) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Elvetett helyreállított dokumentumok: {n} @@ -6083,6 +6087,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 @@ -6319,6 +6326,10 @@ breakText Glyphs Glifák Bow Ív Spike Csúcs Skip Spaces Szóközök kihagyása + Release Type on a Path… Útvonalszöveg szétválasztása… + Release Type on a Path Útvonalszöveg szétválasztása + Text and Path Szöveg és útvonal + Path Only Csak útvonal @msg The art is too large to copy as a picture: other apps get no PNG of it A grafika túl nagy ahhoz, hogy képként másolható legyen: más alkalmazások nem kapnak róla PNG-t # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6330,3 +6341,43 @@ breakText Glyphs Glifák Fully Outside Teljesen kívül No artboards match. Nincs egyező rajztábla. Chosen: {n} of {total} Kiválasztva: {n} / {total} + +# Contour add-on + Contour Kontúr + Contour Tool Kontúr eszköz + Sharp Hegyes + Bake Kibontás + Turn the Contour into plain paths A kontúrt egyszerű útvonalakká alakítja + Set Corners… Sarkok beállítása… + All Anchors Összes horgonypont + Odd-Numbered Anchors Páratlan horgonypontok + Even-Numbered Anchors Páros horgonypontok + 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 8fc99dbdf4..00fc62d15d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4611,6 +4611,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 +5969,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 @@ -6202,6 +6208,10 @@ breakText Glyphs Glif Bow Busur Spike Puncak Skip Spaces Lewati Spasi + Release Type on a Path… Lepaskan Teks pada Jalur… + Release Type on a Path Lepaskan Teks pada Jalur + Text and Path Teks dan jalur + Path Only Hanya jalur @msg The art is too large to copy as a picture: other apps get no PNG of it Gambar terlalu besar untuk disalin sebagai gambar: aplikasi lain tidak mendapatkan PNG darinya # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6213,3 +6223,43 @@ breakText Glyphs Glif Fully Outside Sepenuhnya di luar No artboards match. Tidak ada artboard yang cocok. Chosen: {n} of {total} Dipilih: {n} dari {total} + +# Contour add-on + Contour Kontur + Contour Tool Alat kontur + Sharp Tajam + Bake Perluas + Turn the Contour into plain paths Ubah kontur menjadi jalur biasa + Set Corners… Atur sudut… + All Anchors Semua jangkar + Odd-Numbered Anchors Jangkar bernomor ganjil + Even-Numbered Anchors Jangkar bernomor genap + 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 cddf63e822..ccff8235fe 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4026,6 +4026,7 @@ axis Both Entrambi @msg Create from Selection: the selection has no area Crea da selezione: la selezione non ha area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Il recupero dati non ha dove conservare le copie: imposta Preferenze → Gestione file → Recupero dati → Cartella (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Il recupero dati non può conservare copie in {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Impossibile caricare plug-in da {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) seleziona con Selezione diretta i punti di ancoraggio in cui tagliare (non i punti finali dei tracciati aperti) @msg Divide Objects Below: select a path Dividi oggetti sottostanti: seleziona un tracciato @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato @@ -4716,6 +4717,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}) @@ -5718,6 +5722,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 @@ -5955,6 +5962,10 @@ breakText Glyphs Glifi Bow Arco Spike Picco Skip Spaces Salta gli spazi + Release Type on a Path… Rilascia testo su tracciato… + Release Type on a Path Rilascia testo su tracciato + Text and Path Testo e tracciato + Path Only Solo tracciato @msg The art is too large to copy as a picture: other apps get no PNG of it La grafica è troppo grande per essere copiata come immagine: le altre app non ne ricevono un PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5966,3 +5977,43 @@ breakText Glyphs Glifi Fully Outside Completamente esterno No artboards match. Nessuna tavola da disegno corrisponde. Chosen: {n} of {total} Scelte: {n} di {total} + +# Contour add-on + Contour Contorno + Contour Tool Strumento Contorno + Sharp Appuntito + Bake Espandi + Turn the Contour into plain paths Trasforma il contorno in tracciati semplici + Set Corners… Imposta angoli… + All Anchors Tutti gli ancoraggi + Odd-Numbered Anchors Ancoraggi dispari + Even-Numbered Anchors Ancoraggi pari + 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 3263faaf57..294240791c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4321,6 +4321,7 @@ swatch Bright Violet ビビッドバイオレット @msg unknown preference `{key}` `{key}` は不明な環境設定の項目です @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) データ復帰のコピーを保存する場所がありません: 環境設定 → ファイル管理 → データ復帰 → フォルダー (recoveryFolder) を設定してください @msg Data Recovery can't keep copies in {path}: {e} データ復帰は {path} にコピーを保存できません: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path} からプラグインを読み込めません: {e} @msg `{area}` is no recovery area name `{area}` は復帰用領域の名前として使えません @msg `{name}` is no recovery entry name `{name}` は復帰用エントリの名前として使えません @msg no clock to keep a heartbeat by ハートビートの記録に必要な時刻を取得できません @@ -4403,6 +4404,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} 個はブラシパネルに追加されませんでした @@ -5783,6 +5787,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` はカラーではありません @@ -6020,6 +6027,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 山形 Skip Spaces スペースをスキップ + Release Type on a Path… パス上文字を解除… + Release Type on a Path パス上文字を解除 + Text and Path テキストとパス + Path Only パスのみ @msg The art is too large to copy as a picture: other apps get no PNG of it アートワークが大きすぎるため画像としてコピーできません:他のアプリには PNG が渡されません # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6031,3 +6042,43 @@ breakText Glyphs 字形 Fully Outside 完全に外側 No artboards match. 一致するアートボードはありません。 Chosen: {n} of {total} 選択中: {n} / {total} + +# Contour add-on + Contour 輪郭 + Contour Tool 輪郭ツール + Sharp 鋭角 + Bake 分割 + Turn the Contour into plain paths 輪郭を通常のパスに変換します + Set Corners… コーナーを設定… + All Anchors すべてのアンカー + Odd-Numbered Anchors 奇数番目のアンカー + Even-Numbered Anchors 偶数番目のアンカー + 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 7c73e2f990..9da177b997 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… ფილის კიდის ფერი… @@ -3771,6 +3772,7 @@ font-technology Variable ცვლადი @msg Create from Selection: the selection has no area მონიშნულიდან შექმნა: მონიშნულს ფართობი არ აქვს @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) მონაცემთა აღდგენას ასლების შესანახი ადგილი არ აქვს: მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} მონაცემთა აღდგენა ვერ ინახავს ასლებს აქ: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} პლაგინების ჩატვირთვა ვერ ხერხდება აქედან: {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) პირდაპირი მონიშვნით მონიშნეთ საყრდენი წერტილები, სადაც გაიჭრება (არა ღია ტრაექტორიების ბოლო წერტილები) @msg Divide Objects Below: select a path ქვედა ობიექტების დაყოფა: მონიშნეთ ტრაექტორია @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია @@ -4778,6 +4780,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}-ის ყველა დანომრილი სახელი დაკავებულია @@ -6095,6 +6100,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` ფერი არ არის @@ -6346,6 +6354,10 @@ font-script Japanese იაპონური Bow რკალი Spike პიკი Skip Spaces ჰარების გამოტოვება + Release Type on a Path… ტექსტის ტრაექტორიიდან მოხსნა… + Release Type on a Path ტექსტის ტრაექტორიიდან მოხსნა + Text and Path ტექსტი და ტრაექტორია + Path Only მხოლოდ ტრაექტორია @msg The art is too large to copy as a picture: other apps get no PNG of it ნახატი ზედმეტად დიდია სურათად დასაკოპირებლად: სხვა აპები მის PNG-ს ვერ მიიღებენ # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6357,3 +6369,43 @@ font-script Japanese იაპონური Fully Outside მთლიანად გარეთ No artboards match. შესაბამისი სამუშაო დაფა არ არის. Chosen: {n} of {total} არჩეულია: {n} / {total} + +# Contour add-on + Contour მოხაზულობა + Contour Tool მოხაზულობის ხელსაწყო + Sharp მახვილი + Bake გაშლა + Turn the Contour into plain paths მოხაზულობას ჩვეულებრივ ტრაექტორიებად აქცევს + Set Corners… კუთხეების დაყენება… + All Anchors ყველა საყრდენი წერტილი + Odd-Numbered Anchors კენტი საყრდენი წერტილები + Even-Numbered Anchors ლუწი საყრდენი წერტილები + 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 04ce6904bf..5c215668c5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4248,6 +4248,7 @@ theme Appearance 외관 @msg unknown preference `{key}` 알 수 없는 환경 설정 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 데이터 복구에 복사본을 보관할 곳이 없습니다. 환경 설정 → 파일 처리 → 데이터 복구 → 폴더(recoveryFolder)를 지정하세요 @msg Data Recovery can't keep copies in {path}: {e} 데이터 복구가 {path}에 복사본을 보관할 수 없습니다: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path}에서 플러그인을 불러올 수 없습니다: {e} @msg `{area}` is no recovery area name `{area}`은(는) 복구 영역 이름이 아닙니다 @msg `{name}` is no recovery entry name `{name}`은(는) 복구 항목 이름이 아닙니다 @msg no clock to keep a heartbeat by 하트비트를 유지할 시계가 없습니다 @@ -4330,6 +4331,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}) @@ -5679,6 +5683,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`은(는) 색상이 아닙니다 @@ -5916,6 +5923,10 @@ breakText Glyphs 글리프 Bow 활 모양 Spike 뾰족한 모양 Skip Spaces 공백 건너뛰기 + Release Type on a Path… 패스 위 문자 해제… + Release Type on a Path 패스 위 문자 해제 + Text and Path 문자와 패스 + Path Only 패스만 @msg The art is too large to copy as a picture: other apps get no PNG of it 아트워크가 너무 커서 이미지로 복사할 수 없습니다: 다른 앱에는 PNG가 전달되지 않습니다 # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5927,3 +5938,43 @@ breakText Glyphs 글리프 Fully Outside 완전히 바깥쪽 No artboards match. 일치하는 아트보드가 없습니다. Chosen: {n} of {total} 선택됨: {n} / {total} + +# Contour add-on + Contour 윤곽 + Contour Tool 윤곽 도구 + Sharp 뾰족하게 + Bake 확장 + Turn the Contour into plain paths 윤곽을 일반 패스로 바꿉니다 + Set Corners… 모퉁이 설정… + All Anchors 모든 앵커 + Odd-Numbered Anchors 홀수 번째 앵커 + Even-Numbered Anchors 짝수 번째 앵커 + 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 02004bb0ca..300fb3de19 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4623,6 +4623,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}) @@ -6010,6 +6013,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 @@ -6246,6 +6252,10 @@ breakText Glyphs Glyphs Bow Boog Spike Piek Skip Spaces Spaties overslaan + Release Type on a Path… Tekst op pad vrijgeven… + Release Type on a Path Tekst op pad vrijgeven + Text and Path Tekst en pad + Path Only Alleen pad @msg The art is too large to copy as a picture: other apps get no PNG of it Het illustratiewerk is te groot om als afbeelding te kopiëren: andere apps krijgen er geen PNG van # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6257,3 +6267,43 @@ breakText Glyphs Glyphs Fully Outside Volledig buiten No artboards match. Geen tekengebied komt overeen. Chosen: {n} of {total} Gekozen: {n} van {total} + +# Contour add-on + Contour Omtrek + Contour Tool Omtrek-gereedschap + Sharp Scherp + Bake Uitbreiden + Turn the Contour into plain paths Zet de omtrek om in gewone paden + Set Corners… Hoeken instellen… + All Anchors Alle ankerpunten + Odd-Numbered Anchors Oneven ankerpunten + Even-Numbered Anchors Even ankerpunten + 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 61b2e60ccd..197f6b9d63 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4115,6 +4115,7 @@ imageTrace Outline Kontur @msg Create from Selection: the selection has no area Utwórz z zaznaczenia: zaznaczenie nie ma powierzchni @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Odzyskiwanie danych nie ma gdzie przechowywać kopii: ustaw Preferencje → Obsługa plików → Odzyskiwanie danych → Folder (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Odzyskiwanie danych nie może przechowywać kopii w {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Nie można wczytać wtyczek z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) zaznacz bezpośrednio punkty kontrolne, w których ma nastąpić cięcie (nie punkty końcowe otwartych ścieżek) @msg Divide Objects Below: select a path Podziel obiekty poniżej: zaznacz ścieżkę @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę @@ -4806,6 +4807,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}) @@ -5953,6 +5957,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 @@ -6190,6 +6197,10 @@ breakText Glyphs Glify Bow Łuk Spike Szpic Skip Spaces Pomiń spacje + Release Type on a Path… Uwolnij tekst na ścieżce… + Release Type on a Path Uwolnij tekst na ścieżce + Text and Path Tekst i ścieżka + Path Only Tylko ścieżka @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6201,3 +6212,43 @@ breakText Glyphs Glify Fully Outside Całkowicie na zewnątrz No artboards match. Żaden obszar kompozycji nie pasuje. Chosen: {n} of {total} Wybrano: {n} z {total} + +# Contour add-on + Contour Kontur + Contour Tool Narzędzie Kontur + Sharp Ostry + Bake Rozszerz + Turn the Contour into plain paths Zamienia kontur w zwykłe ścieżki + Set Corners… Ustaw narożniki… + All Anchors Wszystkie punkty + Odd-Numbered Anchors Punkty nieparzyste + Even-Numbered Anchors Punkty parzyste + 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 0221a45e0a..3a9a0c7f85 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3573,6 +3573,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Criar a partir da seleção: a seleção não tem área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) A recuperação de dados não tem onde guardar cópias: defina Preferências → Manipulação de arquivos → Recuperação de dados → Pasta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} A recuperação de dados não pode guardar cópias em {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Não é possível carregar plug-ins de {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecione diretamente os pontos de ancoragem onde cortar (não as extremidades de traçados abertos) @msg Divide Objects Below: select a path Dividir objetos abaixo: selecione um traçado @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado @@ -4900,6 +4901,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 @@ -6015,6 +6019,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 @@ -6408,6 +6415,10 @@ swatch Yellow Green Verde-amarelado Bow Arco Spike Pico Skip Spaces Ignorar espaços + Release Type on a Path… Liberar Texto em um Caminho… + Release Type on a Path Liberar Texto em um Caminho + Text and Path Texto e caminho + Path Only Somente caminho @msg The art is too large to copy as a picture: other apps get no PNG of it A arte é grande demais para ser copiada como imagem: outros aplicativos não recebem um PNG dela # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6419,3 +6430,43 @@ swatch Yellow Green Verde-amarelado Fully Outside Totalmente fora No artboards match. Nenhuma mesa de trabalho corresponde. Chosen: {n} of {total} Escolhidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Ferramenta Contorno + Sharp Pontiagudo + Bake Expandir + Turn the Contour into plain paths Transforma o contorno em caminhos simples + Set Corners… Definir Cantos… + All Anchors Todas as Âncoras + Odd-Numbered Anchors Âncoras Ímpares + Even-Numbered Anchors Âncoras Pares + 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 bdf6dd16dc..3a717f6767 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4021,6 +4021,7 @@ axis Both Оба @msg Create from Selection: the selection has no area Создание из выделения: у выделения нет области @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Восстановлению данных негде хранить копии: задайте Настройки → Работа с файлами → Восстановление данных → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Восстановление данных не может хранить копии в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не удается загрузить модули из {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) выделите прямым выделением опорные точки для разреза (не конечные точки открытых контуров) @msg Divide Objects Below: select a path Разделение объектов ниже: выделите контур @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур @@ -4711,6 +4712,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}) @@ -6076,6 +6080,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` не является цветом @@ -6424,6 +6431,10 @@ shape Open Открытый Bow Дуга Spike Пик Skip Spaces Пропускать пробелы + Release Type on a Path… Освободить текст по контуру… + Release Type on a Path Освободить текст по контуру + Text and Path Текст и контур + Path Only Только контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графика слишком велика для копирования в виде изображения: другие приложения не получат её PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6435,3 +6446,43 @@ shape Open Открытый Fully Outside Полностью снаружи No artboards match. Нет подходящих монтажных областей. Chosen: {n} of {total} Выбрано: {n} из {total} + +# Contour add-on + Contour Эквидистанта + Contour Tool Инструмент «Эквидистанта» + Sharp Острый + Bake Разобрать + Turn the Contour into plain paths Преобразует эквидистанту в обычные контуры + Set Corners… Задать углы… + All Anchors Все опорные точки + Odd-Numbered Anchors Нечётные опорные точки + Even-Numbered Anchors Чётные опорные точки + 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 e488cf3175..839596958c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3895,6 +3895,7 @@ axis Both Båda @msg Create from Selection: the selection has no area Skapa från markering: markeringen har ingen area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Dataåterställning har ingenstans att spara kopior: ange Inställningar → Filhantering → Dataåterställning → Mapp (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Dataåterställning kan inte spara kopior i {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Det går inte att läsa in plugin-program från {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) direktmarkera ankarpunkter att klippa vid (inte slutpunkterna på öppna banor) @msg Divide Objects Below: select a path Dela objekt under: markera en bana @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana @@ -4573,6 +4574,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}) @@ -6151,6 +6155,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 @@ -6391,6 +6398,10 @@ digits Hindi Hindi Bow Båge Spike Spets Skip Spaces Hoppa över mellanslag + Release Type on a Path… Släpp text på bana… + Release Type on a Path Släpp text på bana + Text and Path Text och bana + Path Only Endast bana @msg The art is too large to copy as a picture: other apps get no PNG of it Teckningen är för stor för att kopieras som en bild: andra appar får ingen PNG av den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6402,3 +6413,43 @@ digits Hindi Hindi Fully Outside Helt utanför No artboards match. Ingen rityta matchar. Chosen: {n} of {total} Valda: {n} av {total} + +# Contour add-on + Contour Kantlinje + Contour Tool Kantlinjeverktyg + Sharp Spetsig + Bake Expandera + Turn the Contour into plain paths Gör om kantlinjen till vanliga banor + Set Corners… Ange hörn… + All Anchors Alla ankare + Odd-Numbered Anchors Udda ankare + Even-Numbered Anchors Jämna ankare + 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/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a39ca73666..f84137f801 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3779,6 +3779,7 @@ axis Both Her İkisi @msg Create from Selection: the selection has no area Seçimden Oluştur: Seçimin alanı yok @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Veri Kurtarma'nın kopyaları saklayacak yeri yoktur: Tercihleri ayarlayın → Dosya İşleme → Veri Kurtarma → Klasör (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Veri Kurtarma kopyaları {path} konumunda saklayamıyor: {e} +@msg Plug-ins can't be loaded from {path}: {e} Eklentiler {path} konumundan yüklenemiyor: {e} @msg direct-select anchor points to cut at (not the end points of open paths) kesilecek bağlantı noktalarını doğrudan seçin (açık yolların bitiş noktalarını değil) @msg Divide Objects Below: select a path Aşağıdaki Nesneleri Böl: bir yol seçin @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin @@ -4410,6 +4411,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}) @@ -6056,6 +6060,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 @@ -6292,6 +6299,10 @@ breakText Glyphs Glifler Bow Yay Spike Sivri Uç Skip Spaces Boşlukları Atla + Release Type on a Path… Yoldaki Metni Ayır… + Release Type on a Path Yoldaki Metni Ayır + Text and Path Metin ve yol + Path Only Yalnızca yol @msg The art is too large to copy as a picture: other apps get no PNG of it Çizim, resim olarak kopyalanamayacak kadar büyük: diğer uygulamalar bunun PNG'sini almaz # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6303,3 +6314,43 @@ breakText Glyphs Glifler Fully Outside Tamamen dışarıda No artboards match. Eşleşen çalışma yüzeyi yok. Chosen: {n} of {total} Seçilen: {n}/{total} + +# Contour add-on + Contour Dış Hat + Contour Tool Dış Hat Aracı + Sharp Keskin + Bake Genişlet + Turn the Contour into plain paths Dış hattı sade yollara dönüştürür + Set Corners… Köşeleri Ayarla… + All Anchors Tüm Çapalar + Odd-Numbered Anchors Tek Numaralı Çapalar + Even-Numbered Anchors Çift Numaralı Çapalar + 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 81be50a597..2577238467 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4010,6 +4010,7 @@ axis Both Обидві @msg Create from Selection: the selection has no area Створення з виділення: виділення немає області @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Відновлення даних ніде зберігати копії: задайте Установки → Робота з файлами → Відновлення даних → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Відновлення даних не може зберігати копії в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не вдається завантажити модулі з {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) виділіть прямим виділенням опорні точки для розрізу (не кінцеві точки відкритих контурів) @msg Divide Objects Below: select a path Поділ об’єктів нижче: виділіть контур @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур @@ -4700,6 +4701,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}) @@ -5698,6 +5702,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` не є кольором @@ -5935,6 +5942,10 @@ breakText Glyphs Гліфи Bow Дуга Spike Пік Skip Spaces Пропускати пробіли + Release Type on a Path… Звільнити текст за контуром… + Release Type on a Path Звільнити текст за контуром + Text and Path Текст і контур + Path Only Лише контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графіка завелика, щоб скопіювати її як зображення: інші програми не отримають її PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5946,3 +5957,43 @@ breakText Glyphs Гліфи Fully Outside Повністю зовні No artboards match. Немає відповідних монтажних областей. Chosen: {n} of {total} Вибрано: {n} з {total} + +# Contour add-on + Contour Еквідистанта + Contour Tool Інструмент «Еквідистанта» + Sharp Гострий + Bake Розібрати + Turn the Contour into plain paths Перетворює еквідистанту на звичайні контури + Set Corners… Задати кути… + All Anchors Усі опорні точки + Odd-Numbered Anchors Непарні опорні точки + Even-Numbered Anchors Парні опорні точки + 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 66ad83aea3..cad18a0d6f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4427,6 +4427,7 @@ theme Appearance Giao diện @msg damaged bị hỏng @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Phục hồi dữ liệu không có nơi lưu bản sao: đặt Tùy chọn → Xử lý tệp → Phục hồi dữ liệu → Thư mục (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Phục hồi dữ liệu không thể lưu bản sao vào {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Không thể tải plug-in từ {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) số thập phân phải từ {_1}–{_2} (nhận được {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) chọn trực tiếp các điểm neo để cắt (không phải điểm cuối của đường dẫn mở) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Đã loại bỏ {n} tài liệu đã phục hồi @@ -4534,6 +4535,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 @@ -5699,6 +5703,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 @@ -5936,6 +5943,10 @@ breakText Glyphs Glyph Bow Cung Spike Đỉnh nhọn Skip Spaces Bỏ qua khoảng trắng + Release Type on a Path… Giải phóng chữ trên đường dẫn… + Release Type on a Path Giải phóng chữ trên đường dẫn + Text and Path Văn bản và đường dẫn + Path Only Chỉ đường dẫn @msg The art is too large to copy as a picture: other apps get no PNG of it Hình vẽ quá lớn để sao chép dưới dạng ảnh: các ứng dụng khác không nhận được PNG của nó # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5947,3 +5958,43 @@ breakText Glyphs Glyph Fully Outside Hoàn toàn bên ngoài No artboards match. Không có bảng vẽ nào khớp. Chosen: {n} of {total} Đã chọn: {n} trên {total} + +# Contour add-on + Contour Đường viền + Contour Tool Công cụ Đường viền + Sharp Nhọn + Bake Mở rộng + Turn the Contour into plain paths Chuyển đường viền thành các đường dẫn thường + Set Corners… Đặt góc… + All Anchors Tất cả điểm neo + Odd-Numbered Anchors Điểm neo số lẻ + Even-Numbered Anchors Điểm neo số chẵn + 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 d134298ebe..e0030aa393 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3464,6 +3464,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 大写 @@ -4047,6 +4050,7 @@ imageTrace Outline 轮廓 @msg unknown preference `{key}` 未知首选项 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 数据恢复没有可保存副本的位置:请设置“首选项 → 文件处理 → 数据恢复 → 文件夹” (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 数据恢复无法将副本保存到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 无法从 {path} 载入增效工具:{e} @msg `{area}` is no recovery area name `{area}` 不是恢复区域名称 @msg `{name}` is no recovery entry name `{name}` 不是恢复条目名称 @msg no clock to keep a heartbeat by 没有可用于维持心跳的时钟 @@ -5940,6 +5944,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` 不是颜色 @@ -6176,6 +6183,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 尖峰 Skip Spaces 跳过空格 + Release Type on a Path… 释放路径文字… + Release Type on a Path 释放路径文字 + Text and Path 文字和路径 + Path Only 仅路径 @msg The art is too large to copy as a picture: other apps get no PNG of it 图稿太大,无法作为图片复制:其他应用不会获得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6187,3 +6198,43 @@ breakText Glyphs 字形 Fully Outside 完全在外 No artboards match. 没有匹配的画板。 Chosen: {n} of {total} 已选:{n} / {total} + +# Contour add-on + Contour 轮廓 + Contour Tool 轮廓工具 + Sharp 尖角 + Bake 扩展 + Turn the Contour into plain paths 将轮廓转为普通路径 + Set Corners… 设置转角… + All Anchors 所有锚点 + Odd-Numbered Anchors 奇数锚点 + Even-Numbered Anchors 偶数锚点 + 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 b2bbeec797..36e562b2ea 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1933,6 +1933,7 @@ file-filter Templates 範本 @msg unknown preference `{key}` 未知的偏好設定 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 「資料復原」沒有可存放拷貝的位置:請設定「偏好設定 → 檔案處理 → 資料復原 → 資料夾」 (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 「資料復原」無法將拷貝存放到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 無法從 {path} 載入增效模組:{e} @msg `{area}` is no recovery area name `{area}` 不是復原區域名稱 @msg `{name}` is no recovery entry name `{name}` 不是復原項目名稱 @msg no clock to keep a heartbeat by 沒有可用來維持心跳的時鐘 @@ -4493,6 +4494,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 全部大寫 @@ -5736,6 +5740,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` 不是顏色 @@ -5973,6 +5980,10 @@ breakText Glyphs 字符 Bow 弓形 Spike 尖峰 Skip Spaces 略過空格 + Release Type on a Path… 釋放路徑文字… + Release Type on a Path 釋放路徑文字 + Text and Path 文字和路徑 + Path Only 僅路徑 @msg The art is too large to copy as a picture: other apps get no PNG of it 圖稿太大,無法作為圖片複製:其他應用程式不會取得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5984,3 +5995,43 @@ breakText Glyphs 字符 Fully Outside 完全在外 No artboards match. 沒有符合的工作區域。 Chosen: {n} of {total} 已選:{n} / {total} + +# Contour add-on + Contour 輪廓 + Contour Tool 輪廓工具 + Sharp 尖角 + Bake 展開 + Turn the Contour into plain paths 將輪廓轉為一般路徑 + Set Corners… 設定轉角… + All Anchors 所有錨點 + Odd-Numbered Anchors 奇數錨點 + Even-Numbered Anchors 偶數錨點 + 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/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 579df2187b..78eb6149d1 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -60,6 +60,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), + ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), ("dc-dash-align", include_bytes!("../../../assets/icons/dc-dash-align.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a3601af18d..e352653279 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -85,6 +85,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-eyedropper" => "pipette", "tool-measure" => "dc-measure", "tool-dimension" => "dc-dimension", + "tool-contour" => "dc-contour", "tool-blend" => "dc-blend", "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bdfcaffffa..afb8cbbc4b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -126,6 +126,10 @@ pub struct VectorcraftApp { pub session: Session, pub ui: UiState, pub views: Vec, + /// The document ([`vectorcraft_engine::DocState::uid`]) each of `views` belonged to at the last + /// [`VectorcraftApp::sync_views`], which puts the views back with their documents after + /// `document.move` reorders them (#5663). + pub(crate) view_uids: Vec, pub services: Services, pub canvas: CanvasCache, pub perf: Perf, @@ -147,6 +151,13 @@ pub struct VectorcraftApp { /// moves ([`native_menu::sync`]). run_count: u64, control_rx: Option>, + /// 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 18e77b792e..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, } } @@ -68,6 +71,9 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + crate::addons::pathtools::set_corners::COMMAND => { + (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) + } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 2d134f76f8..1bb536f76e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -494,6 +494,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.task_bar), + "window.pathfinder.compoundShapes" => flag(&mut app.ui.shape_modes_compound), "window.taskBar.pin" => { let place = &mut app.ui.task_bar_place; opt_bool(p, "pinned").map(|pinned| { @@ -577,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 2dd1051b12..78553cc7bd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -79,6 +79,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { crate::toolbar::strips(&app.ui, toolbar).iter().any(|f| f.tools.iter().any(|id| id == tool)) } "window.taskBar" => app.ui.task_bar, + "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); @@ -134,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/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index a3bda35231..44627725df 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -523,6 +523,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), ("window.taskBar", "Contextual Task Bar", "", "{}"), + ( + "window.pathfinder.compoundShapes", + "Shape Mode Buttons Make Compound Shapes", + "", + "{} toggles the Compound Shapes add-on's setting: on, the Pathfinder panel's Shape Mode buttons make a compound shape and Alt-click gives the permanent Pathfinder result; off (the default), the other way round. Members of a compound shape selected always take the mode", + ), ( "window.taskBar.pin", "Pin Bar Position", @@ -777,7 +783,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil and paintbrush, the same at any zoom; pt for smooth and blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", 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 7e0c7a12b0..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 { @@ -1238,6 +1245,8 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let suffix = ui_keys.and_then(|u| u.unit.as_deref()).map(crate::dialogs::unit_suffix).unwrap_or_default(); let nx = if vectorcraft_effects::is_length(&e.id, key, relative) { widgets::num_field(ui, id, Some(x), unit, 70.0) + } else if let Some(range) = vectorcraft_effects::raster_px_range(&e.id, key) { + widgets::range_field_named(ui, id, None, x, range, &crate::dialogs::unit_suffix("px"), 2, 70.0) } else { widgets::plain_field(ui, id, x, &suffix, 2, 70.0) }; @@ -1413,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); } @@ -1556,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(_)) => { @@ -1614,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/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 77023bacb1..deff9d8723 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -5,7 +5,8 @@ //! Artboard duplicates its artboard (as Duplicate Artboards does, with //! its art when the Artboard tool's Move/Copy Artwork with Artboard is on). The highlighted row is the active artboard, the one the status bar's navigator shows and //! Fit Artboard in Window fits: clicking a row makes it active, double-clicking its number also -//! fits it in the window. The options icon at a row's right end opens Artboard Options: a click on +//! fits it in the window. Shift-click selects a range of artboards and Ctrl/Cmd-click adds or +//! removes one, with any tool: another tool gives way to the Artboard tool first (#5698). The options icon at a row's right end opens Artboard Options: a click on //! the active artboard's icon, or a double-click on another row's icon. The lock column left of it //! shows a lock on a locked artboard, and a click there locks or unlocks the artboard //! (`artboard.setProps` with `locked`); Delete leaves locked artboards. @@ -488,6 +489,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let m = ui.input(|inp| inp.modifiers); + // A Shift- or Ctrl/Cmd-click selects several artboards with any tool: it first + // switches to the Artboard tool, which holds the selection, so Properties and the + // Control bar then show the controls that change every selected artboard. + if resp.clicked() && (m.shift || m.command) && app.session.tool_id() != "artboard" { + app.select_tool("artboard"); + } let tool = app.session.tool_id() == "artboard"; row_clicked |= resp.clicked(); if resp.clicked() && tool && m.shift { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index edae3a32e2..bf2b470503 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -156,10 +156,20 @@ fn shift_clicking_rows_selects_several_artboards() { frame(&mut app, 9.0, click(4, egui::Modifiers::NONE)); assert_eq!(picked(&app, 4), [3]); assert_eq!(highlighted(frame(&mut app, 10.0, vec![])), 1); - // With another tool, a Shift-click makes the row's artboard active, as a plain click does. + // With another tool, a plain click makes the row's artboard active and keeps the tool. app.select_tool("selection"); - frame(&mut app, 11.0, click(2, egui::Modifiers::SHIFT)); - assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1], 1)); + frame(&mut app, 11.0, click(2, egui::Modifiers::NONE)); + assert_eq!((app.session.tool_id(), selected(&app, 4)), ("selection", 1)); + // A Shift-click switches to the Artboard tool and selects the range (#5698). + frame(&mut app, 12.0, click(4, egui::Modifiers::SHIFT)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1, 2, 3], 3)); + // So does a Ctrl/Cmd-click, adding one artboard to the one active. + app.select_tool("selection"); + frame(&mut app, 13.0, click(1, egui::Modifiers::NONE)); + frame(&mut app, 14.0, click(3, egui::Modifiers::COMMAND)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![0, 2], 2)); } /// Double-clicking a row's number goes to its artboard and its name renames it; a click on diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 3ae45588b9..7e68824c19 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -590,18 +590,28 @@ fn text_key(app: &mut VectorcraftApp, k: ToolKey, m: Mods) { } fn text_paste(app: &mut VectorcraftApp, s: Option, plain: bool) { - let text_from_clip = CLIP.lock().unwrap_or_else(|e| e.into_inner()).clone(); - let s = s.unwrap_or(text_from_clip); + let s = match s { + Some(text) => text, + None if app.services.system_clipboard.is_some() => app.written_clipboard_text().unwrap_or_default(), + None => CLIP.lock().unwrap_or_else(|e| e.into_inner()).clone(), + }; if !s.is_empty() { - if plain { - app.session.set_tool_option("copy", &json!([])); - } else if let Some(runs) = CLIP_RUNS.lock().unwrap_or_else(|e| e.into_inner()).clone() { + let internal = app.type_paste_has_our_clipboard(); + let mut styled = false; + if !plain + && internal + && let Some(runs) = CLIP_RUNS.lock().unwrap_or_else(|e| e.into_inner()).clone() + { let clip_text: String = serde_json::from_value::>(runs.clone()).unwrap_or_default().into_iter().map(|r| r.text).collect(); if clip_text == s { app.session.set_tool_option("copy", &runs); + styled = true; } } + if !styled { + app.session.set_tool_option("copy", &json!([])); + } let v = app.view_info(); let target_before = crate::ime::target(&mut app.session, v); let before = crate::ime::stamp(&mut app.session, v); @@ -641,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, @@ -649,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); } } } @@ -984,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); @@ -997,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), @@ -1025,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). @@ -1212,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/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 2b71ea0545..631d38ab7f 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -41,6 +41,8 @@ use crate::{VectorcraftApp, icons}; /// Dragging a stop this far below the ramp removes it. const REMOVE_DISTANCE: f32 = 28.0; +/// The Delete Stop button beside the ramp, points square. +const DELETE_STOP_SIZE: f32 = 22.0; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; /// The Aspect Ratio field's preset menu, percent. @@ -280,7 +282,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if hidden { if !freeform { ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); } return; } @@ -358,7 +360,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); ui.add_space(4.0); stop_fields(app, ui, &g.gradient, is_grad); // Dither applies to gradient fills only: off and dimmed behind the Stroke proxy. @@ -569,7 +571,7 @@ fn thumbnail(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: } /// The selected stop's colour (click: its popover; the eyedropper samples one from the art), -/// opacity and location (a selected diamond's midpoint instead), and Delete Stop. +/// opacity and location (a selected diamond's midpoint instead). fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { let stops = &g.stops; let sel = app.session.selected_stop().filter(|i| *i < stops.len() && is_grad); @@ -623,14 +625,29 @@ fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } } }); - let can_del = sel.is_some() && stops.len() > MIN_STOPS; - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, 22.0).clicked() - && let Some(i) = sel - && let Some(v) = remove_stop(stops, i) - { - let next = i.min(v.len() - 1); - set_stops(app, &v, Some(next), Live::Released); - } + }); +} + +/// The ramp with Delete Stop at its right end, level with the ramp so it shows whenever the ramp +/// does: it deletes the selected stop, never below two. +fn ramp_row(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let w = (ui.available_width() - DELETE_STOP_SIZE).max(DELETE_STOP_SIZE * 2.0); + ramp(app, ui, g, is_grad, w); + ui.vertical(|ui| { + // Level with the ramp (the bar starts 10 points down and is 18 tall). + ui.add_space(8.0); + let sel = app.session.selected_stop().filter(|i| *i < g.stops.len() && is_grad); + let can_del = sel.is_some() && g.stops.len() > MIN_STOPS; + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, DELETE_STOP_SIZE).clicked() + && let Some(i) = sel + && let Some(v) = remove_stop(&g.stops, i) + { + let next = i.min(v.len().saturating_sub(1)); + set_stops(app, &v, Some(next), Live::Released); + } + }); }); } @@ -709,10 +726,9 @@ fn dropped_swatch(app: &VectorcraftApp, ui: &Ui, g: &Gradient, area_resp: &egui: Some(drop_color(g, g.stops.iter().position(|s| marker(s.offset).contains(p)), x_to_offset(p.x, bar.left(), bar.width()), c, link)) } -/// The gradient slider: ramp, stops below, midpoint diamonds above. -fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { +/// The gradient slider, `w` points wide: ramp, stops below, midpoint diamonds above. +fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool, w: f32) { let t = Tokens::get(ui.ctx()); - let w = ui.available_width(); let (area, area_resp) = ui.allocate_exact_size(vec2(w, 50.0), Sense::hover()); let bar = Rect::from_min_size(area.min + vec2(8.0, 10.0), vec2(w - 16.0, 18.0)); paint_ramp(ui, g, bar); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 83a290bb1d..65602079b8 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -726,3 +726,39 @@ fn the_panel_menu_saves_deletes_and_hides_presets() { p.menu_click(&mut app, text_at(&texts, "Show Presets").unwrap()); assert!(text_at(&p.frame(&mut app, vec![], Modifiers::NONE), "Presets:").is_some()); } + +/// A stop is deleted by dragging it down off the ramp or with Delete Stop, which sits at the +/// ramp's right end (so a short panel doesn't hide it below the stop fields, #5403); one undo +/// step each, and a two-stop gradient keeps both. +#[test] +fn a_stop_dragged_off_the_ramp_or_deleted_with_the_button_beside_it_goes() { + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let mid = p.widget(("grad-stop", 1)).center(); + // Dragged down off the ramp, the middle stop goes. + p.drag(&mut app, mid, mid + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + // Delete Stop, level with the ramp and right of it, removes the selected stop. + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + let bar = p.widget("grad-bar"); + let del = *p.row_after(bar.left_center(), 22.0).last().expect("Delete Stop beside the ramp"); + assert!(del.left() >= bar.right(), "right of the ramp"); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + app.run("edit.redo", json!({})).unwrap(); + // Two stops stay two: dragged off, the stop comes back, and the button is off. + let first = p.widget(("grad-stop", 0)).center(); + p.drag(&mut app, first, first + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); +} diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 8f87786892..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, 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; @@ -184,6 +184,7 @@ pub(crate) const ROW_KEYS: &str = "ly-keys"; /// The Layers panel: the layer tree with its click, drag and rename rules and the bottom buttons; Delete/Backspace after a row click delete the highlighted rows. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); + show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(st) = app.session.active() else { return }; // A rename belongs to the document it started in (node ids are per document): drop it when // another document shows, so it can't rename that document's node with the same id. 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 297afd6936..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(); @@ -239,6 +300,42 @@ fn row_thumbnails_wait_for_the_end_of_a_drag() { assert_eq!(renders(), after, "once"); } +#[test] +fn the_row_thumbnails_follow_the_document_shown_and_none_once_it_closes() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let showing = || THUMBS.with(|c| c.borrow().showing); + frame(&mut app, &ctx, vec![], false); + let first = app.session.active().map(|st| st.uid); + assert_eq!(showing(), first); + // With no thumbnails drawn, the panel still tells which document it shows. + let p = &mut app.ui.layers_panel; + (p.thumb_layers, p.thumb_groups, p.thumb_objects) = (false, false, false); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + frame(&mut app, &ctx, vec![], false); + let second = app.session.active().map(|st| st.uid); + assert_ne!(second, first); + assert_eq!(showing(), second, "the new document's rows are drawn"); + for _ in 0..2 { + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + } + frame(&mut app, &ctx, vec![], false); + assert_eq!(showing(), None, "no document is shown once both close"); + + // The Links panel alone does the same. + let links = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::links::show(app, ui)); + out.textures_delta.clear(); + }; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + links(&mut app); + assert_eq!(showing(), app.session.active().map(|st| st.uid)); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + links(&mut app); + assert_eq!(showing(), None, "the Links panel shows no document"); +} + #[test] fn clicking_a_target_circle_targets_the_layer() { let (mut app, layer, [a, b]) = two_rects(); diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index adcadd6a26..49ce4b61b9 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -1,4 +1,9 @@ +use std::collections::HashSet; +use vectorcraft_doc::{NodeKind, TextKind}; +use vectorcraft_geom::PathData; + use super::{Arc, Color32, Document, HashMap, Node, NodeId, Settle, ThumbWorker, Ui, VectorcraftApp, Weak, vec2}; +use crate::thumb_worker::Done; /// Where row thumbnails come from: document `uid` at `revision`, and whether a drag is in /// progress (the thumbnails shown then stay until it ends). @@ -47,10 +52,14 @@ 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>, worker_started: bool, + /// The uid of the document whose rows were last drawn: the worker holds jobs for it alone. + pub(super) showing: Option, settle: Settle, /// (pass, ms, count) rendered on the UI thread in that pass. spent: (u64, f64, u32), @@ -71,6 +80,32 @@ const LIGHT_THUMB_MS: f64 = 4.0; /// A node with more objects than this inside has its first thumbnail made on the worker. const LIGHT_THUMB_NODES: usize = 200; +/// A node whose paths have more anchors than this in all has its first thumbnail made on the +/// worker. Type's glyphs, mesh points and image pixels count against it too, each as the anchors +/// that take about as long to render: [`GLYPH_ANCHORS`], [`MESH_POINT_ANCHORS`] and +/// [`IMAGE_PIXELS_PER_ANCHOR`]. +const LIGHT_THUMB_ANCHORS: usize = 2_000; + +/// Anchors one glyph of type counts as. +const GLYPH_ANCHORS: usize = 4; + +/// Anchors one point of a gradient mesh counts as. +const MESH_POINT_ANCHORS: usize = 1; + +/// Pixels of an image that count as one anchor. +const IMAGE_PIXELS_PER_ANCHOR: usize = 100; + +/// The most symbols and placed documents counted inside one another: a node holding them deeper +/// (a symbol whose art holds an instance of itself, for one) has its first thumbnail made on the +/// worker. +const MAX_THUMB_NESTING: usize = 8; + +/// The most steps counting a node takes: each object, subpath, text run and symbol looked at is +/// one step, and so is every 64 bytes of a symbol or placed file name looked up. A node that +/// needs more has its thumbnail made on the worker, and the painted thumbnail draws nothing for +/// it. A row drawn before counts at most this many objects too. +const THUMB_COUNT_STEPS: usize = 20_000; + /// At most this long (ms) and this many thumbnails are rendered on the UI thread in a pass; the /// rest go to the worker, or wait for the next pass where there is none. const THUMB_BUDGET_MS: f64 = 8.0; @@ -82,25 +117,185 @@ pub(crate) fn thumb_options() -> vectorcraft_render::RenderOptions { vectorcraft_render::RenderOptions { image_mips: true, ..Default::default() } } -/// Has `n` at most `limit` objects inside it (counting stops there)? -fn small_node(n: &Node, limit: usize) -> bool { - fn count(n: &Node, left: &mut usize) -> bool { - for c in n.children().into_iter().flatten() { - if *left == 0 { +/// Has `n` at most `nodes` objects inside it, and at most `anchors` anchors in its paths and the +/// paths inside it, the frames of area type and the paths of type on a path included (counting +/// stops at either limit)? With `masks`, the art of the opacity masks that are not disabled, and +/// the objects and anchors inside it, count as well. With `doc` (the document `n` is in), type's +/// glyphs, mesh points and image pixels count as anchors too ([`LIGHT_THUMB_ANCHORS`]), and a +/// symbol instance and a placed document count the objects and anchors of the art they show: the +/// symbol's art in `doc`, and the placed file's art when it has been read (a placed document whose +/// file has not been read, or art nested deeper than [`MAX_THUMB_NESTING`], is not small). A node +/// that takes more than [`THUMB_COUNT_STEPS`] steps to count is not small. +fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> bool { + weigh(n, nodes, anchors, masks, doc).0 +} + +/// [`small_node`], and the steps counting took. +fn weigh(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> (bool, usize) { + /// What may still be counted. + struct Left { + nodes: usize, + anchors: usize, + steps: usize, + masks: bool, + } + impl Left { + /// Count `anchors` more: false past the limit. + fn take(&mut self, anchors: usize) -> bool { + match self.anchors.checked_sub(anchors) { + Some(left) => { + self.anchors = left; + true + } + None => false, + } + } + /// Take `steps` more: false past the limit. + fn step(&mut self, steps: usize) -> bool { + match self.steps.checked_sub(steps) { + Some(left) => { + self.steps = left; + true + } + None => false, + } + } + /// Look up `name`: false past the step limit. + fn look_up(&mut self, name: &str) -> bool { + self.step(1 + name.len() / 64) + } + /// Count one more object: false past the limit. + fn object(&mut self) -> bool { + match self.nodes.checked_sub(1) { + Some(left) => { + self.nodes = left; + true + } + None => false, + } + } + /// Count the anchors of `p`, a step for each subpath. + fn path(&mut self, p: &PathData) -> bool { + p.subpaths.iter().all(|s| self.step(1) && self.take(s.anchors.len())) + } + } + /// Count `art`, drawn in place of an object (`doc` its document), one level deeper. + fn inside(art: &Node, doc: &Document, left: &mut Left, depth: usize) -> bool { + depth < MAX_THUMB_NESTING && left.object() && count(art, Some(doc), left, depth + 1) + } + /// Count symbol `name` of `doc` (one that doesn't exist draws nothing). + fn symbol(name: &str, doc: &Document, left: &mut Left, depth: usize) -> bool { + for s in &doc.symbols { + if !left.look_up(name) { return false; } - *left -= 1; - if !count(c, left) { - return false; + if s.name == name { + return inside(&s.art, doc, left, depth); } } true } - let mut left = limit; - count(n, &mut left) + /// Count what `n` draws besides its children. + fn own(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + let path = match &n.kind { + NodeKind::Text(t) => match &t.kind { + TextKind::Area { frame: p } | TextKind::OnPath { path: p, .. } => Some(p), + TextKind::Point => None, + }, + _ => n.path_data(), + }; + if !path.is_none_or(|p| left.path(p)) { + return false; + } + let Some(doc) = doc else { return true }; + match &n.kind { + // Glyphs are counted only up to one past what the anchors left allow. + NodeKind::Text(t) => t.runs.iter().all(|r| { + let glyphs = r.text.chars().take(left.anchors / GLYPH_ANCHORS + 1).count(); + left.step(1) + && left.take(glyphs.saturating_mul(GLYPH_ANCHORS)) + && r.inline.as_ref().is_none_or(|a| symbol(&a.symbol, doc, left, depth)) + }), + NodeKind::SymbolInstance { symbol: name, .. } => symbol(name, doc, left, depth), + NodeKind::Mesh(m) => left.take(m.points.len().saturating_mul(MESH_POINT_ANCHORS)), + NodeKind::Image(im) => left.take((im.width as usize).saturating_mul(im.height as usize) / IMAGE_PIXELS_PER_ANCHOR), + NodeKind::PlacedDocument(p) => { + left.look_up(&p.key) && vectorcraft_doc::placed_document::read_cached(p).is_some_and(|e| inside(&e.art, &e.doc, left, depth)) + } + _ => true, + } + } + fn count(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + if !(left.step(1) && own(n, doc, left, depth)) { + return false; + } + let mask = n.extras().mask.as_deref().filter(|m| left.masks && !m.disabled).map(|m| &m.art); + n.children().into_iter().flatten().chain(mask).all(|c| left.object() && count(c, doc, left, depth)) + } + let mut left = Left { nodes, anchors, steps: THUMB_COUNT_STEPS, masks }; + let small = count(n, doc, &mut left, 0); + (small, THUMB_COUNT_STEPS - left.steps) +} + +/// Is row `n` (an object of `doc`) light enough to make its thumbnail on the UI thread? `quick`: +/// whether its last thumbnail was quick to render, if it has one. +fn light_row(n: &Node, quick: Option, doc: &Document) -> bool { + match quick { + Some(quick) => quick && small_node(n, THUMB_COUNT_STEPS, LIGHT_THUMB_ANCHORS, true, Some(doc)), + None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)), + } +} + +/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or the worker. +fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option { + r.render_node_thumbnail_with(doc, n, px, None, &thumb_options()) } 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); @@ -129,6 +324,36 @@ 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 of still-open documents stay. + pub(super) fn show(&mut self, uid: Option) { + if self.showing == uid { + return; + } + self.showing = uid; + self.pending.retain(|key, _| Some(key.0) == uid); + if let Some(w) = &self.worker + && !w.discard(move |key| Some(key.0) != uid) + { + self.worker = None; + self.pending.clear(); + } + } + + /// 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); + } + self.upload(ctx, key, node, px, d.img.as_ref(), d.ms); + } + /// The texture of row `n` (`px` pixels square) to draw: made or updated now, or on the /// worker (the old one is drawn meanwhile). Thumbnails shown stay during a drag and until /// the document settles. @@ -148,12 +373,9 @@ impl Thumbs { None => vec![], }; for d in done { - let (key, node, px) = d.key; - if self.pending.get(&key).is_some_and(|(p, ppx)| p.ptr_eq(&node) && *ppx == px) { - self.pending.remove(&key); - } - self.upload(ctx, key, node, px, d.img.as_ref(), d.ms); + self.receive(ctx, d); } + self.show(Some(src.uid)); let key = (src.uid, n.id); let pass = ctx.cumulative_pass_nr(); let (fresh, light) = match self.entries.get_mut(&key) { @@ -174,11 +396,13 @@ impl Thumbs { self.spent = (pass, 0.0, 0); } let in_budget = self.spent.1 < THUMB_BUDGET_MS && self.spent.2 < THUMB_BUDGET_COUNT; - let light = light.unwrap_or_else(|| small_node(n, LIGHT_THUMB_NODES)) && in_budget; + // A row drawn before is light when its last thumbnail was quick to render, unless its + // object now has more anchors than the limit. + let light = light_row(n, light, src.doc) && in_budget; if !light && let Some(w) = &self.worker { let (doc, node) = (src.doc.clone(), n.clone()); let job: ThumbJob = (key, Arc::downgrade(n), px); - if w.submit(key, job, Box::new(move |r| r.render_node_thumbnail_with(&doc, &node, px, None, &thumb_options()))) { + if w.submit(key, job, Box::new(move |r| render_thumb(r, &doc, &node, px))) { self.pending.insert(key, (Arc::downgrade(n), px)); return shown; } @@ -193,7 +417,7 @@ impl Thumbs { static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } let t0 = crate::now_ms(); - let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(src.doc, n, px, None, &thumb_options())); + let img = RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), src.doc, n, px)); let ms = crate::now_ms() - t0; self.spent.1 += ms; self.spent.2 += 1; @@ -203,6 +427,17 @@ impl Thumbs { } } +/// The Layers or Links panel shows the rows of document `uid` in this frame (None: no document +/// is open), whether or not a thumbnail is drawn; see [`Thumbs::show`]. +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. @@ -221,8 +456,14 @@ pub(crate) fn real_thumb(ui: &Ui, src: &ThumbSource, n: &Arc, r: egui::Rec } } -/// Tiny vector thumbnail painted with egui (fallback when rendering isn't possible). +/// Tiny vector thumbnail painted with egui (fallback when rendering isn't possible). A node with +/// more than [`LIGHT_THUMB_ANCHORS`] anchors, or that takes more than [`THUMB_COUNT_STEPS`] steps +/// to count, paints nothing, since this runs on every frame and +/// measuring its bounds takes time in proportion to its anchor count. pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { + if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false, None) { + return; + } let Some(b) = n.visual_bounds() else { return }; let s = ((r.width() - 3.0) as f64 / b.width().max(b.height()).max(1e-6)) as f32; let off = r.center() - vec2(b.center().x as f32 * s, b.center().y as f32 * s); @@ -245,3 +486,528 @@ pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { } }); } + +#[cfg(test)] +mod tests { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, CharStyle, LayerColor, NodeKind, OpacityMask, TextKind, TextObject}; + use vectorcraft_geom::{Affine, Point, SubPath}; + + 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(); + PathData::single(SubPath::polyline(&pts, false)) + } + + /// An open stroked path `id` of `anchors` anchors. + fn path(id: u64, anchors: usize) -> Node { + Node::path(NodeId(id), line(anchors), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)) + } + + /// Area type `id` whose frame has `anchors` anchors. + fn area_type(id: u64, anchors: usize) -> Node { + typed(id, TextKind::Area { frame: line(anchors) }) + } + + /// Type on a path `id` whose path has `anchors` anchors. + fn path_type(id: u64, anchors: usize) -> Node { + typed(id, TextKind::OnPath { path: line(anchors), start: 0.0, end: None }) + } + + fn typed(id: u64, kind: TextKind) -> Node { + let mut t = TextObject::point(Point::ZERO, "Type", CharStyle::default()); + t.kind = kind; + Node::new(NodeId(id), NodeKind::Text(Box::new(t))) + } + + fn rect(id: u64) -> Node { + let r = vectorcraft_geom::rect_from_points(Point::new(0.0, 0.0), Point::new(10.0, 10.0)); + Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0)) + } + + fn small(n: &Node) -> bool { + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, None) + } + + /// Is `n`, an object of `doc`, small? + fn small_in(doc: &Document, n: &Node) -> bool { + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)) + } + + /// `n` with an opacity mask of `art`, disabled or not. + fn masked(mut n: Node, art: Node, disabled: bool) -> Node { + let mut m = OpacityMask::new(art, true); + m.disabled = disabled; + n.extras_mut().mask = Some(Box::new(m)); + n + } + + #[test] + fn the_anchors_of_an_opacity_mask_count_unless_it_is_disabled() { + let long = || path(2, LIGHT_THUMB_ANCHORS + 1); + assert!(!small(&masked(rect(1), long(), false)), "a small object with a long mask"); + assert!(small(&masked(rect(1), long(), true)), "a small object with a long mask that is disabled"); + let inner = Node::group(NodeId(3), vec![Arc::new(long())]); + assert!(!small(&masked(rect(1), inner, false)), "a mask holding a long path"); + let child = Node::group(NodeId(1), vec![Arc::new(masked(rect(4), long(), false))]); + assert!(!small(&child), "a group holding an object with a long mask"); + assert!(small_node(&masked(rect(1), long(), false), usize::MAX, LIGHT_THUMB_ANCHORS, false, None), "masks left out"); + } + + #[test] + fn the_first_thumbnail_goes_to_the_worker_by_anchors_as_well_as_objects() { + assert!(!small(&path(1, LIGHT_THUMB_ANCHORS + 1)), "one long path"); + assert!(small(&path(1, LIGHT_THUMB_ANCHORS)), "a path of as many anchors as the limit"); + let group = |n: usize| Node::group(NodeId(1), (0..n).map(|i| Arc::new(rect(i as u64 + 2))).collect()); + assert!(small(&group(LIGHT_THUMB_NODES)), "many small objects"); + assert!(!small(&group(LIGHT_THUMB_NODES + 1)), "more objects than the limit"); + assert!(small(&Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0))), "an empty layer"); + let inner = Node::group(NodeId(2), vec![Arc::new(path(3, LIGHT_THUMB_ANCHORS + 1))]); + assert!(!small(&Node::group(NodeId(1), vec![Arc::new(rect(4)), Arc::new(inner)])), "a group holding a long path"); + let halves = Node::group(NodeId(1), vec![Arc::new(path(2, LIGHT_THUMB_ANCHORS / 2)), Arc::new(path(3, LIGHT_THUMB_ANCHORS / 2 + 1))]); + assert!(!small(&halves), "paths whose anchors together pass the limit"); + assert!(small(&area_type(1, LIGHT_THUMB_ANCHORS)), "area type whose frame has as many anchors as the limit"); + assert!(!small(&area_type(1, LIGHT_THUMB_ANCHORS + 1)), "area type with a long frame"); + assert!(small(&path_type(1, LIGHT_THUMB_ANCHORS)), "type on a path of as many anchors as the limit"); + assert!(!small(&path_type(1, LIGHT_THUMB_ANCHORS + 1)), "type on a long path"); + let both = Node::group(NodeId(1), vec![Arc::new(path(2, LIGHT_THUMB_ANCHORS / 2)), Arc::new(area_type(3, LIGHT_THUMB_ANCHORS / 2 + 1))]); + assert!(!small(&both), "a path and an area frame whose anchors together pass the limit"); + } + + /// Point type `id` of `glyphs` glyphs. + fn glyphs(id: u64, glyphs: usize) -> Node { + let t = TextObject::point(Point::ZERO, &"a".repeat(glyphs), CharStyle::default()); + Node::new(NodeId(id), NodeKind::Text(Box::new(t))) + } + + /// A gradient mesh `id` of `rows` x `rows` patches. + fn mesh(id: u64, rows: u32) -> Node { + let m = vectorcraft_doc::GradientMesh::from_surface(rows, rows, &|u, v| Point::new(u * 100.0, v * 100.0), &|_, _| Color::BLACK); + Node::new(NodeId(id), NodeKind::Mesh(m)) + } + + /// An image `id` of `w` x `h` pixels. + fn image(id: u64, w: u32, h: u32) -> Node { + let im = vectorcraft_doc::ImageObject { + key: "im".into(), + width: w, + height: h, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(NodeId(id), NodeKind::Image(Box::new(im))) + } + + /// An instance `id` of symbol `name`. + fn instance(id: u64, name: &str) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) + } + + /// A document whose symbol `name` is `art`. + fn with_symbol(name: &str, art: Node) -> Document { + let mut doc = Document::new(200.0, 200.0); + doc.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); + doc + } + + /// A placed document `id` showing file `key`, read already when `art` is given. + fn placed(id: u64, key: &str, art: Option) -> Node { + let p = vectorcraft_doc::PlacedDocument { + link: vectorcraft_doc::LinkInfo::new("/art/placed.vectorcraft"), + key: key.into(), + bounding: false, + page_box: Default::default(), + width: 100.0, + height: 100.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + if let Some(art) = art { + let frame = vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0); + vectorcraft_doc::placed_document::prime(&p, Arc::new(key.as_bytes().to_vec()), (Document::new(100.0, 100.0), art, frame)); + } + Node::new(NodeId(id), NodeKind::PlacedDocument(Box::new(p))) + } + + #[test] + fn type_meshes_and_images_count_their_work_as_anchors() { + let doc = Document::new(200.0, 200.0); + let limit = LIGHT_THUMB_ANCHORS / GLYPH_ANCHORS; + assert!(small_in(&doc, &glyphs(1, limit)), "type of as many glyphs as the limit"); + assert!(!small_in(&doc, &glyphs(1, limit + 1)), "type of more glyphs"); + assert!(!small_in(&doc, &glyphs(1, 5_000)), "long type"); + let beside = Node::group(NodeId(1), vec![Arc::new(glyphs(2, limit / 2)), Arc::new(path(3, LIGHT_THUMB_ANCHORS / 2 + 1))]); + assert!(!small_in(&doc, &beside), "type and a path that together pass the limit"); + // (rows + 1)² points: 1,936 and 2,025. + assert!(small_in(&doc, &mesh(1, 43)), "a small mesh"); + assert!(!small_in(&doc, &mesh(1, 44)), "a mesh of more points"); + let px = (LIGHT_THUMB_ANCHORS * IMAGE_PIXELS_PER_ANCHOR) as u32; + assert!(small_in(&doc, &image(1, px / 100, 100)), "an image of as many pixels as the limit"); + assert!(!small_in(&doc, &image(1, px / 100, 101)), "a larger image"); + assert!(!small_in(&doc, &image(1, 4_000, 3_000)), "a photo"); + // Without the document only paths and frames count, as the painted thumbnail needs. + assert!(small(&glyphs(1, 5_000)) && small(&mesh(1, 100)) && small(&image(1, 4_000, 3_000))); + } + + #[test] + fn a_symbol_instance_and_a_placed_document_count_the_art_they_show() { + let doc = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&doc, &instance(1, "Long")), "an instance of a symbol of a long path"); + assert!(small(&instance(1, "Long")), "without the document"); + assert!(small_in(&doc, &instance(1, "Missing")), "an instance of a symbol that doesn't exist"); + let doc = with_symbol("Short", path(10, LIGHT_THUMB_ANCHORS)); + assert!(small_in(&doc, &instance(1, "Short")), "an instance of a symbol of a path at the limit"); + let two = Node::group(NodeId(1), vec![Arc::new(instance(2, "Short")), Arc::new(instance(3, "Short"))]); + assert!(!small_in(&doc, &two), "two instances whose art together passes the limit"); + let many = with_symbol("Group", Node::group(NodeId(10), (0..LIGHT_THUMB_NODES).map(|i| Arc::new(rect(i as u64 + 11))).collect())); + assert!(!small_in(&many, &instance(1, "Group")), "a symbol of more objects than the limit"); + // Inline graphics in type draw their symbol too. + let mut t = TextObject::point(Point::ZERO, "a", CharStyle::default()); + t.runs[0].inline = Some(vectorcraft_doc::InlineArt { symbol: "Long".into(), scale: 1.0, baseline_shift: 0.0, bounds: None }); + let long = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&long, &Node::new(NodeId(1), NodeKind::Text(Box::new(t)))), "type showing a long symbol inline"); + + let doc = Document::new(200.0, 200.0); + assert!(small_in(&doc, &placed(1, "thumbs-small-placed", Some(path(10, LIGHT_THUMB_ANCHORS)))), "a placed file of a short path"); + assert!(!small_in(&doc, &placed(1, "thumbs-long-placed", Some(path(10, LIGHT_THUMB_ANCHORS + 1)))), "a placed file of a long path"); + assert!(!small_in(&doc, &placed(1, "thumbs-unread-placed", None)), "a placed file not read yet"); + } + + #[test] + fn a_symbol_that_holds_itself_is_not_small_and_is_counted_to_an_end() { + let doc = with_symbol("Loop", Node::group(NodeId(10), vec![Arc::new(rect(11)), Arc::new(instance(12, "Loop"))])); + assert!(!small_in(&doc, &instance(1, "Loop"))); + assert!(!small_node(&instance(1, "Loop"), usize::MAX, usize::MAX, true, Some(&doc)), "without limits on objects and anchors"); + // Nested as deep as counted, the art is small. + let mut doc = with_symbol("S0", rect(10)); + for i in 1..MAX_THUMB_NESTING { + let art = Node::group(NodeId(10 + i as u64), vec![Arc::new(instance(100 + i as u64, &format!("S{}", i - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("S{i}"), art: Arc::new(art), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, &format!("S{}", MAX_THUMB_NESTING - 1))), "symbols as deep as counted"); + let art = Node::group(NodeId(9), vec![Arc::new(instance(99, &format!("S{}", MAX_THUMB_NESTING - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: "Deeper".into(), art: Arc::new(art), dynamic: false }); + assert!(!small_in(&doc, &instance(1, "Deeper")), "one level deeper"); + } + + /// A document of symbols `L0` to `L{levels}`: `L0` is an empty group, and each one above it a + /// group of `fan` instances of the one below. + fn fan_out(levels: usize, fan: usize) -> Document { + let mut doc = with_symbol("L0", Node::group(NodeId(10), vec![])); + let mut id = 100; + for level in 1..=levels { + let below = format!("L{}", level - 1); + let kids = (0..fan) + .map(|_| { + id += 1; + Arc::new(instance(id, &below)) + }) + .collect(); + id += 1; + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("L{level}"), art: Arc::new(Node::group(NodeId(id), kids)), dynamic: false }); + } + doc + } + + #[test] + fn symbols_that_each_hold_many_instances_are_counted_within_the_step_limit() { + // 40 instances on each of 4 levels: 40⁴ (2,560,000) empty groups, and no anchors. + let doc = fan_out(4, 40); + let top = instance(1, "L4"); + assert!(!light_row(&top, Some(true), &doc), "a row drawn before, quick to render"); + assert!(!light_row(&top, None, &doc), "a row not drawn yet"); + let (small, steps) = weigh(&top, THUMB_COUNT_STEPS, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps"); + let (small, steps) = weigh(&top, usize::MAX, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps without a limit on objects"); + // 5 instances on each of 3 levels stay light once drawn quickly. + let doc = fan_out(3, 5); + assert!(light_row(&instance(1, "L3"), Some(true), &doc)); + assert!(!light_row(&instance(1, "L3"), Some(false), &doc), "drawn slowly"); + } + + #[test] + fn empty_subpaths_text_runs_and_symbol_lookups_take_steps() { + let doc = Document::new(200.0, 200.0); + let style = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let empty = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); THUMB_COUNT_STEPS]), style.clone()); + assert!(!small_in(&doc, &empty), "a path of many empty subpaths"); + let fewer = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); 100]), style); + assert!(small_in(&doc, &fewer), "a path of a few"); + let mut t = TextObject::point(Point::ZERO, "", CharStyle::default()); + t.runs = vec![vectorcraft_doc::TextRun::new("", CharStyle::default()); THUMB_COUNT_STEPS]; + assert!(!small_in(&doc, &Node::new(NodeId(2), NodeKind::Text(Box::new(t)))), "type of many empty runs"); + let mut doc = with_symbol("S", rect(10)); + for i in 0..THUMB_COUNT_STEPS { + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("Other {i}"), art: Arc::new(rect(11)), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, "S")), "the first of many symbols"); + assert!(!small_in(&doc, &instance(1, &format!("Other {}", THUMB_COUNT_STEPS - 1))), "the last of many symbols"); + } + + #[test] + fn the_painted_thumbnail_leaves_out_a_long_path() { + let ctx = egui::Context::default(); + let painted = |n: &Node| { + let r = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(24.0, 24.0)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| thumb(ui, n, r)); + out.textures_delta.clear(); + out.shapes.len() + }; + let none = painted(&Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0))); + assert_eq!(painted(&rect(1)), none + 1, "a small path is painted"); + assert_eq!(painted(&path(1, LIGHT_THUMB_ANCHORS)), none + 1, "a path of as many anchors as the limit"); + assert_eq!(painted(&path(1, LIGHT_THUMB_ANCHORS + 1)), none, "a long path is not"); + // Type is not painted, so each holds a small path beside it: the group is painted only + // while the type's frame or path keeps the anchors in all within the limit. + let left = LIGHT_THUMB_ANCHORS - rect(2).path_data().map_or(0, PathData::anchor_count); + let beside = |typ: Node| Node::group(NodeId(1), vec![Arc::new(rect(2)), Arc::new(typ)]); + assert_eq!(painted(&beside(area_type(3, left))), none + 1, "area type whose frame keeps the group at the limit"); + assert_eq!(painted(&beside(area_type(3, left + 1))), none, "area type with a long frame"); + assert_eq!(painted(&beside(path_type(3, left))), none + 1, "type on a path that keeps the group at the limit"); + assert_eq!(painted(&beside(path_type(3, left + 1))), none, "type on a long path"); + } + + /// A document with `n` on its layer, and `n` as the layer holds it. + fn doc_with(n: impl FnOnce(NodeId) -> Node) -> (Arc, Arc) { + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, n(id)).unwrap(); + let doc = Arc::new(doc); + let node = node_arc(&doc, id).unwrap(); + (doc, node) + } + + #[test] + fn a_long_paths_thumbnail_is_made_on_the_worker_and_matches_one_made_here() { + 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() }; + let (doc, n) = doc_with(|id| path(id.0, 50_000)); + let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false }; + assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made"); + assert_eq!(thumbs.renders, 0, "not made on this thread"); + assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker"); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it"); + let there = done.img.as_ref().expect("the worker draws the path"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the path"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + thumbs.receive(&ctx, done); + assert!(thumbs.pending.is_empty()); + assert!(thumbs.texture(&ctx, &src, &n, 24).is_some(), "the worker's thumbnail is shown"); + assert_eq!(thumbs.renders, 0, "and not made again here"); + + // A small object's thumbnail is still made on this thread, at once. + let (doc, n) = doc_with(|id| rect(id.0)); + let src = ThumbSource { uid: 2, revision: 1, doc: &doc, busy: false }; + assert!(thumbs.texture(&ctx, &src, &n, 24).is_some()); + assert_eq!(thumbs.renders, 1); + assert!(thumbs.pending.is_empty()); + } + + /// A document of `rows` paths of 5,000 anchors on its layer, and the paths as the layer holds + /// them. + fn long_paths(rows: usize) -> (Arc, Vec>) { + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers.first().map(|l| l.id); + let ids: Vec = (0..rows) + .map(|_| { + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, path(id.0, 5_000)).unwrap(); + id + }) + .collect(); + let doc = Arc::new(doc); + let nodes = ids.iter().filter_map(|id| node_arc(&doc, *id)).collect(); + (doc, nodes) + } + + /// Keep the worker of `thumbs` busy with a job of row (0, 0) until the sender returned sends, + /// so the jobs submitted meanwhile wait in its queue. + fn hold(thumbs: &Thumbs) -> std::sync::mpsc::Sender<()> { + let (started, running) = std::sync::mpsc::channel::<()>(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let key = (0, NodeId(0)); + 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"); + release + } + + /// The next job `thumbs`'s worker finishes, checked against the thumbnail of the same node in + /// `rows` of `doc` made on this thread, then kept. + fn receive_checked(ctx: &egui::Context, thumbs: &mut Thumbs, uid: u64, doc: &Document, rows: &[Arc]) { + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes a job"); + assert_eq!(done.key.0.0, uid, "a job of document {uid} is done next"); + let n = rows.iter().find(|n| n.id == done.key.0.1).expect("one of its rows"); + let there = done.img.as_ref().expect("the worker draws the path"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, 24).expect("this thread draws the path"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + thumbs.receive(ctx, done); + } + + #[test] + fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() { + 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() }; + let (a, a_rows) = long_paths(3); + let (b, b_rows) = long_paths(2); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.len(), 3, "document 1's rows wait on the worker"); + // Document 2 shows before the worker gets to them. + let src_b = ThumbSource { uid: 2, revision: 1, doc: &b, busy: false }; + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().map(|k| k.0).collect::>(), [2, 2], "only the shown document's rows are pending"); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + for _ in &b_rows { + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown"); + } + // Shown again, document 1's rows are asked for again and come back. + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3); + for _ in &a_rows { + receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows); + } + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_some()); + } + // Document 2's thumbnails were kept: showing it again asks for nothing. + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some()); + } + assert!(thumbs.pending.is_empty()); + assert_eq!(thumbs.renders, 0, "none was made on this thread"); + } + + #[test] + fn the_queued_thumbnails_of_a_closed_document_are_dropped() { + 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() }; + let (a, a_rows) = long_paths(3); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + thumbs.texture(&ctx, &src_a, n, 24); + } + // The document closes and no other shows. + thumbs.show(None); + assert!(thumbs.pending.is_empty()); + // A job queued after it, straight on the worker, comes back next. + let (b, b_rows) = long_paths(1); + let (doc, node) = (b.clone(), b_rows[0].clone()); + let key = (2, node.id); + let job: crate::thumb_worker::JobFn = Box::new(move |r| render_thumb(r, &doc, &node, 24)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Arc::downgrade(&b_rows[0]), 24), job))); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + + #[test] + fn an_instance_of_a_long_symbols_thumbnail_is_made_on_the_worker_and_matches_one_made_here() { + 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() }; + let mut doc = with_symbol("Long", path(900, 50_000)); + let layer = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, instance(id.0, "Long")).unwrap(); + let doc = Arc::new(doc); + let n = node_arc(&doc, id).unwrap(); + let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false }; + assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made"); + assert_eq!(thumbs.renders, 0, "not made on this thread"); + assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker"); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it"); + let there = done.img.as_ref().expect("the worker draws the symbol"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the symbol"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the symbol's art"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + } + + #[test] + fn a_row_whose_object_becomes_a_long_path_is_drawn_again_on_the_worker() { + 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() }; + let (doc, n) = doc_with(|id| path(id.0, 50_000)); + let key = (1, n.id); + // The row's last thumbnail showed a small object and took no time to render. + let before = Arc::new(rect(n.id.0)); + thumbs.upload(&ctx, key, Arc::downgrade(&before), 24, None, 0.0); + let src = ThumbSource { uid: 1, revision: 2, doc: &doc, busy: false }; + // The document reached this revision long before now, so it has settled. + thumbs.settle.settled(&ctx, 1, 2, f64::NEG_INFINITY); + thumbs.texture(&ctx, &src, &n, 24); + assert_eq!(thumbs.renders, 0, "not made on this thread"); + assert!(thumbs.pending.contains_key(&key), "sent to the worker"); + } +} 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 9fc91f5068..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 @@ -316,6 +317,7 @@ fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let o = options(ui.ctx()); + super::layers::show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(cache) = cached(app, ui.ctx(), &o) else { widgets::dim_label(ui, tl!("No document")); return; @@ -533,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). @@ -596,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/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 4d08938c53..97959ed4a8 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -77,12 +77,19 @@ fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, n: usize, min: usi } /// A Shape Mode button clicked: Alt makes a compound shape of the selection in `mode`; with -/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. +/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. With the +/// Compound Shapes add-on's setting on, a click on the selection (not on members) makes the +/// compound shape and Alt gives the permanent result. fn shape_mode(app: &mut VectorcraftApp, ui: &Ui, op: &str, mode: ShapeMode, members: bool) { - if ui.input(|i| i.modifiers.alt) { + let alt = ui.input(|i| i.modifiers.alt); + if members { + if alt { + crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); + } else { + crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); + } + } else if alt != app.ui.shape_modes_compound { crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); - } else if members { - crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); } else { run(app, op); } @@ -588,4 +595,68 @@ mod tests { assert_eq!(app.last_pathfinder, None); assert!(!crate::menus::enabled(&app, "pathfinder.repeat")); } + + /// How many compound shapes the active document holds. + fn compound_shapes(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| n += usize::from(node.is_compound_shape())); + n + } + + /// Off (the default) a Shape Mode click is the permanent Pathfinder result and Alt-click makes a + /// compound shape; with the Compound Shapes add-on's setting on it is the other way round. + #[test] + fn the_compound_shapes_setting_swaps_click_and_alt_on_the_shape_modes() { + // Off: unchanged. + let mut app = two_squares(); + assert!(!app.ui.shape_modes_compound); + click_button(&mut app, "Unite"); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "a click is permanent"); + let mut app = two_squares(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!(compound_shapes(&app), 1, "Alt makes a compound shape"); + + // On: a click makes the compound shape, Alt the permanent result. + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(true)); + click_button(&mut app, "Unite"); + assert_eq!(compound_shapes(&app), 1, "a click makes a compound shape"); + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "Alt is permanent"); + + // Toggled off again, and the check mark follows. + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(!app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(false)); + } + + /// Members of a compound shape that are selected take the clicked mode whatever the setting says. + #[test] + fn selected_members_take_the_mode_with_the_setting_on() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button(&mut app, "Unite"); + let shape = app.session.active().unwrap().selection.objects[0]; + let front = app.session.active().unwrap().doc.node(shape).unwrap().children().unwrap().last().unwrap().id; + app.run("select.set", json!({"ids": [front.0]})).unwrap(); + click_button(&mut app, "Minus Front"); + assert_eq!(compound_shapes(&app), 1, "no second compound shape"); + assert_eq!(vectorcraft_engine::cmd::selected_member_modes(&app.session), [ShapeMode::Subtract]); + } + + /// The setting is kept with the preferences; preferences saved before it read as off. + #[test] + fn the_compound_shapes_setting_is_saved_and_older_preferences_read_as_off() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["shape_modes_compound"], json!(true)); + assert!(serde_json::from_value::(saved.clone()).unwrap().shape_modes_compound); + saved.as_object_mut().unwrap().remove("shape_modes_compound"); + assert!(!serde_json::from_value::(saved).unwrap().shape_modes_compound); + } } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index b8a42e9285..79632f4004 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -462,7 +462,7 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { /// Edit Artboards (the Artboard tool): the active artboard's name, which can be edited to rename /// it, and the Artboard Options icon; its position and size, its preset and /// orientation (#671) (with Scale Artwork with Artboard on, a new size scales its art, #602; a new -/// W or H, preset or orientation goes to every selected artboard, in one undo step), its Fill (background color), Move +/// W or H, preset or orientation goes to every selected artboard, in one undo step), its Fill (background color, also for every selected artboard), Move /// and Scale Artwork with Artboard, New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and /// Exit back to the Selection tool (#530). fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -681,8 +681,11 @@ fn artboard_fill_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, color: Opt None => {} } }); + // A Fill chosen from the list goes to every selected artboard, in one undo step (#5698). if let Some(c) = set { - app.run("artboard.setProps", json!({"index": i, "color": c.as_ref().map(super::color_json)})).ok(); + let color = c.as_ref().map(super::color_json); + let indices = super::artboards::renamed_with(app, i); + super::artboards::set_props(app, &indices, json!({}), |j, _| Some(json!({"index": j, "color": color}))).ok(); } if pick { app.run("ui.colorPicker", json!({"artboard": i})).ok(); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 30ac3cd455..7c5e69e119 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -665,6 +665,25 @@ fn edit_artboards_fill_sets_the_background_color() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields.get("artboard")), Some(Some(&json!(1))), "the chip opens it too"); } +/// #5698: with Artboards 1 and 3 selected, a Fill chosen in Edit Artboards goes to both, in one +/// command and one undo step; Artboard 2 keeps none. +#[test] +fn edit_artboards_fill_sets_every_selected_artboard() { + let mut app = two_selected_artboards(); + let colors = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards.iter().map(|a| a.color).collect::>(); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let texts = frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, &texts, "None"); + let texts = frame(&mut app, &ctx, vec![]); + let commands = app.run_count; + click(&mut app, &ctx, &texts, "Black"); + assert_eq!(app.run_count.wrapping_sub(commands), 1, "one command"); + assert_eq!(colors(&app), [Some(Color::BLACK), None, Some(Color::BLACK)]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); +} + fn artboard_deletion_app(count: usize) -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100, "artboards": count})).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_constrain.rs b/crates/ui-egui/src/panels/tests_constrain.rs index 8fa4c6e028..a90f2b55d1 100644 --- a/crates/ui-egui/src/panels/tests_constrain.rs +++ b/crates/ui-egui/src/panels/tests_constrain.rs @@ -256,6 +256,21 @@ fn a_thousands_comma_in_a_percentage_is_refused_in_a_size_field() { } } +/// Arithmetic with a decimal comma works in W (#5684), also after a value shown with a point; a +/// number with both separators is refused and leaves the size as it was. +#[test] +fn arithmetic_with_a_decimal_comma_works_in_a_size_field() { + let surfaces: [(&str, Draw); 3] = + [("Transform panel", transform::show), ("Properties", properties::transform_section), ("Control bar", crate::chrome::control_bar)]; + for (name, draw) in surfaces { + for (text, want) in [("100,5-20,5", 80.0), ("90-0,5*20", 80.0), ("10,5*2", 21.0), ("100.5 pt-20,5", 80.0), ("1.234,5", 100.0)] { + let mut app = rect_app(); + set_field(&mut app, draw, "100 pt", text, End::Enter(Modifiers::NONE)); + assert_eq!(size(&app), (want, 50.0), "{name}, {text}"); + } + } +} + /// A length field of the New Document dialog keeps the focus on Ctrl/Cmd+Enter, and the dialog /// creates no document. #[test] diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index ba00aabbf5..49f14f281b 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -40,6 +40,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); + check_typed_folders(app, &values)?; app.run("prefs.set", json!({ "values": values }))?; if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(app, app.touch_screen); @@ -386,16 +387,17 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } }); } - // File Handling › Data Recovery › Folder: typed, or picked with Choose… where the host - // has a folder picker (not on the web). - PrefKind::Text if sp.key == "recoveryFolder" => { + // File Handling › Data Recovery › Folder and Plug-ins & Scratch Disks › Additional + // Plug-ins Folder: typed, or picked with Choose… where the host has a folder picker + // (not on the web). + PrefKind::Text if folder_check(sp.key).is_some() => { labeled(ui, sp.label, |ui| { let mut s = v.as_str().unwrap_or("").to_string(); if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(200.0)).changed() { d.fields.insert(sp.key.into(), json!(s)); } if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() { - choose_recovery_folder(app, d); + choose_folder(app, d, sp.key); } }); } @@ -411,15 +413,30 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } } -/// Data Recovery › Choose…: the folder picked becomes the Folder field's value when a folder can be -/// made in it. Otherwise the status bar says why and the field keeps its value, as it does when -/// the picker is canceled. The answer fills the field even when the active document closed while -/// the picker was open. -fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { - let r = crate::picks::in_app_dialog(app, d, |app, d| { +/// A check of a folder path: `Err` says why the folder can't be the preference's value. +type FolderCheck = fn(&str) -> Result<(), String>; + +/// The check a folder preference with a Choose… button gives a folder before it becomes the +/// preference's value: Data Recovery keeps its copies in its folder, and the Additional Plug-ins +/// Folder is read for plug-ins. `None` for any other preference. +fn folder_check(key: &str) -> Option { + match key { + "recoveryFolder" => Some(writable_folder), + "pluginsFolder" => Some(plugins_folder), + _ => None, + } +} + +/// Choose… beside the folder preference `key`: the folder picked becomes the field's value when it +/// passes the preference's [`folder_check`]. Otherwise the status bar says why and the field keeps +/// its value, as it does when the picker is canceled. The answer fills the field even when the +/// active document closed while the picker was open. +fn choose_folder(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) { + let Some(check) = folder_check(key) else { return }; + let r = crate::picks::in_app_dialog(app, d, move |app, d| { let Some(path) = crate::picks::folder(app) else { return Ok(()) }; - writable_folder(&path)?; - d.fields.insert("recoveryFolder".into(), json!(path)); + check(&path)?; + d.fields.insert(key.into(), json!(path)); Ok(()) }); if let Err(e) = r { @@ -427,10 +444,43 @@ fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { } } +/// OK's check of the folder preferences with a Choose… button: a folder typed into one of their +/// fields gets the same [`folder_check`] as a picked one. An empty field (the default folder) and +/// a folder the preference already holds are not checked. The web has no folders to check. +fn check_typed_folders(app: &VectorcraftApp, fields: &Map) -> Result<(), String> { + if cfg!(target_arch = "wasm32") { + return Ok(()); + } + let saved = app.session.prefs.to_json(); + for (key, v) in fields { + let (Some(check), Some(path)) = (folder_check(key), v.as_str()) else { continue }; + let path = path.trim(); + if path.is_empty() || saved[key.as_str()].as_str().is_some_and(|s| s.trim() == path) { + continue; + } + check(path)?; + } + Ok(()) +} + +/// `Ok` when `path` is a folder whose contents can be listed, as the plug-ins in it are found by +/// listing it. A folder outside the automation roots in force is refused before it is looked at. +fn plugins_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_read(path)?; + let dir = std::path::Path::new(path); + if !dir.is_dir() { + return Err(format!("{path} is not a folder")); + } + std::fs::read_dir(dir).map(drop).map_err(|e| format!("Plug-ins can't be loaded from {path}: {e}")) +} + /// `Ok` when `path` is a folder that can be listed and that a folder can be created in, as the /// recovery store lists its folders there and makes its own: the folder is listed, and an empty -/// folder is made there and removed. A folder that can't be removed again is an error too. +/// folder is made there and removed. A folder that can't be removed again is an error too. A +/// folder outside the automation roots in force is refused before it is looked at. fn writable_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_write(path)?; + vectorcraft_engine::file_access::check_read(path)?; let dir = std::path::Path::new(path); if !dir.is_dir() { return Err(format!("{path} is not a folder")); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index ff5dcbca7b..75a165674f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -458,12 +458,12 @@ fn a_chosen_recovery_folder_fills_the_field_and_cancel_keeps_it() { let answer = picked.clone(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); let mut d = a.ui.dialog.clone().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked); assert!(a.ui.status.is_empty(), "{}", a.ui.status); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write check leaves nothing behind"); a.services.pick_folder = Some(Box::new(|| None)); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked, "cancel keeps the field"); a.ui.dialog = Some(d); confirm(&mut a).unwrap(); @@ -486,7 +486,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = path.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); } @@ -501,7 +501,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = locked.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -515,7 +515,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = unlisted.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -535,7 +535,7 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { a.run("file.new", json!({"width": 100, "height": 80})).unwrap(); open(&mut a, Some("File Handling")); let mut d = a.ui.dialog.take().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); a.ui.dialog = Some(d); assert!(matches!(shown.requests().as_slice(), [crate::picks::PickRequest::Folder])); a.session.execute("file.close", &json!({})).unwrap(); @@ -546,3 +546,112 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { assert_eq!(a.ui.dialog.as_ref().unwrap().str("recoveryFolder"), picked, "{}", a.ui.status); let _ = std::fs::remove_dir_all(&dir); } + +/// Plug-ins & Scratch Disks › Additional Plug-ins Folder has a Choose… button where the host has a +/// folder picker, and none where it has not (the web). +#[test] +fn plugins_folder_has_a_choose_button_with_a_folder_picker() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + a.services.pick_folder = Some(Box::new(|| None)); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && text.contains("Choose…"), "{text}"); + a.services.pick_folder = None; + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && !text.contains("Choose…"), "{text}"); +} + +/// Choose… beside Additional Plug-ins Folder puts the folder picked into the field, and OK saves +/// it; a canceled picker, a file and a missing folder leave the field as it was. +#[test] +fn a_chosen_plugins_folder_fills_the_field_and_others_keep_it() { + let dir = temp_folder("plugins-chosen"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let mut d = a.ui.dialog.clone().unwrap(); + for path in [file.clone(), dir.join("missing")] { + let answer = path.to_string_lossy().into_owned(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), ""); + assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); + } + let picked = dir.to_string_lossy().into_owned(); + let answer = picked.clone(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked); + assert!(a.ui.status.is_empty(), "{}", a.ui.status); + a.services.pick_folder = Some(Box::new(|| None)); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked, "cancel keeps the field"); + a.ui.dialog = Some(d); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugins_folder, picked); + let _ = std::fs::remove_dir_all(&dir); +} + +/// OK checks a folder typed into Data Recovery › Folder or Additional Plug-ins Folder as Choose… +/// checks a picked one: one that fails keeps the dialog open and changes no preference. An empty +/// field and a folder the preference already holds are not checked. +#[test] +fn ok_refuses_a_typed_folder_that_choose_would_refuse() { + let dir = temp_folder("typed-folders"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let missing = dir.join("missing").to_string_lossy().into_owned(); + for key in ["recoveryFolder", "pluginsFolder"] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + let before = a.session.prefs.to_json(); + for path in [file.to_string_lossy().into_owned(), missing.clone()] { + let d = a.ui.dialog.as_mut().unwrap(); + d.fields.insert(key.into(), json!(path)); + d.fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + assert_eq!(confirm(&mut a), Err(format!("{path} is not a folder")), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + assert_eq!(a.session.prefs.to_json(), before, "{key}: no preference changes"); + } + // A typed folder that passes is saved, with the spaces around it as typed. + let typed = format!(" {} ", dir.to_string_lossy()); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(typed)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(typed), "{key}"); + // An empty field keeps the default folder. + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!("")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(""), "{key}"); + // A folder already saved is not checked again, so OK works while it is unavailable. + a.run("prefs.set", json!({"key": key, "value": missing})).unwrap(); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(missing), "{key}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Under automation roots, OK refuses a typed folder outside them before it looks at the folder. +#[test] +fn ok_refuses_a_typed_folder_outside_the_automation_roots_before_looking_at_it() { + use vectorcraft_engine::file_access::{self, Access}; + let dir = temp_folder("typed-roots"); + let inside = dir.join("inside"); + std::fs::create_dir_all(&inside).unwrap(); + let outside = dir.join("outside-missing").to_string_lossy().into_owned(); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap().unwrap(); + for (key, access) in [("recoveryFolder", Access::Write), ("pluginsFolder", Access::Read)] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(outside)); + let r = file_access::confine(Some(&roots), || confirm(&mut a)); + assert_eq!(r, Err(roots.check(&outside, access).unwrap_err()), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 3d35247880..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`]). @@ -150,7 +158,7 @@ pub struct Services { pub wayland: bool, /// On Wayland, no cursor theme can be loaded, so winit sets no pointer and the compositor's /// default one would never come back once the canvas hid it: the canvas keeps the system - /// pointer visible next to the tool glyph ([`cursors::hide_system_pointer`], #2450). + /// pointer and paints no tool glyph ([`cursors::paint_glyphs`], #2450). pub no_cursor_theme: bool, /// The pen pressure and pen end the host reads from the system itself (desktop Linux under /// X11 and XWayland, macOS and Windows). The canvas uses the pressure when a frame's events carry no touch force, 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 77c19753fc..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 { @@ -366,6 +381,10 @@ pub struct UiState { /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, + /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the + /// permanent Pathfinder result on Alt-click (off, the default: the other way round). + #[serde(default)] + pub shape_modes_compound: bool, /// The locked objects under the pointer at the last right-click on the canvas, with the /// document's `uid`: the context menu's Unlock submenu lists them while the menu is open. Not /// saved. @@ -378,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, @@ -452,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: @@ -935,8 +962,10 @@ impl Default for UiState { toolbar_advanced: false, task_bar: true, task_bar_place: TaskBarPlace::default(), + 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(), @@ -963,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, @@ -1171,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/sysclip.rs b/crates/ui-egui/src/sysclip.rs index f72339a3e5..ac382547de 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -34,6 +34,29 @@ pub trait SystemClipboard { fn read_deferred(&mut self, mimes: &[&'static str]) -> Option { self.read(mimes).map(ClipboardRead::Now) } + /// A number that changes each time any app copies something, read without opening the + /// clipboard; `None` where the platform has none (the default). + fn change_count(&mut self) -> Option { + None + } +} + +/// What the system clipboard held when the formats of a Copy or Cut could not be written. +#[derive(PartialEq)] +enum Held { + /// Its [`SystemClipboard::change_count`]. + Count(u64), + /// Its text, where the platform has no change count. + Text(Option>), +} + +impl Held { + fn now(cb: &mut (dyn SystemClipboard + 'static)) -> Self { + match cb.change_count() { + Some(n) => Self::Count(n), + None => Self::Text(cb.read(&[TEXT]).map(|f| f.data)), + } + } } /// What [`SystemClipboard::read_deferred`] read. @@ -71,6 +94,9 @@ pub(crate) struct Publishing { latest: Arc, /// The latest one's formats wait to be written. pending: bool, + /// The latest one's formats could not be written: what the system clipboard held when the + /// write failed, and the text of those formats. + unwritten: Option<(Held, String)>, } impl Publishing { @@ -113,6 +139,25 @@ pub(crate) fn import_command(f: &Flavour, center: Option<[f64; 2]>) -> (&'static } impl VectorcraftApp { + /// A Type paste may reuse its saved styled runs only while our desktop copy still owns the + /// clipboard. Pending formats also belong to that copy; web hosts have no ownership service. + pub(crate) fn type_paste_has_our_clipboard(&mut self) -> bool { + self.clipboard_publishing.pending + || self.unwritten_clipboard_text().is_some() + || self.services.system_clipboard.as_mut().is_none_or(|cb| cb.holds_ours()) + } + + /// The text of the latest Copy or Cut whose formats could not be written to the system + /// clipboard, while nothing has been copied since that Copy or Cut. A paste into type or a text + /// field takes this text until another app copies something. Where the platform has no change + /// count, a copy is noticed only when it changes the clipboard's text, so the copy is kept only + /// when the clipboard held text when the write failed. + pub(crate) fn unwritten_clipboard_text(&mut self) -> Option { + let cb = self.services.system_clipboard.as_deref_mut()?; + let (held, text) = self.clipboard_publishing.unwritten.as_ref()?; + (Held::now(cb) == *held).then(|| text.clone()) + } + /// After Copy or Cut: offer the copied objects to other apps. With the system clipboard /// service, the background worker makes the formats from a copy of the clipboard /// ([`background::run`]) and they are written when they are ready. While the worker has a @@ -142,6 +187,9 @@ impl VectorcraftApp { let latest = self.clipboard_publishing.latest.clone(); let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1); self.clipboard_publishing.pending = true; + self.clipboard_publishing.unwritten = None; + // What the clipboard holds at the Copy or Cut: a copy made elsewhere before the write is newer. + let before = self.services.system_clipboard.as_deref_mut().map(Held::now); let (tx, made) = channel(); let work = move |_: Writer| { // These formats are not made when a later Copy or Cut, or a copy through egui, dropped them. @@ -159,7 +207,31 @@ impl VectorcraftApp { publishing.pending = false; let formats = r.and_then(|_| made.try_recv().map_err(|e| e.to_string())); let written = formats.and_then(|(f, warnings)| { - app.services.system_clipboard.as_mut().map_or(Ok(()), |cb| cb.write(&f))?; + let Some(cb) = app.services.system_clipboard.as_mut() else { return Ok(warnings) }; + let before_write = Held::now(cb.as_mut()); + // Nothing copied elsewhere since the Copy or Cut. + let current = before.as_ref() == Some(&before_write); + if let Err(e) = cb.write(&f) { + // Another app may hold the clipboard open. It keeps what it held (or what the + // failed write left), and a paste into text takes this copy's text until + // something else is copied. + let held = Held::now(cb.as_mut()); + let text = f.iter().find(|t| t.mime == TEXT).map(|t| String::from_utf8_lossy(&t.data).into_owned()); + // A change during the write is the failed write emptying the clipboard and + // writing some of the formats, or another app's copy: the clipboard then holds + // nothing to paste, this copy's text, or no text and one of this copy's + // formats only after the former. + let left_by_write = held == before_write + || match cb.read(&[TEXT]) { + Some(now) => text.as_deref().is_some_and(|ours| now.data == ours.as_bytes()), + None => !cb.has(&PASTE_ORDER) || f.iter().any(|ours| cb.read(&[ours.mime]).is_some_and(|now| now.data == ours.data)), + }; + // Without a change count, a clipboard with no text can't show a later copy of + // a picture, or tell an empty clipboard from one that couldn't be read. + let trackable = held != Held::Text(None); + app.clipboard_publishing.unwritten = text.filter(|_| current && left_by_write && trackable).map(|text| (held, text)); + return Err(e); + } Ok(warnings) }); match written { @@ -190,6 +262,7 @@ impl VectorcraftApp { let publishing = &mut self.clipboard_publishing; publishing.latest.fetch_add(1, Ordering::SeqCst); publishing.pending = false; + publishing.unwritten = None; match self.services.system_clipboard.as_mut() { Some(cb) => { if let Err(e) = cb.write(&[]) { @@ -211,6 +284,9 @@ impl VectorcraftApp { pub(crate) fn drop_formats_after_egui_copy(&mut self, ctx: &egui::Context) { let copied = ctx.output(|o| o.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_) | egui::OutputCommand::CopyImage(_)))); let publishing = &mut self.clipboard_publishing; + if copied { + publishing.unwritten = None; + } if copied && publishing.pending { publishing.latest.fetch_add(1, Ordering::SeqCst); publishing.pending = false; @@ -235,6 +311,22 @@ impl VectorcraftApp { let waited = ctx.data(|d| d.get_temp::(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false); ctx.data_mut(|d| d.remove::(egui::Id::unique("clipboard.pending-at-tick"))); if !(self.clipboard_publishing.pending || waited) { + // A copy whose formats could not be written: a paste takes its text, not the text the + // clipboard kept ([`Self::unwritten_clipboard_text`]). + let pasting = textless || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))); + if pasting && let Some(text) = self.unwritten_clipboard_text() { + ctx.input_mut(|i| { + for e in &mut i.events { + if let egui::Event::Paste(t) = e { + t.clone_from(&text); + } + } + if textless { + i.events.insert(0, egui::Event::Paste(text)); + } + }); + return; + } // The formats the clipboard still holds were written after the chord's key went down. if textless && self.services.system_clipboard.as_mut().is_some_and(|cb| cb.holds_ours()) @@ -362,11 +454,12 @@ impl VectorcraftApp { } /// The text on the system clipboard once the formats a Copy or Cut is making are written, for a - /// paste into a text field or type. + /// paste into a text field or type. When they could not be written, their text + /// ([`Self::unwritten_clipboard_text`]). pub(crate) fn written_clipboard_text(&mut self) -> Option { // Only other copies' formats are ahead of them on the worker ([`Self::publish_clipboard`]). background::wait_until(self, |app| !app.clipboard_publishing.pending); - self.system_clipboard_text() + self.unwritten_clipboard_text().or_else(|| self.system_clipboard_text()) } /// The text on the system clipboard, if any. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index f0c779f646..2593115f60 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -51,6 +51,7 @@ mod sysclip_emf; mod sysclip_guides; mod sysclip_probe; mod tab_overflow; +mod tab_reorder; mod taskbar; mod toolescape; mod trace_runs; diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index 9a77194307..77ff0149b4 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -232,6 +232,277 @@ fn paste_without_formatting_takes_surrounding_style() { assert!(t2.runs.iter().all(|r| r.style.size == 10.0), "all runs take 10 pt size: {:?}", t2.runs); } +#[test] +fn external_plain_text_matching_an_old_copy_uses_destination_style() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board) = super::sysclip::app(); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + crate::background::wait_all(&mut app); + + let own_destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": own_destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(own_destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: Hello"); + assert_eq!(t.runs.last().unwrap().style.size, 36.0, "our copy keeps its style"); + + // Another app later copies the same characters as plain text. Their style is unrelated. + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Hello".to_vec())]); + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 80, "text": "Before ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 7, "end": 7})); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Hello".into())]); + assert_eq!(app.system_clipboard_text().as_deref(), Some("Hello")); + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 12, "end": 12})); + assert!(app.session.tool_wants_text()); + assert!(crate::panels::character::intercept_text_command(&mut app, "edit.paste").is_some()); + + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Before HelloHello"); + assert!(t.runs.iter().all(|run| run.style.size == 12.0 && run.style.fill == Paint::solid(Color::rgb8(0, 0, 0)))); +} + +#[test] +fn type_paste_keeps_a_copy_the_system_clipboard_refused_until_another_app_copies() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board) = super::sysclip::app(); + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Old".to_vec())]); + super::sysclip::lock(&board, true); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + crate::background::wait_all(&mut app); + super::sysclip::lock(&board, false); + assert_eq!(app.system_clipboard_text().as_deref(), Some("Old"), "the write was refused"); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: Hello"); + assert_eq!(t.runs.last().unwrap().style.size, 36.0, "our copy keeps its style"); + + // A paste event carries the text the clipboard kept. + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 10, "end": 10})); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: HelloHello"); + + // Another app copies, even the same text: Paste takes it, in the destination's style. + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Old".to_vec())]); + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: OldHelloHello"); + let old = t.runs.iter().find(|run| run.text.contains("Old")).unwrap(); + assert_eq!(old.style.size, 12.0, "another app's text takes the destination's style"); +} + +/// An app whose fake clipboard has no change count and holds `held`; "Hello" (36 pt) copied in the +/// Type tool with `refuse` set up by `before_copy`; and a paste at `at` into "Own: " (12 pt). +fn uncounted_refused_copy( + held: (&'static str, Vec), + before_copy: impl FnOnce(&std::rc::Rc>), +) -> (VectorcraftApp, std::rc::Rc>, impl Fn(&mut VectorcraftApp, usize) -> String) { + let (mut app, board) = super::sysclip::app(); + super::sysclip::without_change_count(&board); + super::sysclip::copy_elsewhere(&board, vec![held]); + before_copy(&board); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + crate::background::wait_all(&mut app); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let paste_at = move |app: &mut VectorcraftApp, at: usize| { + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": at, "end": at})); + crate::panels::character::intercept_text_command(app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() + }; + (app, board, paste_at) +} + +#[test] +fn type_paste_without_a_change_count_keeps_a_refused_copy_while_the_text_is_unchanged() { + use vectorcraft_engine::cmd::clipboard::TEXT; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board, paste_at) = uncounted_refused_copy((TEXT, b"Old".to_vec()), |b| super::sysclip::refuse_writes(b, true)); + assert_eq!(paste_at(&mut app, 5), "Own: Hello"); + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + assert_eq!(paste_at(&mut app, 5), "Own: NewHello"); +} + +#[test] +fn type_paste_without_a_change_count_drops_a_refused_copy_it_cannot_track() { + use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + // The clipboard can't be read when the write fails: its text read later may be another app's. + let (mut app, board, paste_at) = uncounted_refused_copy((TEXT, b"Old".to_vec()), |b| super::sysclip::lock(b, true)); + assert_eq!(paste_at(&mut app, 5), "Own: "); + super::sysclip::lock(&board, false); + assert_eq!(paste_at(&mut app, 5), "Own: Old"); + + // The clipboard holds a picture, and another app copies a different picture: no text pastes. + let (mut app, board, paste_at) = uncounted_refused_copy((PNG, super::sysclip::blue_png()), |b| { + super::sysclip::has_text_only(b); + super::sysclip::refuse_writes(b, true); + }); + super::sysclip::copy_elsewhere(&board, vec![(PNG, super::sysclip::blue_png().into_iter().rev().collect())]); + assert_eq!(paste_at(&mut app, 5), "Own: "); +} + +#[test] +fn a_paste_event_waiting_on_a_refused_copy_pastes_that_copy() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + // Another copy's formats hold the worker, so this Copy's formats wait. + let (mut app, board, hold) = super::sysclip::app_with_busy_worker(""); + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Old".to_vec())]); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + assert!(app.clipboard_publishing.is_pending()); + + // The paste comes while the formats wait, and the write then fails with the clipboard open. + super::sysclip::lock(&board, true); + drop(hold); + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: Hello"); +} + +#[test] +fn a_copy_elsewhere_before_a_refused_write_wins_the_type_paste() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board, hold) = super::sysclip::app_with_busy_worker(""); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + assert!(app.clipboard_publishing.is_pending()); + + // Another app copies while the formats wait, and keeps the clipboard open for the write. + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"New".to_vec())]); + super::sysclip::lock(&board, true); + drop(hold); + crate::background::wait_all(&mut app); + super::sysclip::lock(&board, false); + + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + assert_eq!(t.plain_text(), "Own: New"); +} + +#[test] +fn type_paste_keeps_a_copy_whose_write_failed_after_emptying_the_clipboard() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + assert_eq!(paste_after_a_write_that_failed_after_emptying(false), "Own: Hello"); + // The formats other than text were written before the failure. + assert_eq!(paste_after_a_write_that_failed_after_emptying(true), "Own: Hello"); +} + +/// Copy "Hello" in the Type tool with a write that empties the clipboard and fails (`keep_others`: +/// after writing the formats other than text), then paste into "Own: ". +fn paste_after_a_write_that_failed_after_emptying(keep_others: bool) -> String { + let (mut app, board) = super::sysclip::app(); + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Old".to_vec())]); + super::sysclip::fail_writes_after_emptying(&board, keep_others); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + crate::background::wait_all(&mut app); + + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() +} + +#[test] +fn a_copy_elsewhere_during_a_refused_write_wins_the_type_paste() { + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; + assert_eq!(paste_after_a_copy_during_a_refused_write(TEXT, b"Race".to_vec(), false), "Own: Race"); + // Its other formats may match this copy's; its text still differs. + assert_eq!(paste_after_a_copy_during_a_refused_write(TEXT, b"Race".to_vec(), true), "Own: Race"); + // A picture has no text to paste into type. + assert_eq!(paste_after_a_copy_during_a_refused_write(PNG, super::sysclip::blue_png(), false), "Own: "); +} + +/// Copy in the Type tool while another app copies `data` of type `mime` (with `our_formats`, also +/// the copy's formats other than text) and the write fails, then paste into "Own: ". +fn paste_after_a_copy_during_a_refused_write(mime: &'static str, data: Vec, our_formats: bool) -> String { + let (mut app, board) = super::sysclip::app(); + super::sysclip::copy_elsewhere(&board, vec![(vectorcraft_engine::cmd::clipboard::TEXT, b"Old".to_vec())]); + super::sysclip::copy_during_next_write(&board, mime, data, our_formats); + let source = run(&mut app, "text.create", json!({"x": 20, "y": 40, "text": "Hello", "size": 36, "color": "#ff0000"}))["id"].as_u64().unwrap(); + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": source, "start": 0, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.copy"); + crate::background::wait_all(&mut app); + + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() +} + /// https://helpx.adobe.com/illustrator/using/format-text.html #[test] fn copying_single_character_carries_formatting_across_documents() { diff --git a/crates/ui-egui/src/tests/fonts.rs b/crates/ui-egui/src/tests/fonts.rs index f8f019171e..073be1e083 100644 --- a/crates/ui-egui/src/tests/fonts.rs +++ b/crates/ui-egui/src/tests/fonts.rs @@ -9,6 +9,10 @@ use crate::{VectorcraftApp, menus}; #[test] fn type_font_menu_lists_every_available_family() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + // The app starts the installed fonts' scan, and until it ends Type › Font lists only the + // loaded fonts (#5483). The scan changes the generation a moment before it counts as done, so + // a read in between sees the old list under the new generation: wait for it to end first. + FontDb::global().family_list(); app.run("file.new", json!({})).unwrap(); let fonts = |app: &VectorcraftApp| -> Vec { menus::menu_entries(app).into_iter().filter(|e| e.path == ["Type", "Font"]).map(|e| e.label).collect() diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index e4c9d47ef4..9406ba2c97 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -488,6 +488,29 @@ fn the_control_bar_shows_the_image_file_link_colour_mode_and_ppi() { assert!(text.contains("Embedded"), "{text}"); } +/// The Control bar's label is read from the first selected object each frame, so it follows an +/// edit, Undo, a switch to another document and back, and a selection change. +#[test] +fn the_control_bar_label_follows_edits_undo_documents_and_selection() { + let mut app = app(); + let path = temp_file("label.png", &png(30, 30, 72.0)); + app.run("file.place", json!({"path": path})).unwrap(); + let text = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, crate::chrome::control_bar); + assert!(text(&mut app).contains("Linked File")); + app.run("links.embed", json!({})).unwrap(); + let embedded = text(&mut app); + assert!(embedded.contains("Embedded") && !embedded.contains("Linked File"), "{embedded}"); + app.run("edit.undo", json!({})).unwrap(); + assert!(text(&mut app).contains("Linked File")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(!text(&mut app).contains("Linked File"), "the new document has nothing selected"); + app.session.set_active(0); + assert!(text(&mut app).contains("Linked File")); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + let rect = text(&mut app); + assert!(!rect.contains("Linked File") && !rect.contains("Embedded"), "{rect}"); +} + /// Click the Control bar's `label`. fn click_label(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { use crate::tests_removeanchors::{at, click_control, control_frame}; diff --git a/crates/ui-egui/src/tests/synthetic.rs b/crates/ui-egui/src/tests/synthetic.rs index cb328e235f..e61cb8fa19 100644 --- a/crates/ui-egui/src/tests/synthetic.rs +++ b/crates/ui-egui/src/tests/synthetic.rs @@ -82,6 +82,207 @@ fn a_typed_key_holds_its_modifiers_for_its_text() { assert_eq!(app.session.tool_id(), "blobBrush", "Shift+B, not B"); } +/// A `ui.pointer` release sent right after a `ui.key` waits until the key reached the busy tool: +/// C pressed while an arc is dragged out closes the arc drawn on release. +#[test] +fn a_pointer_release_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": "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(); + tx.send(up).unwrap(); + // Each frame as the host runs it: the input hook, the control requests, then the UI pass. + let mut released = 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(r) = up_reply.try_recv() { + released = Some(r); + break; + } + let mut out = ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + let r = released.expect("the release ran"); + assert_eq!(r["ok"], true, "{r}"); + let document = app.session.active().unwrap(); + let arc = *document.selection.objects.last().expect("the arc drawn on release"); + let closed = document.doc.node(arc).unwrap().path_data().unwrap().subpaths[0].closed; + 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/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 3266e6ba19..595d12b51f 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -22,6 +22,26 @@ pub(super) struct Board { ours: bool, /// How many times the app wrote it. writes: usize, + /// Another app has the clipboard open: the app's writes fail and change nothing, and reads + /// find nothing. + locked: bool, + /// Raised by every write and every copy elsewhere. + changes: u64, + /// The platform has no change count. + uncounted: bool, + /// The app's writes empty the clipboard and then fail. + partial: bool, + /// With `partial`, the formats other than text are written before the failure. + partial_keeps_others: bool, + /// Another app copies this while the app's write tries to open the clipboard, and the write + /// fails. + race: Option, + /// With `race`, the other app's copy also carries the app's formats other than text. + race_with_our_formats: bool, + /// The app's writes fail and change nothing; reads still work. + refuse: bool, + /// `has` finds text only, as the Linux clipboard's does. + text_only_has: bool, } struct Fake(Rc>); @@ -29,6 +49,9 @@ struct Fake(Rc>); impl Fake { fn find(&self, mimes: &[&'static str]) -> Option { let b = self.0.borrow(); + if b.locked { + return None; + } let matches = |m: &str, f: &Flavour| f.mime == m || (m == BITMAP && f.mime.starts_with("image/") && f.mime != SVG); mimes.iter().find_map(|m| b.flavours.iter().find(|f| matches(m, f)).cloned()) } @@ -37,9 +60,30 @@ impl Fake { impl SystemClipboard for Fake { fn write(&mut self, flavours: &[Flavour]) -> Result<(), String> { let mut b = self.0.borrow_mut(); - *b = Board { flavours: flavours.to_vec(), ours: true, writes: b.writes + 1 }; + if b.locked || b.refuse { + return Err("another app has the clipboard open".into()); + } + if let Some(copied) = b.race.take() { + b.flavours = vec![copied]; + if b.race_with_our_formats { + b.flavours.extend(flavours.iter().filter(|f| f.mime != TEXT).cloned()); + } + b.ours = false; + b.changes += 1; + return Err("another app has the clipboard open".into()); + } + if b.partial { + b.flavours = if b.partial_keeps_others { flavours.iter().filter(|f| f.mime != TEXT).cloned().collect() } else { vec![] }; + b.changes += 1; + return Err("a format could not be written".into()); + } + *b = Board { flavours: flavours.to_vec(), ours: true, writes: b.writes + 1, changes: b.changes + 1, ..std::mem::take(&mut *b) }; Ok(()) } + fn change_count(&mut self) -> Option { + let b = self.0.borrow(); + (!b.uncounted).then_some(b.changes) + } fn holds_ours(&mut self) -> bool { self.0.borrow().ours } @@ -47,6 +91,9 @@ impl SystemClipboard for Fake { self.find(mimes) } fn has(&mut self, mimes: &[&'static str]) -> bool { + if self.0.borrow().text_only_has { + return mimes.contains(&TEXT) && self.find(&[TEXT]).is_some(); + } self.find(mimes).is_some() } } @@ -66,7 +113,44 @@ pub(super) fn app() -> (VectorcraftApp, Rc>) { pub(super) fn copy_elsewhere(board: &Rc>, flavours: Vec<(&'static str, Vec)>) { let flavours = flavours.into_iter().map(|(mime, data)| Flavour { mime, data }).collect(); let mut b = board.borrow_mut(); - *b = Board { flavours, ours: false, writes: b.writes }; + *b = Board { flavours, ours: false, changes: b.changes + 1, ..std::mem::take(&mut *b) }; +} + +/// Another app opens the clipboard (`true`) or closes it. +pub(super) fn lock(board: &Rc>, locked: bool) { + board.borrow_mut().locked = locked; +} + +/// The fake clipboard reports no change count, as on platforms that have none. +pub(super) fn without_change_count(board: &Rc>) { + board.borrow_mut().uncounted = true; +} + +/// The fake clipboard's `has` finds text only, as the Linux clipboard's does. +pub(super) fn has_text_only(board: &Rc>) { + board.borrow_mut().text_only_has = true; +} + +/// The app's writes fail (`true`) and change nothing, while reads still work. +pub(super) fn refuse_writes(board: &Rc>, refuse: bool) { + board.borrow_mut().refuse = refuse; +} + +/// The app's writes empty the clipboard and then fail, as when one format can't be written; with +/// `keep_others`, the formats other than text are written. +pub(super) fn fail_writes_after_emptying(board: &Rc>, keep_others: bool) { + let mut b = board.borrow_mut(); + b.partial = true; + b.partial_keeps_others = keep_others; +} + +/// Another app copies `data` of type `mime` while the app's next write tries to open the +/// clipboard, and that write fails. With `our_formats`, its copy also carries the app's formats +/// other than text. +pub(super) fn copy_during_next_write(board: &Rc>, mime: &'static str, data: Vec, our_formats: bool) { + let mut b = board.borrow_mut(); + b.race = Some(Flavour { mime, data }); + b.race_with_our_formats = our_formats; } pub(super) fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value { diff --git a/crates/ui-egui/src/tests/tab_reorder.rs b/crates/ui-egui/src/tests/tab_reorder.rs new file mode 100644 index 0000000000..c1070fbc70 --- /dev/null +++ b/crates/ui-egui/src/tests/tab_reorder.rs @@ -0,0 +1,207 @@ +//! Document tabs dragged along the tab strip move their documents (#5663); dragged off it, they +//! still float them. + +use egui::{Event, PointerButton, Pos2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::{VectorcraftApp, chrome}; + +const SIZE: egui::Vec2 = egui::vec2(1000.0, 700.0); +const NAMES: [&str; 4] = ["Alpha", "Bravo", "Charlie", "Delta"]; + +/// Run a tab-strip frame; → the tabs' titles with their rects, and the frame's output. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) -> (Vec<(String, egui::Rect)>, egui::FullOutput) { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), time: Some(time), events, ..Default::default() }, + |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }, + ); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_owned(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut texts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut texts); + } + (texts, out) +} + +fn button(at: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// An app with documents Alpha, Bravo, Charlie and Delta, Delta current, and a context that has +/// drawn the strip once. +fn app() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in NAMES { + app.run("file.new", json!({"width": 100, "height": 100, "name": name})).unwrap(); + } + app.sync_views(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![]); + (app, ctx) +} + +fn order(app: &VectorcraftApp) -> Vec { + app.session.documents().iter().map(|d| d.title()).collect() +} + +fn current(app: &VectorcraftApp) -> String { + app.session.active().map(|d| d.title()).unwrap_or_default() +} + +/// The middle of the title of `name`'s tab. +fn tab(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, name: &str) -> Pos2 { + let (texts, _) = frame(app, ctx, time, vec![]); + texts.iter().find(|(t, _)| t.starts_with(name)).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{name}'s tab: {texts:?}")) +} + +/// Press at `from`, move to `to` in steps, and release there; → the output of the frame before +/// the release (while the tab is still dragged). +fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, from: Pos2, to: Pos2) -> egui::FullOutput { + frame(app, ctx, time, vec![Event::PointerMoved(from)]); + frame(app, ctx, time + 0.05, vec![button(from, true)]); + let mut last = None; + for k in 1..=8 { + let p = from + (to - from) * (k as f32 / 8.0); + last = Some(frame(app, ctx, time + 0.05 + 0.02 * f64::from(k), vec![Event::PointerMoved(p)]).1); + } + frame(app, ctx, time + 0.3, vec![button(to, false)]); + frame(app, ctx, time + 0.35, vec![]); + last.unwrap() +} + +#[test] +fn a_tab_dragged_along_the_strip_moves_its_document_and_the_current_one_stays() { + let (mut app, ctx) = app(); + assert_eq!(current(&app), "Delta"); + let alpha = tab(&mut app, &ctx, 0.1, "Alpha"); + let delta = tab(&mut app, &ctx, 0.15, "Delta"); + let during = drag(&mut app, &ctx, 0.2, alpha, delta + egui::vec2(80.0, 0.0)); + assert_eq!(during.platform_output.cursor_icon, egui::CursorIcon::Grabbing, "the tab is held while it moves"); + assert_eq!(order(&app), ["Bravo", "Charlie", "Delta", "Alpha"]); + assert_eq!(current(&app), "Delta", "a move is not a switch"); + // The tabs are drawn in the new order. + let xs: Vec = NAMES.iter().map(|n| tab(&mut app, &ctx, 1.0, n).x).collect(); + assert!(xs[1] < xs[2] && xs[2] < xs[3] && xs[3] < xs[0], "Bravo, Charlie, Delta, Alpha: {xs:?}"); + + // And back to the start, before Bravo. + let alpha = tab(&mut app, &ctx, 1.1, "Alpha"); + let bravo = tab(&mut app, &ctx, 1.15, "Bravo"); + drag(&mut app, &ctx, 1.2, alpha, bravo - egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), NAMES); + assert_eq!(current(&app), "Delta"); +} + +#[test] +fn a_document_keeps_its_own_zoom_after_its_tab_moves() { + let (mut app, ctx) = app(); + for (k, v) in app.views.iter_mut().enumerate() { + v.zoom = 1.0 + k as f64; + } + let bravo = tab(&mut app, &ctx, 0.1, "Bravo"); + let delta = tab(&mut app, &ctx, 0.15, "Delta"); + drag(&mut app, &ctx, 0.2, bravo, delta + egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), ["Alpha", "Charlie", "Delta", "Bravo"]); + let zooms: Vec = app.views.iter().map(|v| v.zoom).collect(); + assert_eq!(zooms, [1.0, 3.0, 4.0, 2.0], "each view went with its document"); + assert_eq!(app.view().map(|v| v.zoom), Some(4.0), "the current document's view is still Delta's"); +} + +/// A move from outside the strip (MCP, the control channel, a recording) keeps the views with +/// their documents too. +#[test] +fn views_follow_a_move_made_by_the_engine_command() { + let (mut app, _ctx) = app(); + for (k, v) in app.views.iter_mut().enumerate() { + v.zoom = 1.0 + k as f64; + } + app.session.execute("document.move", &json!({"from": 3, "to": 0})).unwrap(); + app.sync_views(); + assert_eq!(order(&app), ["Delta", "Alpha", "Bravo", "Charlie"]); + assert_eq!(app.views.iter().map(|v| v.zoom).collect::>(), [4.0, 1.0, 2.0, 3.0]); + // Closing a document still leaves the others' views with them. + app.run("file.close", json!({"index": 1})).unwrap(); + app.sync_views(); + assert_eq!(order(&app), ["Delta", "Bravo", "Charlie"]); + 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(); + let alpha = tab(&mut app, &ctx, 0.1, "Alpha"); + drag(&mut app, &ctx, 0.2, alpha, alpha + egui::vec2(150.0, 300.0)); + assert_eq!(order(&app), NAMES, "the documents keep their order"); + let uid = app.session.documents()[0].uid; + assert!(app.ui.floating.iter().any(|w| w.uid == uid), "Alpha floats in a window"); +} + +#[test] +fn next_document_steps_through_the_tabs_in_their_new_order() { + let (mut app, ctx) = app(); + let delta = tab(&mut app, &ctx, 0.1, "Delta"); + let alpha = tab(&mut app, &ctx, 0.15, "Alpha"); + drag(&mut app, &ctx, 0.2, delta, alpha - egui::vec2(80.0, 0.0)); + assert_eq!(order(&app), ["Delta", "Alpha", "Bravo", "Charlie"]); + assert_eq!(current(&app), "Delta"); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(current(&app), "Alpha", "after Delta, now first, comes Alpha"); + app.run("window.previousDocument", json!({})).unwrap(); + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(current(&app), "Charlie", "before the first tab comes the last"); +} + +#[test] +fn a_click_on_a_tab_still_switches_to_it() { + let (mut app, ctx) = app(); + let bravo = tab(&mut app, &ctx, 0.1, "Bravo"); + frame(&mut app, &ctx, 0.2, vec![Event::PointerMoved(bravo)]); + frame(&mut app, &ctx, 0.25, vec![button(bravo, true)]); + frame(&mut app, &ctx, 0.3, vec![button(bravo, false)]); + assert_eq!(current(&app), "Bravo"); + assert_eq!(order(&app), NAMES); +} diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index a1374bd373..96e4533449 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -418,3 +418,59 @@ fn a_compound_path_under_direct_selection_drops_edit_path() { let (_, texts) = bar(&mut app); assert!(has(&texts, "Release Compound Path") && !has(&texts, "Edit Path"), "{texts:?}"); } + +/// After a switch to another document and back, the task bar shows the actions for the active +/// document's selection: an open path's Join in the first, a rectangle's Shape Properties in the +/// second. +#[test] +fn the_task_bar_follows_the_active_document() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + assert!(has(&bar(&mut app).1, "Join")); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join") && has(&texts, "Duplicate"), "{texts:?}"); + app.session.set_active(0); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Join"), "{texts:?}"); + app.session.set_active(1); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join"), "{texts:?}"); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "Rectangle Properties:"), "{texts:?}"); + assert!(!locked(&app, rect), "the button doesn't lock the shape"); +} + +/// The task bar shows the selection as it is after an edit and after Undo: Join leaves once the +/// open path is closed and comes back with Undo, and Shape Properties shows a rectangle's new +/// corner radius and then its old one. +#[test] +fn the_task_bar_follows_edits_and_undo() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + assert!(has(&bar(&mut app).1, "Join")); + app.run("path.join", json!({})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Join"), "{texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Join"), "{texts:?}"); + + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); + app.run("object.setLiveShape", json!({"radius": 20})).unwrap(); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "20 pt") && !has(&texts, "10 pt"), "{texts:?}"); + app.run("edit.undo", json!({})).unwrap(); + let (_, texts) = click_lock_slot(&mut app); + assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); + assert!(!locked(&app, rect), "the button doesn't lock the shape"); +} diff --git a/crates/ui-egui/src/thumb_worker.rs b/crates/ui-egui/src/thumb_worker.rs index f187d06dd4..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,12 +33,25 @@ struct Job { run: JobFn, } +/// 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), + Discard(SlotTest), +} + /// A render thread for one panel's thumbnails. Jobs go in by slot (the Navigator has one, the /// Layers panel one per row): a job not started yet is replaced by a newer one for its slot, so /// only the latest image of anything is drawn. pub struct ThumbWorker { - tx: Sender>, + tx: Sender>, rx: Receiver>, + forgotten: Forgotten, } impl ThumbWorker { @@ -52,46 +66,99 @@ impl ThumbWorker { } /// Spawn the thread. - fn start(ctx: &egui::Context, name: &str) -> Option { - let (tx, jobs) = channel::>(); + 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}")) .spawn(move || { let mut r = Renderer::new(); let mut queue: VecDeque> = VecDeque::new(); - let add = |queue: &mut VecDeque>, job: Job| match queue.iter_mut().find(|j| j.slot == job.slot) { - Some(old) => *old = job, - None => queue.push_back(job), + let add = |queue: &mut VecDeque>, msg: Msg| match msg { + Msg::Job(job) => match queue.iter_mut().find(|j| j.slot == job.slot) { + Some(old) => *old = job, + None => queue.push_back(job), + }, + Msg::Discard(which) => queue.retain(|j| !which(&j.slot)), }; 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 /// thread is gone: the caller renders on the UI thread from now on. #[must_use] pub fn submit(&self, slot: S, key: K, run: JobFn) -> bool { - self.tx.send(Job { slot, key, run }).is_ok() + self.tx.send(Msg::Job(Job { slot, key, run })).is_ok() + } + + /// Drop the jobs not started yet whose slot `which` picks, so they don't hold up the jobs + /// submitted after them; they never come back from [`ThumbWorker::poll`]. A job already + /// running still finishes. False when the thread is gone, as for [`ThumbWorker::submit`]. + #[must_use] + pub fn discard(&self, which: impl Fn(&S) -> bool + Send + 'static) -> bool { + 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 @@ -106,6 +173,12 @@ impl ThumbWorker { } } } + + /// The next finished job, waiting for it; None when the thread is gone. + #[cfg(test)] + pub(crate) fn wait(&self) -> Option> { + self.rx.recv().ok() + } } /// When the document last changed, for [`SETTLE_SECS`]: thumbnails already shown are drawn again @@ -163,6 +236,31 @@ mod tests { drop(w); } + #[test] + fn discarded_jobs_do_not_run_and_the_running_one_finishes() { + let Some(w) = ThumbWorker::::start(&egui::Context::default(), "test") else { return }; + let job = |n: u32| -> JobFn { Box::new(move |_| Some(Rendered { width: n, height: 1, pixels: vec![0; 4] })) }; + // A job that holds the thread until it is let go, so the others queue behind it. + let (started, running) = channel::<()>(); + let (release, held) = channel::<()>(); + let blocker: JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(w.submit(0, 0, blocker)); + running.recv().expect("the first job starts"); + assert!(w.submit(1, 1, job(1))); + assert!(w.submit(2, 2, job(2))); + assert!(w.submit(1, 3, job(3))); + assert!(w.discard(|slot| *slot == 0 || *slot == 1)); + assert!(w.submit(3, 4, job(4))); + release.send(()).expect("the first job is waiting"); + assert_eq!(w.wait().map(|d| d.key), Some(0), "the running job finishes"); + assert_eq!(w.wait().map(|d| d.key), Some(2), "slot 1's jobs were dropped"); + assert_eq!(w.wait().map(|d| d.key), Some(4), "a job submitted after the discard runs"); + } + #[test] fn settles_after_the_document_stays_unchanged() { let ctx = egui::Context::default(); 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 ed4fb0ac15..b5bc1991bd 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -52,9 +52,9 @@ pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_labe pub(crate) use labels::{label_field, take_previous_label}; 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, opt_field, opt_field_named, - plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, spin_field, - spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, + SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_within, num_field_within_empty, opt_field, + opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped, size_field, size_field_named, slider, + spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, }; #[cfg(test)] use numeric::{decimal_point, field_number, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; @@ -441,9 +441,9 @@ mod step_to_multiple_tests { mod decimal_point_tests { use super::*; - /// A decimal comma reads as a point, in a length, with arithmetic and in a percentage; text - /// with a point keeps its commas and is refused as before, and so does a thousands comma - /// (#3837). + /// A decimal comma reads as a point, in a length, with arithmetic and in a percentage, next to + /// numbers written with a point too (#5684); a number with both separators is refused, and so + /// is a thousands comma (#3837). #[test] fn a_decimal_comma_reads_as_a_point() { let mm = |s: &str| Unit::Millimeters.parse(&decimal_point(s)).map(|pt| Unit::Millimeters.from_pt(pt)); @@ -460,6 +460,15 @@ mod decimal_point_tests { let got = mm(text).unwrap_or(f64::NAN); assert!((got - want).abs() < 1e-9, "{text} is a decimal: {got}"); } + // Each number reads its own separator: a comma typed after a value shown with a point + // (#5684). A number with both separators is refused. + for (text, want) in [("100,5-20", 80.5), ("100-0,5", 99.5), ("10,5*2", 21.0), ("100.5 mm-0,5", 100.0), ("0,5+100.25", 100.75)] { + let got = mm(text).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-9, "{text}: {got}"); + } + for both in ["1.234,5", "1,234.5", "1.5,5-2"] { + assert_eq!(mm(both), None, "{both}: a point and a comma in one number"); + } assert_eq!(share_of("12,5%", 200.0), Some(25.0)); assert_eq!(share_of("1,000%", 200.0), None, "1,000% reads as thousands: refused, not 1%"); } diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 7f619aa239..ed1f257eeb 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -20,10 +20,12 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { } /// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837). Text with a point keeps its commas, so `1,000.5` is still refused rather than read -/// with two decimal separators, and so does a number that reads as thousands ([`thousands`]). +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !text.contains('.') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } /// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three @@ -59,20 +61,35 @@ pub fn num_field_within( bounds: RangeInclusive, ) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false) + unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false, "") +} + +/// [`num_field_within`] whose empty value reads `empty` (Transform Each's Absolute scales read +/// "Mixed" when the selected objects differ): typing replaces it, as it replaces the value shown. +pub fn num_field_within_empty( + ui: &mut Ui, + id: impl std::hash::Hash, + value: Option, + empty: &str, + unit: Unit, + width: f32, + bounds: RangeInclusive, +) -> Option { + let label = take_previous_label(ui); + unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false, empty) } /// [`num_field`] for a row whose visible label is not an adjacent label widget (a grid cell with /// its label painted separately): screen readers name the field `name` (already translated). pub fn num_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option, unit: Unit, width: f32) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, name, value, unit, width, false, ANY, &[], false) + unit_field(ui, id, label, name, value, unit, width, false, ANY, &[], false, "") } /// The field returns valid typed distances immediately and preserves the text being edited. pub fn num_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: Option, unit: Unit, width: f32) -> Option { let label = take_previous_label(ui); - unit_field(ui, id, label, None, value, unit, width, false, ANY, &[], true) + unit_field(ui, id, label, None, value, unit, width, false, ANY, &[], true, "") } /// Any number: the bounds of a field that has none. @@ -100,9 +117,10 @@ fn unit_field( bounds: RangeInclusive, stops: &[f64], live: bool, + empty: &str, ) -> Option { let id = id_with(ui.scope_id(), id); - let shown = value.map(|v| unit.format(v)).unwrap_or_default(); + let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string()); take_dialog_focus(ui, id, &shown); let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name); select_all_on_focus(ui, &resp, &buf); @@ -332,7 +350,7 @@ pub fn size_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str } }); } - unit_field(ui, id, label, name, value, unit, width, true, ANY, &[], false) + unit_field(ui, id, label, name, value, unit, width, true, ANY, &[], false, "") } /// [`plain_field`] for a number kept within `range` (the values of dialogs, preferences and panels @@ -600,7 +618,7 @@ pub fn spin_field_stops_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, None, None, None, width, step, min, presets, presets, &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets, false) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, presets, false, "") }) .and_then(SpinPick::value) } @@ -657,7 +675,7 @@ pub fn spin_field_auto_named( ) -> Option { let label = take_previous_label(ui); spin_generic(ui, label, value, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| { - unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false) + unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false, "") }) } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2aa1e3496a..a0e392cd6c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -402,6 +402,12 @@ Bar Position (`window.taskBar.reset`), which unpins it and puts it back under th Panel. As in Illustrator, neither the position nor the pin is saved: each launch starts with the bar under the selection. +The Compound Shapes add-on's setting, `window.pathfinder.compoundShapes` (omitted params toggle; checked while on; kept with the +preferences; off by default), swaps what a click and an Alt-click do on the Pathfinder panel's Shape Mode buttons: on, a click makes a +compound shape (`object.compoundShape.make`) and Alt-click gives the permanent Pathfinder result. Selected members of a compound +shape always take the clicked mode (`object.compoundShape.setMode`). Its submenu, Object › Plug-ins › Compound Shapes, also lists +Make, Release and Expand Compound Shape. + The Free Transform widget: while the Free Transform tool (E) is active, a small box at the canvas's top left holds Constrain over the tool's three modes, Free Transform, Perspective Distort and Free Distort. The buttons set the tool's options, as `tool.setOption {key: "mode", value: "free"|"perspective"|"distort"}` and `{key: "constrain", value}` do: @@ -484,14 +490,15 @@ equivalents); `ui.dialog.confirm` runs `swatch.spotOptions {useLab}` as one undo Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `scale`, `object.transformEach` → `transformEach`, also Move, Rotate, Reflect, Shear and the Path dialogs). The Scale dialog (`scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`, -`scaleV` %, `moveH`, `moveV` pt, `rotate` °, `reflectX`, `reflectY`, `random`, `reference` 0–8, `copy`, `preview`) +`scaleV` %, and `absH`, `absV` pt, the width and height each object becomes with `relative` false, absent while they +read "Mixed"; `moveH`, `moveV` pt, `rotate` °, `reflectX`, `reflectY`, `random`, `reference` 0–8, `copy`, `preview`) have the fields `corners` (Scale Corners) and `strokes` (Scale Strokes & Effects). They start from the preferences `scaleCorners` and `scaleStrokes`, and `ui.dialog.confirm` keeps them as the preferences (`prefs.set`) before running `object.scale` / `object.transformEach` with them. The Transform panel's checkboxes and flyout item and the Properties panel's checkbox set the same preferences through `prefs.set`. Transform Each opens on the values it was last -confirmed with (scale, move, rotate, reflect, random, reference, `objects` and `preview`; never `copy`), kept with the -UI state (#1732). Its Copy button, left of Cancel, sets `copy: true` and confirms; `ui.dialog.set {field: "copy", -value: true}` then `ui.dialog.confirm` does the same. +confirmed with (scale, Relative or Absolute, the link between the two scales, move, rotate, reflect, random, +reference, `objects` and `preview`; never `copy`), kept with the UI state (#1732). Its Copy button, left of Cancel, +sets `copy: true` and confirms; `ui.dialog.set {field: "copy", value: true}` then `ui.dialog.confirm` does the same. Use Preview Bounds: the Align panel flyout's Use Preview Bounds item shows and toggles the `usePreviewBounds` preference (`prefs.set`); while it is on, the bounding box and the Transform panel, Properties and Control bar @@ -523,7 +530,8 @@ opens the `perspectivePlane` dialog (fields `plane`: left, right or ground; `loc normal; `objects`: none, move or copy). `ui.dialog.confirm` runs `perspective.plane.move` with them. Units: dialog distance fields (Move's `dx`/`dy`, shape sizes, Offset Path's `offset`, Split Into Grid's gutters and totals, -Artboard Options' sizes, effects' distances, `transformEach`'s `moveH`/`moveV`, New Document's `width`/`height`, the +Artboard Options' sizes, effects' distances, `transformEach`'s `moveH`/`moveV` and its Absolute `scaleH`/`scaleV`, New +Document's `width`/`height`, the length preferences in `preferences`) show in the General unit (the active document's units, or `unitsGeneral` without a document). Through `ui.dialog.set` a number is in points and a string may carry its unit (`"10 mm"`; a bare number in a string is points). The `preferences` dialog's `unitsGeneral` starts as the active document's units, and OK sets them. @@ -859,7 +867,7 @@ events take `pressure` (0..1, default 1): it is the Liquify intensity while Use Freehand Tool Options: double-clicking the Pencil, Paintbrush, Smooth, Blob Brush or Eraser tool (`tool.options {tool: "pencil"}`) opens a `freehandOptions` dialog. Its fields are `tool` and the options the tool -keeps: `fidelity` (pt; Pencil, Paintbrush, Smooth, Blob Brush), `fill` (Pencil, Paintbrush), `keepSelected` (Pencil, +keeps: `fidelity` (screen pixels for the Pencil and Paintbrush, the same at any zoom; pt for Smooth and Blob Brush), `fill` (Pencil, Paintbrush), `keepSelected` (Pencil, Paintbrush, Blob Brush; on by default for the Pencil and Paintbrush and off for the Blob Brush, and while it is off the path a stroke draws, continues or merges into is not selected afterwards), `mergeOnlySelection` (Blob Brush; off by default, and while it is on a stroke merges only with selected blobs), `closeWithin` and `editWithin` diff --git a/docs/effects-parity.md b/docs/effects-parity.md index d4aa59eaf5..2878c56825 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Expand Appearance makes each copy of a path's Transform effect an object of its own (#5612); previously: Pixelate › Color Halftone: Max Radius in pixels of the Document Raster Effects resolution, 4–127 px, with older documents converted on opening and radii written back in points for older app versions (#3260); Effect dialogs clamp bounded length inputs immediately on commit and flash rejection on invalid input (#4638); previously: Drop Shadow Darkness uses fixed RGB subtraction and CMYK black addition; scores unchanged; Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add an overprinting strip of the lighter colour where two solid colours meet; recounted with Hard Mix (#3061) and Soft Mix already in the catalogue: Pathfinder 13/13, Illustrator effects 49/50) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -22,7 +22,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( |---|---|---:|---| | Convert to Shape | Rectangle, Rounded Rectangle, Ellipse | 3/3 | — | | Crop Marks | Crop Marks | 1/1 | — | -| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646) | +| Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612) | | Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | | Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | @@ -193,6 +193,8 @@ angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Expand Appearance of a path or compound path whose Transform effect makes copies gives a group of one object per copy, each with the path's fills and strokes, instead of one compound path of every copy; copies of copies nest (#5612). Counts unchanged. | +| 2026-10-30 | minor | Pixelate › Color Halftone: Max Radius is in pixels of the Document Raster Effects resolution, 4–127 px, as the [filter effects reference](https://helpx.adobe.com/photoshop/using/filter-effects-reference.html) gives it, instead of points (#3260): fine screens are possible at print resolutions (4 px at 300 ppi ≈ 0.96 pt). The dialog and the Appearance panel show it in px whatever the document units; documents saved before (document versions 1 and 2) open with each radius converted, so their dots stay the same size, and a file saved for an older app version (native versions before today's) holds them in points again. Scores unchanged. Tests: `vectorcraft_effects` `color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution` and `color_halftones_radius_is_in_raster_pixels_not_a_distance`, `vectorcraft_doc` `halftone_radii::tests`, `vectorcraft_format` `halftone_radii_of_older_documents_open_in_pixels`, `vectorcraft_engine` `a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels`, `dialogs::tests::color_halftones_max_radius_stays_in_pixels_whatever_the_units`. | | 2026-10-30 | minor | Effect dialogs: bounded length fields (Color Halftone Max Radius) clamp on commit and visibly reject invalid input (#4638); scores unchanged. | | 2026-10-23 | minor | Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)): the Pathfinder panel's Trap… (`object.pathfinder.trap`, one undo step, the traps grouped above the topmost selected object and selected) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add an overprinting strip of the lighter colour inside the darker one where two solid colours meet (Reverse Traps: the darker into the lighter, but not a rich black), with Thickness, Height/Width, Tint Reduction and Traps with Process Color; the effect also has Precision and Remove Redundant Points. Recounted: Hard Mix (#3061) and Soft Mix had shipped, so Pathfinder 11/13 → 13/13 and Illustrator effects 46/50 → 49/50 (SVG Filters remains); remaining 6–10 → 4–8 h. Tests: `vectorcraft_pathops` `trap::tests`, `vectorcraft_effects` `trap::tests` and `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `vectorcraft_engine` `tests_trap`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`. | | 2026-10-22 | minor | The Transform effect has Transform Objects, Transform Patterns and Scale Strokes & Effects, with visible checkboxes (#885); on a fill's or stroke's own Transform effect the last two are still missing. Counts unchanged. | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 206f368016..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-01 · **Change:** minor (native format: dynamic symbols, #4938) · **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,6 +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 d754fe7740..0f98d7e8b0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,17 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (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 (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,11 @@ 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) | +| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): Object › Plug-ins › Compound Shapes lists Make, Release and Expand Compound Shape, and holds a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons make a compound shape on a click and give the permanent result on Alt-click (the default is the reverse). Selected members of a compound shape always take the clicked mode. The setting is `window.pathfinder.compoundShapes`; no existing behavior changes while it is off. Scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-02 | minor | Font-family fields step selected text with the mouse wheel (#5253); no scored gap or estimate reassessed. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | @@ -170,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 @@ -437,9 +456,11 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** User Interface › Open Documents As Tabs: with the box cleared, each document opened or created afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. -- **Missing:** 3 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: - Hyphenation › Default Language (hyphenation is English-only, with no per-language - dictionaries), Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to +- **Done:** Hyphenation › Default Language is the language of new type, unless Document Setup chose one, and each + run hyphenates in its own language (Character panel). Only English has break points so far: text in another + language stays whole, apart from the Exceptions list (#394). +- **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: + Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to disk), and Clipboard Handling › Legacy vector clipboard with its Preserve Paths / Preserve Appearance and Overprints choice (Illustrator's own clipboard flavour, which has no public specification). Also Properties panel per context, context menus beyond the canvas, Layers panel row menus and Collect for Export, SVG @@ -534,9 +555,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 @@ -611,6 +634,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Window › Arrange › Tile (`window.arrange.tile`) shows every open document in its own pane, edge to edge in the document area, and Consolidate All Windows (`window.arrange.consolidateAllWindows`) goes back to one document under its tab, on the desktop and the web. Estimate unchanged. - **Done:** Window › Arrange › Float in Window (`window.arrange.floatInWindow`), Float All in Windows (`window.arrange.floatAllInWindows`) and Cascade (`window.arrange.cascade`) move documents out of the tab strip into floating windows of their own, OS windows on the desktop and windows inside the app's window on the web and on Wayland; Cascade stacks them from the upper left to the lower right. Consolidate All Windows brings them back under the tabs. Estimate unchanged. - **Done:** a document tab dragged off the tab strip floats its document in a window under the pointer, and a document window dragged by its title bar (an OS window by the tab at its top) onto the tab strip goes back under the tabs. Estimate unchanged. +- **Done (#5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)), a line marking where it goes; the current document stays current, each document keeps its own view, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` does the same from MCP and the control channel. Estimate unchanged. - **Done (#4116):** Window › New Window (`window.newWindow`) opens another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab titled with the view's number ("Name:2"); Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document. Closing a view leaves the document open until its last view closes. Estimate unchanged. - **Estimate:** 15–25 h. @@ -625,6 +649,11 @@ 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):** 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). Still to do: the first frame still renders on the UI thread, + and at 100% zoom or more an image is still separated whole; tiles would bound that by the view. - **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 @@ -735,6 +764,8 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-03 | minor | Symbol editing shows draggable 9-slice guides within the artwork (#5280). Guides outside the artwork remain unsupported. The G5 estimate remains 14–24 h. | 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 14ef0f74f7..720c0d4e3e 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. | +| `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. | @@ -489,14 +490,17 @@ mode. To press the key during a drag, end one bounding-box scale or rotation, a marquee, a corner widget, pie widget or bracket drag) cancels it: the art goes back, no copy is left, no undo step is added, and the `up` event that follows does nothing. -With nothing being dragged, `e` chooses the tool bound to E. +With nothing being dragged, headless `press_key` `e` chooses the tool bound to E. Remote `press_key` does not run +single-key shortcuts (see the Arc tool below). While an arc is being dragged out with the Arc tool, `press_key {key: "c"}` switches it between an open and a closed path, `{key: "f"}` switches its base between the X and Y axes in the same box, and `{key: "up"}` and `{key: "down"}` raise and lower its slope by 10, within −100…100. Each press switches once. The arc drawn on release uses these values, and they stay as the Arc tool's `closed`, `baseAlong` and `slope` options for the next arc. With nothing being -dragged, `c` chooses the tool bound to C, and `f` runs the shortcut bound to F in remote mode (headless has no -binding for it). +dragged, headless `press_key` `c` chooses the tool bound to C (headless has no binding for F). In remote mode, +`press_key` sends the key event without the letter it types, and the app runs a single-key shortcut such as C or F only +from the typed letter, so with nothing being dragged `c` and `f` do not run their shortcuts there. Use `select_tool` or +`invoke_menu` instead. While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows @@ -515,7 +519,8 @@ While a grid is being dragged out with the Rectangular Grid or Polar Grid tool, 10, and `{key: "x"}` and `{key: "c"}` lower and raise that of the vertical dividers (`columnSkew`) or the concentric dividers (`concentricSkew`), within ±500. Plain and Shift presses change the skew; with Alt, Ctrl or Cmd held they do not. The grid drawn on release uses these skews, and they stay as the tool's options for the next grid. With nothing -being dragged, the four letters run their shortcuts as before. +being dragged, headless `press_key` runs the shortcuts bound to `v`, `x` and `c` (it has none for `f`), and remote +`press_key` does not run single-key shortcuts (see the Arc tool above). Appearance stacks: an object can carry several fills and strokes (`appearance.addFill`, `appearance.addStroke`), indexed in paint order (0 is painted first, the bottom row of the Appearance panel). Cmd+/ runs `appearance.addFill` and @@ -704,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 @@ -926,8 +936,8 @@ Method (the Gradient panel's menu): `classic` (the default) mixes the colours be Perceptual gradient as an image at the Document Raster Effects resolution (a dithered Perceptual fill with its noise). PDF exports write it the same way, except for a linear or radial gradient with spot color stops whose other stops are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve does not have too many -stops. A CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in -CMYK. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK +stops. An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a +CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. `paint.setFill`/`paint.setStroke` take it in `gradient` too: @@ -1141,7 +1151,7 @@ nothing. These Object menu commands refuse a string, a number or another value that is not true or false with `` `copy` must be true or false ``, naming the key, and change nothing: `reflectX`, `reflectY`, `random`, `copy`, -`strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray` and `deleteRaster` in +`relative`, `strokes`, `corners`, `objects` and `patterns` in `object.transformEach`; `gray` and `deleteRaster` in `object.createObjectMosaic`; `trim` in `object.cropImage`; `allArtboards` in `object.createTrimMarks`; and `byColumn`, `moveArtwork` and `patterns` in `artboard.rearrange`. A null is read as a key left out. `object.createTrimMarks` refuses a `style` that is not a string, such as `5`, with `` `style` must be roman or japanese ``, the message it gives @@ -2328,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 @@ -2788,8 +2799,8 @@ give it `swatch` (and `tint` %, default 100 or a tint swatch's own) instead of ` in gradient swatches. A spot stop separates on its plate. A linear or radial gradient whose stops are all tints of one spot ink (or paper white, 0 %) exports to PDF as a Separation shading, and one that mixes spot inks with other spot, CMYK or gray inks exports as a DeviceN shading. A gradient that mixes a spot ink with colors written in RGB or Lab is written in -process colors, with a warning; a CMYK document, or an export that converts colors to a CMYK destination profile, -writes RGB and Lab stops in CMYK. Freeform gradients and dithered fills export to PDF as images in process colors, and Method +process colors, with a warning; an export that converts colors to a CMYK destination profile writes RGB and Lab stops +in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. Freeform gradients and dithered fills export to PDF as images in process colors, and Method above covers Perceptual gradients. ```json @@ -3202,6 +3213,19 @@ used, as a transform's does. {"name":"run_command","arguments":{"command":"object.transformEach","params":{"scaleH":50,"scaleV":50,"strokes":false}}} ``` +## Transform Each: Relative and Absolute + +`object.transformEach` scales by percentages of each object's size (the dialog's Relative, the default), or with +`relative: false` to the width and height each object becomes: `scaleH` and `scaleV` in pt, as the dialog's Absolute. +Absolute is measured on each object's own geometric bounds, so objects of different sizes come out alike about their +own reference points. A side left out keeps its size, a side the object doesn't have (a line's height, say) keeps its +factor 1, and a scale of 0 is refused in either mode, as it collapses the object. `object.transformAgain` repeats the +Absolute target, so it leaves objects that already have that size as they are; repeat a scale with Relative instead. + +```json +{"name":"run_command","arguments":{"command":"object.transformEach","params":{"relative":false,"scaleH":50,"scaleV":50}}} +``` + ## Live Corners `object.setLiveShape {id?, ids?, radius?, kind?, corners?, items?}` sets the corners of any path (one undo step): a live @@ -4140,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. @@ -4964,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}}} @@ -5411,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. @@ -6483,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 @@ -6614,13 +6651,18 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. -- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?}` cuts live corners, the ones Direct Selection's +- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and `anchors` the anchor indices of each path's outline with no corners cut; without `anchors`, a path's direct-selected anchors, or all of them. `items: [{id, anchors?}…]` gives each path its own instead. Only anchors where two sides meet at an angle take a corner: smooth anchors and open ends are skipped, and it is an error if none is left. `radius` is 0 to 1,000,000 pt, drawn no larger than fits; `kind` is `round`, `invertedRound` or `chamfer` (default: each corner's - own). → `{ids, corners}`. + own). `every` (`all`, `odd` or `even`; default `all`) keeps, of those anchors, only the odd- or even-numbered ones, + counting each path's anchors from 1 (the 1st, 3rd, 5th… are odd): an anchor that takes no corner still counts, and it + is an error if none is left. `minAngle` and `maxAngle` (degrees 0 to 180; default 0 and 180) keep only the corners + whose sides meet at an angle in that range (small for a sharp spike, near 180 for a shallow bend); `minAngle` can't + be more than `maxAngle`, and it is an error, saying so, if no chosen corner is in the range. Object › Plug-ins › Path Precision Tools › Set Corners… (also in the Anchor Inspector's + Corners section) sets these with Preview. → `{ids, corners}`. - `addon.pathtools.cornerRemove {ids?, anchors?, items?}` makes those corners sharp again, as one undo step; a plain path with none left is plain again. → `{ids, corners}`. - `addon.pathtools.slideAnchor {id, subpath?, anchor, t}` moves an anchor along its path, the segments beside it refitted @@ -6762,6 +6804,27 @@ The panel sets the next segment and runs Remove Points Keep Shape (`addon.pathto {"name":"run_command","arguments":{"command":"addon.pen.reshape","params":{"id":12,"segment":0,"t":0.3,"dx":0,"dy":-25}}} ``` +## Contour add-on + +Contour is a built-in add-on: it grows or shrinks a copy of a path or shape by a distance, live. Its command is +`addon.contour.set`; in the desktop app it lives in Object › Plug-ins › Contour and in the Contour Tool (`contour`), which +the toolbars don't show until it is added from the All Tools drawer (or chosen with `tool.select`); it has no shortcut. A +floating bar over the selection (the distance, Sharp / Round / Square and Bake) acts through the same commands. + +`addon.contour.set {offset, corners?, miterLimit?}` puts a copy of each selected path, shape or compound path directly above +it with a live Offset Path effect of `offset` points (negative insets), and selects the copies. `corners` is `"sharp"` +(default), `"round"` or `"square"` (corners cut off flat), `miterLimit` 1 to 500 (4; sharp corners). A selected object that +already has that effect (a Contour made earlier) has its effect changed instead of getting another, so the same call +adjusts a Contour. The original is kept, and nothing is baked: `effect.expandAppearance` turns a Contour into plain paths. +Type, images and groups are left alone; with nothing to offset it says "select paths or shapes". One undo step. Result: +`{ids, created, updated}`. + +The tool (`contour`) drags a distance from the selected shape's edge, outward to grow and inward to shrink: the press +changes nothing until the pointer moves, a Contour that already stands at a distance continues from it, Shift rounds to +whole points and Escape cancels. A drag keeps a Contour's own corners and miter limit; a new Contour takes the tool's +options `corners` and `miterLimit` (`tool.setOption`). A border with a gap is two Contours of one shape (the gap first, so +it ends up in front), baked with `effect.expandAppearance`, then `object.pathfinder.minusFront`. + ## Color Effects add-on Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is @@ -6821,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 @@ -6997,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 @@ -7019,8 +7108,8 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Type Tools add-on -Type Tools is a built-in add-on for type: its command is `addon.type.textTweaker`, and in the desktop app it lives in -Object › Plug-ins › Type Tools (#4924). Text Tweaker gives one character attribute to the characters letter by letter, +Type Tools is a built-in add-on for type: its commands are `addon.type.textTweaker` and `addon.type.releasePath`, and +in the desktop app it lives in Object › Plug-ins › Type Tools (#4924, #5532). Text Tweaker gives one character attribute to the characters letter by letter, from a start value to an end value along a shape, as one undo step; the text stays live and editable. Each value is set as `text.setRangeStyle` sets it (the Character panel), in its units and ranges ([formatting type](https://helpx.adobe.com/illustrator/using/formatting-type.html)), so on scaled type it is the size shown. @@ -7045,3 +7134,38 @@ default values, and the seed starts new whenever the document has changed. {"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"baselineShift","from":0,"to":18,"shape":"bow"}}} {"name":"run_command","arguments":{"command":"addon.type.textTweaker","params":{"attribute":"rotation","from":-15,"to":15,"shape":"random","seed":4}}} ``` + +### Release Type on a Path + +`addon.type.releasePath` splits each type on a path (`text.createInPath` with `mode: "onPath"`) into point type that +holds the same text and the plain path it was set on (#5532). The reference app has no command for this, so it is a +VectorCraft addition and changes no parity score. + +- **The path** keeps its exact shape (open or closed, every anchor and handle, the object's transform) and goes in the + type's layer at its place in the stacking order. Type paths carry no paint of their own (making type on a path drops + the path's fill and stroke), so the released path has no fill and no stroke. +- **The text** keeps its runs with their character attributes and its paragraph attributes, and becomes point type on + one straight line along the object's own axis, with the baseline starting where the first character sat on the path + (type with no characters starts at its start bracket). Type on a Path Options (effect, align to path, spacing, flip, + brackets) don't apply to point type and are dropped. Without `keepOriginal` the type object itself becomes the point + type, keeping its id, so a frame of threaded text leaves its thread with the text it holds, as + `type.convertToPointType` does for area type. +- It acts on the type on a path among `ids` (or `id`, else the selection), groups included; other objects are left + alone. With none among them nothing changes and no undo step is made. Otherwise the whole run is one undo step and + the released objects are selected. + +| Parameter | Values (default) | +|---|---| +| `mode` | `both` (point type and the path), `path` (the path only: the type goes), `text` (point type only) (`both`) | +| `keepOriginal` | false; true: the type on a path stays as it is and the released objects go just above it | +| `ids`, `id` | the objects to release (default: the selection) | + +→ `{ids (the released objects, bottom to top), paths, texts}`. Release Type on a Path… opens the command dialog +(`ui.paramDialog`) on Mode (Text and Path, Path Only, Text Only) and Keep Original, with Preview: while Preview is on +the canvas shows the release, Cancel restores the original with no undo step, and OK applies it as one, as Type on a +Path Options' Preview does (#5360). + +```json +{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{}}} +{"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} +``` diff --git a/docs/plugins.md b/docs/plugins.md index cd867d53ed..bdd02b6f64 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -51,7 +51,8 @@ background ([below](#heavy-filters)). **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; -the web build installs from bytes). +the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a +picked or typed folder whose contents can't be listed. Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record (`{"id": "plugin.", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it diff --git a/docs/roadmap.md b/docs/roadmap.md index 527bb286e1..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,7 +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 7adffe3db6..ab631eaee2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,14 +1,22 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Pencil: Edit Selected Paths follows strokes lifted away, carves, loops, closes and redraws compound paths (#3793), scores unchanged; previously: 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 (Pencil: Edit Selected Paths follows strokes lifted away, carves, loops, closes and redraws compound paths (#3793), scores unchanged; previously: large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; Libraries panel colours keep their spot ink in every document, #5812; 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. -**Feature evidence last updated:** 2026-11-03. +**Feature evidence last updated:** 2026-11-05. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. @@ -23,9 +31,27 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 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. | +| 2026-11-04 | minor | Path Precision Tools add-on (a VectorCraft addition): Set Corners… and `addon.pathtools.cornerSet` `every` round all, the odd-numbered or the even-numbered anchors of each path (#5546); evidence added; scores unchanged. | +| 2026-11-04 | minor | Transform Each's Scale has the documented Relative and Absolute radio buttons (`object.transformEach` `relative`: percentages of each object's size, or the width and height it becomes, measured on each object's own bounds) and the link that keeps the two scales in proportion; the panel lists Scale, Move, Rotate, the Options in two columns, the Reference Point and Preview (level with Copy, Cancel and OK) in the documented order. Scores and estimates unchanged. | +| 2026-11-05 | minor | PDF import: a DeviceN gradient of a spot ink over process plates keeps the ink and the plates, and PDF export writes it as a DeviceN shading again (#3235); scores unchanged | | 2026-11-05 | minor | Optical kerning moves each pair part of the way toward the font's own stem spacing, with a minimum gap and tighter limits, and leaves ideographs, kana, fullwidth forms and dashes on the font's spacing, so text is no longer squeezed (#5336). Scores and estimates unchanged. | +| 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. | @@ -34,6 +60,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-03 | minor | Correct the Type core missing list and remove duplicate target and Type core entries: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | | 2026-11-03 | minor | Correct the Type core missing list: Hyphenation and Justification options are complete; the remaining Every-line Composer fidelity limits stay listed. Record the Kashidas paragraph lengths and per-character switch in the feature history (#5404). Scores and estimates unchanged. | | 2026-11-03 | minor | Ligature caret stops use GDEF contour-point positions in horizontal and vertical type at the font's default variation location; invalid point indices keep the evenly divided fallback. Scores and estimates unchanged. | +| 2026-11-04 | minor | Record Find Font's replacement rows: family and style together, a search over them, and a scroll state of their own (#4972); scores and estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-11-03 | minor | Type Tools add-on: Text Tweaker (a VectorCraft addition, #4924): evidence added; scores unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | @@ -175,7 +202,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, 4 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, hyphenation Default Language, 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** | | @@ -474,6 +501,8 @@ since 2026-10-01. | **Agent automation** | beyond Illustrator | Every command, gesture and dialog is drivable over MCP, the CLI and the control channel; synthetic-input counts, pending events and per-frame control requests are bounded (#1709); what an agent reads and writes on disk can be confined to chosen folders (`--automation-read-root` / `--automation-write-root`, as in PhotoCraft, #832) | | **Scrubby numeric fields** | beyond Illustrator | As in Photoshop, dragging a numeric field's label (`W:`, `Opacity:`, the Character panel's icons) left or right steps its value live; one undo step per drag, Escape cancels (#400) | | **Align Stroke on live type** | beyond Illustrator | The Stroke panel's Align Stroke works on type's character stroke: inside or outside the glyphs without Create Outlines, the type staying editable (as InDesign does; users have asked Illustrator for it since 2010, e.g. [redd.it/1dwhos6](https://redd.it/1dwhos6)). Canvas, PDF and EPS clip it to its side of the glyphs; SVG keeps the text live and draws the stroke on the glyph outlines (#2294) | +| **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 (Shift: whole points); the copy carries a live Offset Path effect so it stays editable, with its own fill and stroke, until Bake (Expand Appearance). A second drag on a selected Contour changes it instead of nesting another; Escape cancels. A floating bar above the selection sets the distance and the corners (Sharp, Round, Square); `addon.contour.set` makes or changes one over MCP and the control channel. The tool is in Object › Plug-ins › Contour and under its own heading in All Tools, with no default shortcut or toolbar slot. Two Contours baked and combined with Minus Front give a border with a gap. Paths, shapes and compound paths only; type isn't offset. Tests: `crates/engine/src/cmd/addons/contour/tests.rs`, `crates/ui-egui/src/canvas/tests.rs` | +| **Compound Shapes add-on** | beyond Illustrator | Object › Plug-ins › Compound Shapes puts Make, Release and Expand Compound Shape in the menus, and holds a setting (off by default) that swaps the Pathfinder panel's Shape Mode buttons: a click makes a compound shape and Alt-click gives the permanent result. Selected members of a compound shape always take the clicked mode; the setting is kept with the preferences. Tests: `panels::pathfinder::tests` in `crates/ui-egui/src/panels/pathfinder.rs` | ## Evidence: what ships today, by area @@ -504,6 +533,7 @@ since 2026-10-01. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Global Edit: Shift-click leaves a match out:** while Global Edit is on, a Shift-click with the Selection tool on a highlighted match, or on an object inside a matched group, leaves that match out (`select.globalEditExclude`): it is no longer highlighted and later edits leave it as it is; the object the edit started from stays, and Global Edit ends when fewer than two matches are left ([Update assets quickly with Global Edit](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)). Regression tests: `a_shift_click_*`, `an_object_left_out_*`, `a_group_left_out_*` and `leaving_out_all_but_one_*` in `crates/engine/src/tests/globaledit.rs`. - **Global Edit Options in the Control bar:** while Select › Start Global Edit can run, the Control bar shows a Global Edit Options dropdown that opens the same options as the Properties panel's (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)); both set the same options. The dropdown is off while Global Edit is on; it sits after Recolor Artwork, ahead of the X/Y/W/H fields ([Edit similar objects globally](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)). Regression test: `the_control_bar_shows_the_global_edit_options` in `crates/ui-egui/src/chrome/tests.rs`. +- **Global Edit's enabled check on large paths:** the check that decides whether Select › Start Global Edit can run on the selected path, compound path or symbol instance (which the Control bar makes every frame) measures the box of its anchors and handles instead of building and normalizing a copy of every anchor, with the same answer. On a 200,000-anchor path the check takes 0.7 ms instead of 2.2 to 3.0 ms. Regression tests: `support_*` in `crates/engine/src/cmd/globaledit.rs`. - **Control bar's inline X, Y, W and H fields fit the bar:** the Control bar shows the inline X, Y, W and H fields only when all four, their labels as drawn in the current language and the W/H link fit inside the bar's margin; otherwise it shows the Transform link alone. This is VectorCraft's own layout rule. Regression test: `the_control_bar_shows_the_inline_transform_fields_only_when_they_fit` in `crates/ui-egui/src/chrome/tests.rs`. - **Pattern-only backquote drags:** With Selection move, bounding-box scale or rotate, or the Rotate, Reflect, Scale or Shear tool, backquote held at mouse release applies the drag matrix to selected pattern paint while object geometry stays in place. The key may be pressed after mouse press; if released before the mouse button, the drag commits as an ordinary transform. Objects without pattern paint stay still; stroke-only patterns and patterned objects in mixed selections take the same matrix. Regression tests: `backquote_move_uses_release_state_and_one_commit` and `backquote_box_scale_and_rotate_use_pattern_matrix_at_release` in `select/tests.rs`, `backquote_drag_previews_and_commits_pattern_only_for_each_transform_tool` in `xform/transform.rs`, `selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art` and `selection_backquote_drag_changes_stroke_only_pattern` in `tests/pattern.rs`, `egui_backtick_drag_uses_key_state_at_release` in `canvas/tests.rs`, and `synthetic_pointer_backquote_keeps_solid_object_in_place` in `control/tests.rs`. Scores and hours unchanged. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. @@ -517,6 +547,7 @@ since 2026-10-01. - **Selected artboard deletion:** the Artboards panel menu, panel trash button and Properties use the same selected set; selecting all retains artboard 1. Pointer-event tests cover nonadjacent and single selections, the original first-board survivor, ordinary artwork, Undo/Redo and the single-board guard. Public reference: [Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). - **Delete Empty Artboards:** the Artboards panel menu item ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html)) runs `artboard.deleteEmpty`: every unlocked artboard with no artwork goes with its guides in one undo step, artboard 1 stays when every artboard is empty and none is locked, and the panel makes an artboard that is left active; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). Engine tests in `tests/panelcmds.rs` (`delete_empty_artboards_*`) and the panel test `delete_empty_artboards_deletes_the_empty_ones_and_selects_one_left`. + The menu item's enabled check measures nothing in a document with one artboard, and Save Gradient Preset's check reads the proxy's paint without measuring the object; both give the same answer as before. An artboard that no path's control points, grown by the farthest its strokes reach, can meet is found empty without measuring the path. With an open path of 200,000 anchors selected, the checks take under 0.01 ms instead of 21.9 ms and 17.2 ms in a release build; with a second, empty artboard, Delete Empty Artboards' check takes 0.85 ms instead of 42.1 ms. Tests `delete_empty_artboards_is_enabled_exactly_when_it_deletes_something`, `delete_empty_artboards_enabled_state_matches_the_command_on_varied_documents`, `empty_artboard_checks_match_the_visual_bounds_on_varied_strokes`, `the_empty_artboard_check_matches_measuring_every_artboard`, `the_save_check_matches_saving_with_and_without_a_gradient`, `the_unmeasured_proxy_paint_is_the_measured_one` and `the_unmeasured_proxy_paint_is_the_measured_one_on_varied_objects`. - **Artboard history selection:** headless pointer/key tests in `panels/properties.rs` pass for panel New → Undo → Delete/Backspace/Properties, Duplicate → Undo → Delete, pruning removed indices and preserving valid multiselection. They assert board survivors, artwork and object selection, Move/Scale Artwork options, saved state and Undo/Redo. Full workspace CI passes. - **Artboard tab-switch follow-up:** changing the active document through its tab aligns the Artboard tool with the displayed board before Properties Delete; clicking the already-active tab preserves multiselection and Move/Scale Artwork options. Three headless `chrome::tests::artboard_document_tab_*` regressions cover actual tab A → B → A clicks followed by Properties Delete, surviving boards and guides, preserved artwork/symbols and Undo/Redo; controls cover same-tab multiselection, Move/Scale Artwork options and other tools. Historical focused validation on `dbd2497b` recorded one expected RED failure with two passing controls, then all three GREEN tests passed. All three also passed in historical full CI on `a0671777`. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. - **Artboard clean active-tab close (2026-10-15):** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. Nine targeted checks passed: three existing tab regressions, one clean close/Delete regression and five existing unsaved-document controls. The close regression checks the correct surviving board, preserved artwork/symbols and object selection, affected guides, one Delete edit, saved state and Undo/Redo. Three reviewed original full-app headless captures show the active tab before closing, the surviving document's shown board after closing, and the correct survivor after Properties Delete, using the actual tab × and Delete controls. @@ -552,6 +583,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. +- **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. @@ -563,7 +595,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** the active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). - **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html). -- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`); with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). +- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. - **Shift with the Artboard tool:** a Shift-click adds an artboard to the selection or takes it out when the button comes up. A Shift-drag inside an artboard draws a new artboard there, and a Shift-drag on the pasteboard is a marquee that toggles the artboards it touches, as the [default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (a Shift-drag draws an artboard within an existing one) and [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy) describe. Shift no longer keeps an artboard move at 45° steps or a drawn artboard square. Escape during a marquee or while a new artboard is being drawn cancels it and keeps the Artboard tool. Pointer and key tests in `crates/tools/src/xform/artboard.rs` cover the four gestures and Escape. @@ -628,6 +660,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`). @@ -670,7 +703,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Three stored options still do nothing yet (the audit below). - Preferences › Type › Highlight Substituted Fonts (on by default) paints pink behind text drawn in a substitute for a missing font in every document, and turning it off removes that highlight everywhere (`prefs.set highlightSubstitutedFonts`); Document Setup keeps Highlight Substituted Glyphs ([help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/edit-text-without-replacing-missing-fonts.html)). - - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. + - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only (Units › East Asian Type and User Interface › Open Documents As Tabs, stored only on the day of the audit, act now: East Asian Type since 2026-10-31, Open Documents As Tabs as the Window › Arrange bullet says); [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - Units › East Asian Type (#394, `unitsAsianType`): Points by default; it offers every unit and Q and Ha, a quarter of a millimetre each (0.709 pt: the [Illustrator Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/); `q` and `h` are the field suffixes [InDesign's notation table](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html) lists), and only it lists them: rulers, Document Setup and the other Units preferences keep their ten. The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. The model stays in points; any length field reads `13q`/`13h`. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` (`crates/engine/src/tests/units.rs`). - Preferences audit (2026-10-30, #394): every Preferences dialog option is read by shipped code, by its field or its key, except User Interface › Open Documents As Tabs, Units › East Asian Type, Hyphenation › Default Language, Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard and its mode, which are stored only; [gaps.md G12](gaps.md#g12-preferences-and-panels-that-dont-act-yet) says what each waits on. - With Performance › Real-time Drawing and Editing off, the bounding box moves with a Selection-tool move drag and the object moves when the button is released ([help](https://web.archive.org/web/20220324053041id_/https://helpx.adobe.com/illustrator/using/real-time-editing.html); `real_time_drawing_off_moves_the_bounding_box_with_a_move_drag`). @@ -692,6 +725,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). @@ -723,6 +757,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. @@ -768,8 +803,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). - Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). - Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). The link that keeps Transform Each's two scales equal is not built. + Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. + Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. @@ -818,7 +853,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Pencil and Paintbrush Tool Options, Edit selected paths within 0 px turns editing off, so a stroke that starts exactly on an end of a selected open path draws a new path; Close paths when ends are within 0 px turns closing off, so a stroke that ends exactly where it started stays open. 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)). With Edit selected paths on, a Pencil or Paintbrush stroke that starts on a selected path and ends farther than its distance takes the path with it (a closed path opens where the stroke starts; an open one is cut there and drops the part the stroke heads along), one that returns to its start adds a loop, one over an open path's two ends closes it, a stroke across a closed shape replaces the side nearer to it, the stroke's ends bend onto the path, and a selected compound path's member paths are redrawn (`path.freehand` `redraw`, #3793); while the stroke is drawn, the preview shows it as drawn and the path changes at the release ([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`). @@ -853,7 +888,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)). @@ -1047,6 +1082,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. @@ -1060,6 +1096,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. Windows, Linux and other browsers have no sampler yet; the button is gray there. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. + - The Gradient panel's Delete Stop sits at the right end of the ramp, level with it, so a panel too short to show the stop fields still shows it; it deletes the selected stop (never below two), as dragging a stop down off the ramp does (#5403). - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. @@ -1099,7 +1136,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". @@ -1132,11 +1169,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Files (M4):** - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests/import_fidelity.rs`, `pdf/src/tests/realtext.rs`). - A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. + A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests/import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. The stops of an axial or radial shading in a DeviceN space that mixes one spot ink with process plates (a spot ink over a constant cyan, for example) link to the ink's swatch at its tint and keep the process plates, and PDF and EPS (Level 3) export write those stops in a DeviceN space of the ink and those plates, so the spot plate is not lost (#3235, `import_color::a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks`). Solid fills that mix a spot ink with process plates, and stops that mix several spot inks, still import as RGB, with the spot inks kept as swatches. PDF export writes a linear or radial gradient that mixes a spot color with process colors, or two spot colors, as a DeviceN shading of the spot inks and the process inks its stops use, so each spot ink prints on its own plate; an off-center midpoint is written as a stop with the inks halfway between its two stops. A gradient that mixes a spot color with RGB or Lab colors is still written without the spot ink, with a warning. A Perceptual gradient of spot inks is written as a Separation or DeviceN shading of the stops on its curve; a dithered gradient fill, and a Perceptual gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, are written as images in process colors, with a warning. A Lab spot color in such a shading is named by the same Separation space, with the Lab alternate, as its flat fills (`engine/src/tests/linked_stops.rs`, `engine/src/tests/labspots.rs`). PDF export writes a spot color named All or None (in a Separation space, the names of every plate and of no plate: [ISO 32000-1:2008](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf), 8.6.6.4) as the ink All Spot or None Spot (All Spot 2 and on when a spot swatch already has that name) in its fills, strokes, gradients, colorized images and Lab alternates; Registration still prints on every plate (`pdf/src/tests/output.rs`). - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). - Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. + Preferences › File Handling › Data Recovery › Folder has a Choose… button on the desktop that picks the folder Data Recovery keeps its copies in ([Illustrator reference, Set Data Recovery preferences](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)); a picked folder that Data Recovery cannot create its folders in or list is refused with a status message, and the field keeps its value. OK applies the same check to a folder typed into the field (VectorCraft's own rule): when it fails, the dialog stays open, the status bar says why and no preference changes; an empty field (the default folder) and the folder already saved are not checked. Preferences › Plug-ins & Scratch Disks is where additional plug-ins folders are set ([Illustrator preferences help](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html)); its Additional Plug-ins Folder has a Choose… button on the desktop as well, VectorCraft's own, matching Data Recovery's, and VectorCraft's own rule refuses a picked or typed folder whose contents can't be listed. Additional Fonts Folder and Templates Folder stay typed only. A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). A name returned by the desktop save panel with the extension of a format the save does not write has it replaced with the saved format's: Save As of a new document saves `card.ait` and `card.png` as `card.vectorcraft`, and Save as Template saves `card.pdf` as `card.vctemplate`. An extension that names no format stays part of the name (`notes.v2` is saved as `notes.v2.vectorcraft`). Export As, Save as PDF, Save for Office Documents, Save for Web, Text Export Options, print to file, the presets' Export… and the library, swatch and Document Info saves replace a typed extension of another format than the one they write in the same way: Export As PNG writes `card.svg` as `card.png`, Save as PDF writes `card.png` as `card.pdf`, and `document.exportSelection` with a `format` suggests and adds that format's extension. An extension of the written format stays as typed in any letter case (`photo.JPEG` for JPEG), Export As SVG writes `art.svgz` compressed, and `document.exportSelection` without a `format` writes the format the typed extension names (`tests/saveext.rs`). @@ -1154,12 +1191,15 @@ 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 `