diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 55d2a1983c..ccd7767934 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -33,37 +33,37 @@ "applicability": "required" }, { - "name": "gate / cache warm (ubuntu-24.04)", + "name": "gate / build (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 1/6 (ubuntu-24.04)", + "name": "gate / lint (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 2/6 (ubuntu-24.04)", + "name": "gate / test 1/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 3/6 (ubuntu-24.04)", + "name": "gate / test 2/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 4/6 (ubuntu-24.04)", + "name": "gate / test 3/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 5/6 (ubuntu-24.04)", + "name": "gate / test 4/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 6/6 (ubuntu-24.04)", + "name": "gate / test 5/5 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94e08ef762..c86dfb998a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,9 +31,9 @@ jobs: with: # Same craft-fonts commit as release.yml. craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c - # A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change) - # took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with - # those steps and the save it needs about two hours. + # A cold build of every shard's tests (the nightly run, or any run after a toolchain or + # lockfile change) took 90 minutes to reach its last three steps on 2026-11-27 and was + # canceled there; with those steps and the save it needs about two hours. timeout-minutes: 150 # The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0, # CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line @@ -43,19 +43,24 @@ jobs: dev-strip: true # The workspace crates also build without line tables. A panic still names its file and line. dev-debug: "0" - # Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run - # half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6 - # runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate ()` passes only - # when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and - # saves the dependency cache. - test-shards: 6 + # The `build ()` job builds the tests once and writes one nextest archive per shard with + # that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test + # legs download their own archive and run it without building: shards 1 and 2 each run half + # of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates + # (xtask/src/shards.rs). The `lint ()` leg runs the other `cargo xtask ci` steps beside + # them, with a dependency cache of its own. `gate ()` passes when the build and every + # test leg that ran passed; `lint ()` is a check of its own. + test-shards: 5 shard-command: cargo xtask ci shard - warm-command: cargo xtask ci warm + archive-command: cargo xtask ci archive + shard-archives: true + after-archive-command: cargo xtask ci doctests + lint-command: cargo xtask ci checks # A pull request runs only the test shards whose crates its changes reach: the crates that # own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every - # crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the - # shards left out and why; pushes to main, the nightly run and the `full-ci` label run all - # six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does. + # crate that depends on them. The `select legs` log lists the shards left out and why; pushes + # to main, the nightly run and the `full-ci` label run all five. `shard-members` names each + # shard's crates, as xtask/src/shards.rs › GROUPS does. select-tests: true shard-members: | vectorcraft-ui-egui @@ -63,14 +68,10 @@ jobs: vectorcraft-engine vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask (rest) - (always) - # The warm build runs as one `cache warm /6` leg per shard, in parallel (each builds what - # its shard builds), and `cache warm` puts their files into the one entry it saves. - warm-split: true # The dependency cache also keeps the compiled workspace crates and their library and binary - # test executables (not the integration tests' executables), so a - # pull request's shards rebuild only the crates its changes reach. Each main run's `cache - # warm` leg saves a rolling entry of its own, every leg restores the newest one, and + # test executables (not the integration tests' executables), so a pull request's build + # rebuilds only the crates its changes reach. Each main run's `build` job saves a rolling + # entry of its own, every build restores the newest one, and # cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores # nothing and builds everything from source. cache-workspace-crates: true @@ -83,15 +84,12 @@ jobs: # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes - # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). - # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run - # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a - # free runner, and with `warm-split` after every `cache warm /6` leg. The script suspends its - # start deadline while any split leg is queued or running, then allows 180 minutes from the last - # split completion for the saving leg to start. Without split legs, it allows 180 minutes from - # the script's start. A failed split leg fails this job too. The script then waits up to 160 - # minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the - # script's deadlines expire when split builds or runner waits take too long. + # the old entries when the `build` job starts saving (scripts/ci-clear-rolling-cache.py). When + # the job fails or is canceled, before its save or during it, this job fails too, so "Re-run + # failed jobs" runs it again beside the re-run build. The build starts after `gate / select legs` + # and a free runner. The script allows 180 minutes from its start for the build to start, then + # waits up to 160 minutes from the build's start. GitHub's 360-minute job limit can end this job + # before the script's deadlines expire when runner waits take too long. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' diff --git a/ASSETS.md b/ASSETS.md index a74a9a29a4..0f8647fb61 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -255,6 +255,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-item.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-new-sublayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a layer row with a new-item square nested under it | MIT OR Apache-2.0 | | | `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | | | `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-bullets.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three dots, each before a line | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index 4329ab1597..60280cad0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8716,6 +8716,7 @@ dependencies = [ name = "vectorcraft-cad" version = "0.25.1" dependencies = [ + "acadrust", "craft-dwg", "craft-dxf", "craft-image-codecs", @@ -8792,6 +8793,7 @@ dependencies = [ "thiserror 2.0.21", "tiff", "vectorcraft-color", + "vectorcraft-doc", "vectorcraft-geom 0.25.1", "zune-jpeg", ] diff --git a/Cargo.toml b/Cargo.toml index 8a8749d639..f649989a43 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,9 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "71dac2 craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "71dac21c25f4233b5ae1aeed5b8fec1c22bf2cd0" } # DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified). craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "71dac21c25f4233b5ae1aeed5b8fec1c22bf2cd0" } +# The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the +# R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not. +acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "71dac21c25f4233b5ae1aeed5b8fec1c22bf2cd0" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "71dac21c25f4233b5ae1aeed5b8fec1c22bf2cd0" } diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index ba5d3d298d..8f92ffbe44 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -140,7 +140,8 @@ mod platform { let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); // The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its // whole monitor, which it no longer does once trimmed. - let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| { + let frame = super::frame_limit(hwnd.GetDpiForWindow()); + let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work, frame).or_else(|| { super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten() }) else { return; @@ -238,21 +239,29 @@ impl Viewports { } } -/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about -/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being -/// dragged or snapped, and is left alone. -const FRAME: i32 = 32; +/// How far, in physical pixels at 96 DPI (100 %), a parked maximize reaches past a monitor or +/// work-area edge at most: the resize border is about 8 px at 100 %. Past that, a maximized +/// window's rect is not parked but being dragged or snapped, and is left alone. +const FRAME_AT_96_DPI: i32 = 32; + +/// [`FRAME_AT_96_DPI`] for a window at `dpi`, which the resize border grows with; never less than +/// at 96 DPI, so an unknown DPI (0) counts as 100 %. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +fn frame_limit(dpi: u32) -> i32 { + let scaled = i64::from(FRAME_AT_96_DPI) * i64::from(dpi) / 96; + i32::try_from(scaled).unwrap_or(i32::MAX).max(FRAME_AT_96_DPI) +} /// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize /// border it was parked with, or `None` when it already does or `rect` (`left, top, right, /// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's -/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The -/// border is read from the edges that have no taskbar, and every edge must sit that far outside -/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the -/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested -/// everywhere. +/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates; +/// `frame` is the largest border a parked maximize has ([`frame_limit`]). The border is read from +/// the edges that have no taskbar, and every edge must sit that far outside either the monitor +/// (where Windows puts a caption-less maximize) or the work area (where the guard puts it), so a +/// rect it already moved is left alone. Platform-neutral so it is tested everywhere. #[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] -fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { +fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32), frame: i32) -> Option<(i32, i32, i32, i32)> { let (l, t, r, b) = rect; let (ml, mt, mr, mb) = monitor; let (wl, wt, wr, wb) = work; @@ -269,7 +278,7 @@ fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: ] .into_iter() .flatten() - .filter(|n| (0..=FRAME).contains(n)) + .filter(|n| (0..=frame).contains(n)) .min()?; let parked = |monitor: Option, work: Option| monitor == Some(border) || work == Some(border); if !parked(ml.checked_sub(l), wl.checked_sub(l)) @@ -304,9 +313,11 @@ fn covers(rect: Rect, monitor: Rect) -> bool { } /// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the -/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden -/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie -/// outside the monitor. +/// taskbar's center, or `None` when the taskbar is not this monitor's. A shown taskbar lies wholly +/// on its monitor. An auto-hidden taskbar is parked mostly past its edge with a sliver left on the +/// monitor, so its center can lie outside the monitor; the part past the edge can lie on a +/// neighboring monitor, which a taskbar that is neither wholly on the monitor nor mostly off it +/// belongs to. #[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); @@ -314,6 +325,12 @@ fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { return None; } + let inside = tl >= ml && tt >= mt && tr <= mr && tb <= mb; + let area = |l: i64, t: i64, r: i64, b: i64| i128::from(r - l) * i128::from(b - t); + let on_monitor = area(tl.max(ml), tt.max(mt), tr.min(mr), tb.min(mb)); + if !inside && on_monitor * 2 >= area(tl, tt, tr, tb) { + return None; + } // The center and the distances are doubled, so nothing is rounded. let (cx, cy) = (tl + tr, tt + tb); [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] @@ -346,7 +363,12 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: & #[cfg(test)] mod tests { - use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + use super::{Edge, Viewports, frame_limit, short_of_autohide_taskbars, taskbar_edge}; + + /// [`super::clamped_rect`] for a window at 96 DPI (100 %). + fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { + super::clamped_rect(rect, monitor, work, frame_limit(96)) + } fn viewport(name: &str) -> egui::ViewportId { egui::ViewportId::from_hash_of(name) @@ -453,6 +475,22 @@ mod tests { } } + #[test] + fn the_frame_limit_grows_with_the_monitor_dpi() { + // At 500 % (480 DPI) the resize border is about 40 px, past the limit at 100 %. + let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000)); + let rect = (-40, -40, 3880, 2200); + assert_eq!(clamped_rect(rect, monitor, work), None, "100 %"); + let Some(clamped) = super::clamped_rect(rect, monitor, work, frame_limit(480)) else { + panic!("500 %: the maximized frame is not clamped"); + }; + assert_eq!((clamped.0, clamped.1, clamped.2), (rect.0, rect.1, rect.2), "500 %: only the bottom edge moves"); + assert_eq!(clamped.3 - work.3, monitor.1 - rect.1, "500 %: the bottom border hangs below the work area as the top one above the monitor"); + assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit"); + assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %"); + assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow"); + } + #[test] fn a_maximize_without_a_reserved_taskbar_is_left_alone() { let monitor = (0, 0, 1920, 1080); @@ -503,6 +541,12 @@ mod tests { assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + // With monitors stacked, the part of the upper monitor's auto-hidden taskbar parked past its + // bottom edge lies on the monitor below, which it does not belong to. + let below = (0, 1080, 1920, 2160); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), below), None, "neighbor's auto-hidden taskbar"); + assert_eq!(taskbar_edge((0, 2158, 1920, 2206), below), Some(Edge::Bottom), "its own auto-hidden taskbar"); + assert_eq!(taskbar_edge((0, 1080, 1920, 1128), below), Some(Edge::Top), "its own shown top taskbar"); assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); } } diff --git a/assets/icons/dc-new-sublayer.svg b/assets/icons/dc-new-sublayer.svg new file mode 100644 index 0000000000..0efcbf48c0 --- /dev/null +++ b/assets/icons/dc-new-sublayer.svg @@ -0,0 +1 @@ + diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index c09eb31879..005988ef18 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -29,3 +29,7 @@ serde_json = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine) # and in fonts built in code (`vectorcraft_text::test_fonts`). vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] } + +# Writes the R12, R13 and R14 DWG files the import tests read. Left out where craft-dwg leaves it out. +[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies] +acadrust = { workspace = true } diff --git a/crates/cad/src/dwg.rs b/crates/cad/src/dwg.rs index c49beecb99..4b9cf7f902 100644 --- a/crates/cad/src/dwg.rs +++ b/crates/cad/src/dwg.rs @@ -1,9 +1,11 @@ //! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result. +//! Export writes a DWG the other way: the DXF writer's drawing, converted by `craft_dwg` ([`from_dxf`]). //! -//! The conversion runs in a child process once the program has called [`use_own_worker`] (and +//! Each conversion runs in a child process once the program has called [`use_own_worker`] (and //! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort //! ends that process, not VectorCraft. Without a worker the conversion is refused, unless -//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there. +//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read or written +//! there. use std::hash::BuildHasher; use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak}; @@ -11,7 +13,7 @@ use std::time::Duration; use web_time::Instant; -pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker}; +pub use craft_dwg::{Unwritten, WORKER_ARG, allow_in_process, use_own_worker}; /// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder. pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))); @@ -62,9 +64,72 @@ pub fn use_own_worker_for(limit: std::time::Duration) { /// The largest DXF rendition kept for the next read of the same drawing (128 MiB). const MAX_KEPT: usize = 128 << 20; -/// Is `bytes` a DWG drawing (an `AC10nn` version code first)? +/// Is `bytes` a DWG drawing (an `AC10nn` or `AD10nn` version code first)? pub fn is_dwg(bytes: &[u8]) -> bool { - craft_dwg::is_dwg(bytes) + craft_dwg::is_dwg(bytes) || craft_dwg::is_dwg(&ac_code(bytes)) +} + +/// The first six bytes of `bytes`, with an `AD10` start read as `AC10`. +fn ac_code(bytes: &[u8]) -> Vec { + let mut head = bytes.get(..bytes.len().min(7)).unwrap_or(bytes).to_vec(); + if head.starts_with(b"AD10") { + head[1] = b'C'; + } + head +} + +/// The version codes of DWG drawings and the name of each version, oldest first +/// (). +const VERSIONS: [(&str, &str); 21] = [ + ("MC0.0", "R1.0"), + ("AC1.2", "R1.2"), + ("AC1.40", "R1.40"), + ("AC1.50", "R2.05"), + ("AC2.10", "R2.10"), + ("AC2.21", "R2.21"), + ("AC2.22", "R2.22"), + ("AC1001", "R2.22"), + ("AC1002", "R2.50"), + ("AC1003", "R2.60"), + ("AC1004", "R9"), + ("AC1006", "R10"), + ("AC1009", "R11/12"), + ("AC1012", "R13"), + ("AC1014", "R14"), + ("AC1015", "2000"), + ("AC1018", "2004"), + ("AC1021", "2007"), + ("AC1024", "2010"), + ("AC1027", "2013"), + ("AC1032", "2018"), +]; + +/// The version codes the DWG reader reads, each also with `AD` in place of `AC` except `AC1006`. +const READS: [&str; 10] = ["AC1006", "AC1009", "AC1012", "AC1014", "AC1015", "AC1018", "AC1021", "AC1024", "AC1027", "AC1032"]; + +/// Why `bytes` can't be read when they start with a DWG version code that the DWG reader does +/// not read: the message names the version and says to save the drawing as DXF or as a DWG +/// version that is read. `None` for any other bytes, a DWG drawing of a version that is read +/// included. +pub fn unreadable(bytes: &[u8]) -> Option { + let head = ac_code(bytes); + let numbered = head.starts_with(b"AC10"); + if !numbered && ![&b"MC0."[..], b"AC1.", b"AC2."].iter().any(|m| head.starts_with(m)) { + return None; + } + if numbered && READS.iter().any(|c| head.starts_with(c.as_bytes())) && !bytes.starts_with(b"AD1006") { + return None; + } + let named = match VERSIONS.iter().find(|(c, _)| head.starts_with(c.as_bytes())) { + Some((code, name)) => format!("DWG {name} ({})", if bytes.starts_with(b"AD") { code.replacen("AC", "AD", 1) } else { code.to_string() }), + None => { + let shown: String = bytes.iter().take(6).take_while(|b| b.is_ascii_graphic()).map(|&b| char::from(b)).collect(); + format!("DWG version {shown}") + } + }; + Some(format!( + "this drawing is {named}, a DWG version VectorCraft can't read: save it from the CAD app as a DXF, or as a DWG from R10 to 2018, and open that" + )) } /// A DWG drawing as DXF bytes, and what the conversion left out. @@ -173,11 +238,55 @@ pub fn hold(bytes: &[u8]) -> Result { } fn convert(bytes: &[u8]) -> Result { + if let Some(why) = unreadable(bytes) { + return Err(why); + } let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?; Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() }) } -/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one. +/// Can a DWG file of `version` be written? craft-dwg writes 2000, 2004, 2007, 2010, 2013 and 2018. +pub fn writes(version: crate::DxfVersion) -> bool { + craft_dwg::VERSIONS.iter().any(|(code, _)| *code == version.acadver()) +} + +/// A DWG file of `version` from `dxf`, an ASCII DXF of that version as [`crate::export_drawings`] +/// writes it, and what the DWG writer left out: how many records of each DXF type. The conversion +/// runs in the worker, as reading does. +/// +/// # Errors +/// +/// When `version` is one a DWG can't be written as, or the conversion fails. +pub fn from_dxf(dxf: &[u8], version: crate::DxfVersion) -> Result<(Vec, craft_dwg::Unwritten), String> { + if !writes(version) { + return Err(format!("DWG version `{}` can't be written: use {}", version.id(), written_versions())); + } + craft_dwg::encode_noted(dxf, version.acadver()) +} + +/// The versions a DWG can be written as, as the `version` param names them ("2000, 2004 … or 2018"). +pub fn written_versions() -> String { + let ids: Vec<&str> = crate::DxfVersion::ALL.iter().rev().filter(|v| writes(**v)).map(|v| v.id()).collect(); + match ids.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")), + Some((last, _)) => (*last).to_string(), + None => String::new(), + } +} + +/// The warning for what the DWG writer left out of `files` files, by DXF type, else none. +pub fn left_out_warning(left_out: &craft_dwg::Unwritten, files: usize) -> Option { + let total: usize = left_out.values().sum(); + if total == 0 { + return None; + } + let kinds: Vec = left_out.iter().map(|(kind, n)| format!("{kind} × {n}")).collect(); + let of = if files > 1 { format!("these {files} drawings") } else { "this drawing".to_string() }; + let records = if total == 1 { "record" } else { "records" }; + Some(format!("DWG: {total} {records} of {of} can't be written in this DWG version and were left out ({})", kinds.join(", "))) +} + +/// craft-dwg's message or note on reading a DWG, in VectorCraft's words. fn worded(message: &str) -> String { message .replace("accepted by this bridge", "VectorCraft opens") @@ -278,4 +387,68 @@ mod tests { let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them"); assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)"); } + + #[test] + fn a_version_before_2000_is_refused_before_converting() { + // No worker is configured here, so a conversion that ran would fail for that reason instead. + let e = from_dxf(b" 0\nEOF\n", crate::DxfVersion::R14).unwrap_err(); + assert!(e.starts_with("DWG version `R14` can't be written: use 2000,") && e.ends_with("or 2018"), "{e}"); + assert!(writes(crate::DxfVersion::R2000) && !writes(crate::DxfVersion::R13) && !writes(crate::DxfVersion::R12)); + } + + #[test] + fn records_the_dwg_writer_left_out_are_counted_by_type() { + assert_eq!(left_out_warning(&craft_dwg::Unwritten::new(), 1), None); + let one: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 1)].into_iter().collect(); + let w = left_out_warning(&one, 1).unwrap(); + assert!(w.contains("1 record of this drawing") && w.contains("ACME_WIDGET × 1"), "{w}"); + let some: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 2), ("ACME_OBJECT".to_string(), 1)].into_iter().collect(); + let w = left_out_warning(&some, 3).unwrap(); + assert!(w.contains("3 records of these 3 drawings") && w.contains("ACME_OBJECT × 1, ACME_WIDGET × 2"), "{w}"); + } + + #[test] + fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() { + let named = [ + (&b"AC1001\x00\x00\x00\x00"[..], "DWG R2.22 (AC1001)"), + (b"AD1006\x00\x00\x00\x00", "DWG R10 (AD1006)"), + (b"AD1004\x00\x00\x00\x00", "DWG R9 (AD1004)"), + (b"AC1.50\x00\x00\x00\x00", "DWG R2.05 (AC1.50)"), + (b"AC1.2\x00\x00\x00\x00", "DWG R1.2 (AC1.2)"), + (b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"), + (b"AC1033\x00\x00\x00\x00", "DWG version AC1033"), + (b"AC1010\x00\x00\x00\x00", "DWG version AC1010"), + (b"AC10\x00\x00\x00\x00", "DWG version AC10"), + ]; + for (bytes, name) in named { + let why = unreadable(bytes).unwrap_or_default(); + assert!(why.starts_with(&format!("this drawing is {name},")), "{name}: {why}"); + assert!(why.contains("as a DXF, or as a DWG from R10 to 2018"), "{why}"); + } + for read in [ + &b"AC1006\x00\x00"[..], + b"AC1009\x00\x00", + b"AD1009\x00\x00", + b"AC1018\x00\x00", + b"AC1032\x00\x00", + b"AD1015\x00\x00", + b"0\nSECTION\n", + b"AC", + b"", + ] { + assert_eq!(unreadable(read), None, "{:?}", String::from_utf8_lossy(read)); + } + } + + #[test] + fn an_ad_version_code_is_a_dwg_drawing() { + assert!(is_dwg(b"AD1018\x00\x00") && is_dwg(b"AC1018\x00\x00")); + assert!(!is_dwg(b"AD10\x00\x00\x00") && !is_dwg(b"AD1018") && !is_dwg(b"0\nSECTION\n")); + } + + #[test] + fn a_dwg_version_the_reader_skips_is_refused_before_converting() { + let e = hold(b"AC1004\x00\x00\x00\x00").unwrap_err(); + assert!(e.starts_with("this drawing is DWG R9 (AC1004),"), "{e}"); + } } diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index bed5bef361..f4c4cf99c8 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -5,9 +5,11 @@ //! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred //! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art //! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on -//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid -//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols -//! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), +//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and +//! gradient hatches, pattern hatches' lines, solids and regions become paths; text and multiline +//! text point type; named blocks symbols +//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the +//! files they name, clipped by their clip boundaries. Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. //! @@ -15,6 +17,7 @@ //! blocks and layouts. //! - `entity`: entities to items (geometry and properties). //! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths. +//! - `hatch`: pattern hatches' lines and gradient hatches' fills. //! - `text`: text values to plain text. //! - `acis`: a region's solid-modeler data as its outline. //! - `build`: items to the document. @@ -23,6 +26,7 @@ mod acis; mod build; mod curve; mod entity; +mod hatch; mod reader; mod text; @@ -74,7 +78,8 @@ pub struct Imported { /// What a drawing holds, for the import options. #[derive(Clone, Debug, PartialEq)] pub struct DxfInfo { - /// The DXF version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones). + /// The drawing's version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones). A DWG + /// file's is the DWG's own, not that of the DXF it converts to. pub version: String, /// The drawing unit's name (`Millimeters`, `Unitless`…). pub units: String, @@ -108,15 +113,18 @@ pub fn is_dxf(bytes: &[u8]) -> bool { /// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read /// left out: where the file is damaged, and what the DWG conversion couldn't read. fn tags(bytes: &[u8]) -> Result<(Vec, Vec), String> { + if let Some(why) = crate::dwg::unreadable(bytes) { + return Err(why); + } if crate::dwg::is_dwg(bytes) { let converted = crate::dwg::to_dxf(bytes)?; let (tags, mut notes) = dxf_tags(&converted.dxf)?; notes.extend(converted.notes.iter().cloned()); return Ok((tags, notes)); } - // R1.x and R2.x drawings (MC0.0, AC1.2 to AC2.10), and an AC10 header with no version number. - if [&b"AC10"[..], b"AC1.", b"AC2.", b"MC0."].iter().any(|magic| bytes.starts_with(magic)) { - return Err("this DWG drawing's version can't be read: save it from the CAD app as a DXF and open that".into()); + // A DWG version code with nothing after it. + if [&b"AC10"[..], b"AD10"].iter().any(|magic| bytes.starts_with(magic)) { + return Err("DWG: the file is cut short".into()); } dxf_tags(bytes) } @@ -187,7 +195,9 @@ pub fn info(bytes: &[u8]) -> Result { } let h = &d.header; let (unit, scale) = default_ratio(h); - let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == h.acadver).map_or_else(|| h.acadver.clone(), |v| v.id().to_string()); + // A DWG's own version: the DXF it converts to can be newer (an R12 DWG converts to an R13 DXF). + let acadver = craft_dwg::version(bytes).unwrap_or_else(|| h.acadver.clone()); + let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == acadver).map_or(acadver, |v| v.id().to_string()); Ok(DxfInfo { version, units: units_name(h.insunits).into(), @@ -240,4 +250,6 @@ mod tests; #[cfg(test)] mod tests_dwg; #[cfg(test)] +mod tests_image; +#[cfg(test)] mod tests_region; diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 0b3532ca87..98f28f6ebc 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -7,13 +7,17 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; -use kurbo::BezPath; -use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; +use kurbo::{BezPath, PathEl}; +use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind, + Symbol, TextObject, +}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; use super::ImportOptions; -use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem}; +use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Shade, Span, TextItem}; +use super::hatch::{Grad, Second}; use super::reader::{Drawing, LayoutDef}; use crate::{CAP_HEIGHT, MAX_NEST}; @@ -22,7 +26,7 @@ const PT_PER_MM: f64 = 72.0 / 25.4; /// The stroke weight of lineweight 0 (CAD apps draw it one device pixel wide), in points. const THINNEST: f64 = 0.25; /// The most objects an import makes. -const MAX_NODES: usize = 2_000_000; +const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 }; /// The most block work an import does, whatever it produces: one per insert copy drawn, and one /// per item of the block looked at for it (art on hidden layers too). const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; @@ -38,6 +42,9 @@ const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 }; const MAX_FAMILY_BYTES: usize = 256; /// How far from the origin art may lie (points): the canvas. pub(crate) const MAX_EXTENT: f64 = 4.0e6; +/// How far from a symbol's origin its image clip points may lie (points): as far as an insert at +/// the smallest scale it accepts (1e-12) still brings back onto the canvas. +const MAX_SYMBOL_EXTENT: f64 = MAX_EXTENT * 1e12; const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out"; const XREFS: &str = "blocks referencing other drawings (external references) are left out"; @@ -46,6 +53,27 @@ const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out"; const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; +const NO_IMAGE_FILE: &str = "images that name no image file are left out"; +const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out"; +const IMAGE_SIZE: &str = "images with no size in pixels, or more than 1,048,576 pixels a side, are left out"; +/// The most pixels an image may have a side. +const MAX_IMAGE_SIDE: f64 = 1_048_576.0; +/// The key of the image data of the images showing the file at a path: the placeholder, until +/// the file is read. +const IMAGE_KEY: &str = "dxf-image-"; + +/// How a path paints. +#[derive(Clone, Copy)] +enum Look<'g> { + /// Stroked at its width or lineweight, in its linetype. + Line, + /// Filled with its color. + Fill, + /// Filled with a gradient hatch's gradient. + Gradient(&'g Grad), + /// Pattern hatch lines: stroked without the linetype; `dots` take round caps. + Pattern { dots: bool }, +} /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -58,6 +86,35 @@ struct Inherit { layer: Option, } +/// Objects, path elements, dash lengths and text bytes taken from the import's limits. +#[derive(Clone, Copy, Debug, Default)] +struct Cost { + nodes: usize, + elements: usize, + dash_values: usize, + text_bytes: usize, +} + +impl Cost { + fn minus(self, o: Cost) -> Cost { + Cost { + nodes: self.nodes.saturating_sub(o.nodes), + elements: self.elements.saturating_sub(o.elements), + dash_values: self.dash_values.saturating_sub(o.dash_values), + text_bytes: self.text_bytes.saturating_sub(o.text_bytes), + } + } + + fn plus(self, o: Cost) -> Cost { + Cost { + nodes: self.nodes.saturating_add(o.nodes), + elements: self.elements.saturating_add(o.elements), + dash_values: self.dash_values.saturating_add(o.dash_values), + text_bytes: self.text_bytes.saturating_add(o.text_bytes), + } + } +} + pub(crate) struct Build<'d, 'a> { d: &'d Drawing<'a>, o: &'d ImportOptions, @@ -74,6 +131,21 @@ pub(crate) struct Build<'d, 'a> { next_suffix: HashMap, /// Blocks being drawn, outermost first. stack: Vec, + /// How many symbols' art is being drawn: above 0, art is in a symbol's own space. + in_symbol: u32, + /// The box of the image clip points in the symbol being drawn, in its own space, and of each + /// symbol made (none: its art has no clips). + clip_reach: Option, + symbol_reach: HashMap, + /// What each symbol's own art took from the limits (not the symbols made while drawing it), + /// how many instances place each symbol, and what the symbols made inside the one being + /// drawn took. + symbol_cost: HashMap, + uses: HashMap, + nested: Cost, + /// Each symbol's place in the document's symbols, and the symbols whose art was taken out. + symbol_slot: HashMap, + empty: HashSet, /// Document space per drawing unit, and its symbols' (no translation). map: Affine, symbol_map: Affine, @@ -137,6 +209,14 @@ impl<'d, 'a> Build<'d, 'a> { symbol_names: HashSet::new(), next_suffix: HashMap::new(), stack: vec![], + in_symbol: 0, + clip_reach: None, + symbol_reach: HashMap::new(), + symbol_cost: HashMap::new(), + uses: HashMap::new(), + symbol_slot: HashMap::new(), + empty: HashSet::new(), + nested: Cost::default(), map: Affine::IDENTITY, symbol_map: Affine::IDENTITY, lw_scale: 1.0, @@ -169,6 +249,72 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// What the import has taken from its limits so far. + fn cost(&self) -> Cost { + Cost { nodes: self.nodes, elements: self.elements, dash_values: self.dash_values, text_bytes: self.text_bytes } + } + + fn set_cost(&mut self, c: Cost) { + self.nodes = c.nodes; + self.elements = c.elements; + self.dash_values = c.dash_values; + self.text_bytes = c.text_bytes; + } + + /// Take symbol `name`'s art out when no instance places it, giving back its share of the limits + /// and its art's instances of other symbols (and in turn those that no instance places any + /// more); the art, when it was taken. The symbol stays empty until [`Self::restore`] puts the + /// art back or [`Self::symbol`] draws it again, and is dropped at the end if still empty. + fn take_unused(&mut self, name: &str) -> Option> { + let first = self.take_art(name)?; + // A worklist, not recursion: chains of symbols can be long. + let mut todo = placed_symbols(&first); + while let Some(s) = todo.pop() { + if let Some(n) = self.uses.get_mut(&s) { + *n = n.saturating_sub(1); + } + if let Some(art) = self.take_art(&s) { + todo.extend(placed_symbols(&art)); + } + } + Some(first) + } + + /// Symbol `name`'s art, taken out with its share of the limits when no instance places it. + fn take_art(&mut self, name: &str) -> Option> { + if self.uses.get(name).is_some_and(|n| *n > 0) || self.empty.contains(name) { + return None; + } + let i = *self.symbol_slot.get(name)?; + let id = self.doc.alloc_id(); + let art = std::mem::replace(&mut self.doc.symbols.get_mut(i)?.art, Arc::new(Node::group(id, vec![]))); + self.set_cost(self.cost().minus(self.symbol_cost.get(name).copied().unwrap_or_default())); + self.empty.insert(name.to_string()); + Some(art) + } + + /// Put `art`, taken from symbol `name` by [`Self::take_unused`], back, charging its share of + /// the limits again; false (nothing changed) when that share no longer fits. + fn restore(&mut self, name: &str, art: Arc) -> bool { + let t = self.cost().plus(self.symbol_cost.get(name).copied().unwrap_or_default()); + let inner = placed_symbols(&art); + // Its instances of symbols that are empty now need those drawn again. + let fits = t.nodes < MAX_NODES && t.elements <= MAX_ELEMENTS && t.dash_values <= MAX_DASH_VALUES && t.text_bytes <= MAX_TEXT_BYTES; + if !fits || inner.iter().any(|s| self.empty.contains(s)) { + return false; + } + let Some(slot) = self.symbol_slot.get(name).and_then(|i| self.doc.symbols.get_mut(*i)) else { + return false; + }; + slot.art = art; + self.set_cost(t); + self.empty.remove(name); + for s in inner { + *self.uses.entry(s).or_default() += 1; + } + true + } + /// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own /// unit and at the scale asked for (fitting computes its own). pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec), String> { @@ -183,6 +329,7 @@ impl<'d, 'a> Build<'d, 'a> { if !layers.is_empty() { doc.layers = layers; } + drop_unplaced_symbols(&mut doc); if let Some(a) = doc.artboards.first_mut() { a.rect = Rect::from_origin_size(Point::ZERO, size); } @@ -291,7 +438,7 @@ impl<'d, 'a> Build<'d, 'a> { /// An item's bounds in world coordinates (type: an estimate from its height and length). fn item_bounds(&mut self, it: &Item, depth: u32) -> Option { match &it.geom { - Geom::Path { bp, .. } => super::curve::bounds(bp), + Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp), Geom::Text(t) => { let lines = t.text.lines().count().max(1) as f64; let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64; @@ -314,6 +461,14 @@ impl<'d, 'a> Build<'d, 'a> { let attribs: Vec> = ins.attribs.iter().map(|a| self.item_bounds(a, depth)).collect(); cells.map(Some).chain(attribs).fold(None, vectorcraft_geom::union_opt) } + Geom::Image(im) => { + self.image_file(im)?; + let (w, h) = self.image_size(im)?; + let place = im.placement(h); + let whole = place.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)); + let clip = im.clip.as_ref().and_then(|c| c.iter().map(|p| place * *p).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b))); + Some(clip.map_or(whole, |c| c.intersect(whole))) + } } .filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) } @@ -331,8 +486,17 @@ impl<'d, 'a> Build<'d, 'a> { for it in items.iter() { let p = &it.props; let on_zero = p.layer == "0"; - s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock; - s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER"); + // Fills draw no stroke, and pattern lines carry their own dashes. + let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. }); + let stroked = !filled; + let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. }); + s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock; + s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK"); + s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER")); + if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom { + let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer); + s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c)); + } if let Geom::Insert(ins) = &it.geom { s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1); } @@ -391,6 +555,23 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be. + fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint { + let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh); + let first = rgb(g.first); + let second = match g.second { + Second::Col(c) => rgb(c), + Second::Tint(t) => Grad::tinted(first, t), + }; + let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect(); + let mut geom = g.geom; + geom.transform(map, g.kind); + let mut paint = GradientPaint::new(Gradient::new(g.kind, stops)); + paint.angle = geom.angle_deg(); + paint.geom = Some(geom); + Paint::Gradient(Box::new(paint)) + } + /// What a block placed by an insert with `p` inherits. fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit { Inherit { @@ -479,16 +660,75 @@ impl<'d, 'a> Build<'d, 'a> { return None; } let mut node = match &it.geom { - Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?, + Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?, + Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?, Geom::Text(t) => self.text(t, &it.props, map, inh)?, Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth), + Geom::Image(im) => self.image(im, map)?, }; node.opacity = self.opacity(&it.props, inh); self.nodes += 1; Some(node) } - fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option { + /// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no + /// length go on a path of their own with round caps, grouped with the dashes, which keep + /// butt caps and their lengths. + fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option { + if !dots { + return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + let (mut dashes, mut points) = (BezPath::new(), BezPath::new()); + let (mut dash_count, mut dot_count) = (0usize, 0usize); + let mut from = None; + for el in bp.elements() { + match *el { + PathEl::MoveTo(a) => from = Some(a), + PathEl::LineTo(b) => { + if let Some(a) = from { + let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) }; + out.move_to(a); + out.line_to(b); + *count += 1; + } + } + _ => {} + } + } + if dashes.elements().is_empty() { + return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh); + } + if points.elements().is_empty() { + return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); + } + // Every object the split makes: the group (`item` counts it), the two paths, and each + // piece of a path with more than one (`path` counts those). + let loops = |count: usize| if count > 1 { count } else { 0 }; + if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) { + self.warn(TOO_MANY); + return None; + } + if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) { + self.warn(TOO_MANY_POINTS); + return None; + } + // A split that loses either path is left out whole, and charges nothing. + let (nodes, elements) = (self.nodes, self.elements); + let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh); + let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh)); + let (Some(lines), Some(dots)) = (lines, dots) else { + (self.nodes, self.elements) = (nodes, elements); + return None; + }; + self.nodes += 2; + Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)])) + } + + /// A path painted as `look` says; `width`: a line's width in drawing units (0: the + /// lineweight). + fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option { + let fill = matches!(look, Look::Fill | Look::Gradient(_)); let n = bp.elements().len(); if self.elements.saturating_add(n) > MAX_ELEMENTS { self.warn(TOO_MANY_POINTS); @@ -498,7 +738,14 @@ impl<'d, 'a> Build<'d, 'a> { let mut bp = bp.clone(); bp.apply_affine(map); super::curve::bounds(&bp)?; - let paint = Paint::solid(rgb_color(self.rgb(p, inh))); + let paint = match look { + Look::Gradient(g) => self.gradient(g, p, map, inh), + _ => Paint::solid(rgb_color(self.rgb(p, inh))), + }; + let pattern = match look { + Look::Pattern { dots } => Some(dots), + _ => None, + }; let scale = map.determinant().abs().sqrt(); let path = PathData::from_bezpath(&bp); // A compound path's loops each keep a copy of its appearance, beside its own. @@ -515,7 +762,14 @@ impl<'d, 'a> Build<'d, 'a> { f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale }; let mut ap = Appearance::basic(Paint::None, paint, w); - if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() + // Pattern lines carry their own dashes; dots of no length show with round caps. + if let Some(dots) = pattern { + if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() + && dots + { + s.cap = LineCap::Round; + } + } else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut() && let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale) { match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) { @@ -590,6 +844,92 @@ impl<'d, 'a> Build<'d, 'a> { Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj)))) } + /// The non-empty, trimmed file path that image `im`'s IMAGEDEF names. + fn image_file(&self, im: &ImageItem) -> Option { + im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty()) + } + + /// The size in pixels of image `im`: its own, else its file's as its IMAGEDEF gives it. + fn image_size(&self, im: &ImageItem) -> Option<(f64, f64)> { + let def = im.def.and_then(|h| self.d.images.get(&h)).map_or([0.0; 2], |f| f.size); + let size = if im.size.iter().all(|v| *v >= 1.0) { im.size } else { def }; + let [w, h] = size.map(f64::round); + [w, h].iter().all(|v| (1.0..=MAX_IMAGE_SIDE).contains(v)).then_some((w, h)) + } + + /// A raster image, linked to the file its IMAGEDEF names (the path as the drawing stores it, + /// found from the drawing's folder when the document opens): until the file is read it shows + /// a placeholder over its pixels. A clip boundary makes it a clip group. + fn image(&mut self, im: &ImageItem, map: Affine) -> Option { + let Some(path) = self.image_file(im) else { + self.warn(NO_IMAGE_FILE); + return None; + }; + let Some((w, h)) = self.image_size(im) else { + self.warn(IMAGE_SIZE); + return None; + }; + let xf = map * im.placement(h); + if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) { + return None; + } + // The clip boundary, unless it shows the whole image. Its path and the image are objects of + // their own (`item` counts the group), and its points and the close are path elements: both + // are checked against the limits before the points are read. + let clip = im.clip.as_ref().filter(|c| !covers(c, w, h)); + let elements = clip.map_or(0, |c| c.len().saturating_add(1)); + if clip.is_some() && self.nodes.saturating_add(2) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + if self.elements.saturating_add(elements) > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + return None; + } + // In document space, or in a symbol's own space, where each instance places it. + let clip: Option> = clip.map(|c| c.iter().map(|p| xf * *p).collect()); + let local = self.in_symbol > 0; + let limit = if local { MAX_SYMBOL_EXTENT } else { MAX_EXTENT }; + let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= limit && p.y.abs() <= limit; + if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) { + self.warn(FAR_CLIPS); + return None; + } + // Each image keeps its own copy of the path. + if !self.charge_text(path.len()) { + return None; + } + let key = format!("{IMAGE_KEY}{}", vectorcraft_doc::links::hash_bytes(path.as_bytes())); + if !self.doc.images.contains_key(&key) { + let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder()?); + let blob = ImageBlob { + mime: vectorcraft_doc::links::PROXY_MIME.into(), + bytes: bytes.clone(), + proxy: Some(bytes), + file_font: Default::default(), + }; + self.doc.images.insert(key.clone(), blob); + } + let (w_px, h_px) = (w as u32, h as u32); + let image = ImageObject { key, width: w_px, height: h_px, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }; + let image = Node::new(self.doc.alloc_id(), NodeKind::Image(Box::new(image))); + let Some(clip) = clip else { return Some(image) }; + // A symbol's clips are checked where each of its instances places them. + if local && let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) { + self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); + } + self.nodes += 2; + self.elements += elements; + let mut bp = BezPath::new(); + for (i, p) in clip.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + bp.close_path(); + let path = PathData::from_bezpath(&bp); + let clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false }); + Some(Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })) + } + /// An insert: a symbol instance per copy (anonymous blocks: a group of their art), grouped /// with its attributes. fn insert(&mut self, ins: &InsertItem, p: &Props, map: Affine, inh: &Inherit, depth: u32) -> Option { @@ -597,11 +937,53 @@ impl<'d, 'a> Build<'d, 'a> { let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base); let unbase = Affine::translate(-base.to_vec2()); let anonymous = ins.block.starts_with('*'); - let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth) }; + // An empty symbol is drawn again only for a cell that places an instance of it. + let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) }; + // The symbol's art when this insert took it out. + let mut taken = None; let mut parts = vec![]; for cell in &ins.cells { let node = match &symbol { Some(name) => { + let xf = map * *cell * self.symbol_map.inverse(); + // Its image clips where this instance places them: inside another symbol, their + // box joins that symbol's; else, when it may leave the canvas, this placement + // draws the block's art, which checks each clip where it lands. + let reach_of = |b: &Self| b.symbol_reach.get(name).map(|r| placed_reach(xf, *r)); + let leaves = + |r: Option| r.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT)); + let mut reach = reach_of(self); + // An empty symbol is drawn again (or its taken art put back) unless this placement + // draws the art anyway; the art drawn again may reach further. + if self.empty.contains(name) && (self.in_symbol > 0 || !leaves(reach)) { + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + let back = taken.take().is_some_and(|art| self.restore(name, art)); + if !back && self.symbol(&ins.block, &child, depth, true).is_none() { + continue; + } + reach = reach_of(self); + } + // Joins the enclosing symbol's box once the instance is kept. + let inside = reach.filter(|_| self.in_symbol > 0); + if inside.is_none() && leaves(reach) { + // This placement draws the art instead of the symbol. The art of a symbol + // no instance places yet is taken out, so that it isn't kept and charged + // as well; an instance in a later cell puts it back. + if taken.is_none() { + taken = self.take_unused(name); + } + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth)); + continue; + } + // Checked here, after the art drawn in its place: that art gets back the + // share of an unused symbol. if self.nodes >= MAX_NODES { self.warn(TOO_MANY); break; @@ -609,7 +991,10 @@ impl<'d, 'a> Build<'d, 'a> { if !self.charge_text(name.len()) { break; } - let xf = map * *cell * self.symbol_map.inverse(); + if let Some(b) = inside { + self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); + } + *self.uses.entry(name.clone()).or_default() += 1; self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) } @@ -664,30 +1049,124 @@ impl<'d, 'a> Build<'d, 'a> { } } - /// The symbol for block `name` placed with `inh` (made once per look). - fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32) -> Option { + /// The symbol for block `name` placed with `inh` (made once per look). One whose art was + /// taken out is drawn again when `draw` is set, and else returned empty. + fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option { let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() }; let key = (name.to_string(), inh); if let Some(s) = self.symbols.get(&key) { - return s.clone(); - } - let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); - let map = self.symbol_map * Affine::translate(-base.to_vec2()); - let art = self.art(name, map, &key.1, depth); - let made = art.and_then(|art| { - let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); - // The symbol keeps its name: text, as its instances' copies of it are. - if !self.charge_text(label.len()) { - return None; + let s = s.clone()?; + if !draw || !self.empty.contains(&s) { + return Some(s); } + let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i)); + return match (art, slot) { + (Some(art), Some(slot)) => { + slot.art = Arc::new(art); + self.symbol_cost.insert(s.clone(), cost); + match reach { + Some(b) => self.symbol_reach.insert(s.clone(), b), + None => self.symbol_reach.remove(&s), + }; + self.empty.remove(&s); + Some(s) + } + // Nothing of it fits now: what it took goes back, and it stays empty. + _ => { + self.set_cost(self.cost().minus(cost)); + self.nested = self.nested.minus(cost); + None + } + }; + } + let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let made = art.map(|art| { + let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); + if let Some(b) = reach { + self.symbol_reach.insert(symbol.clone(), b); + } + self.symbol_slot.insert(symbol.clone(), self.doc.symbols.len()); + self.symbol_cost.insert(symbol.clone(), cost); self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); - Some(symbol) + symbol }); self.symbols.insert(key, made.clone()); made } + + /// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and + /// what it took from the limits itself (not the symbols made while drawing it, which other + /// instances may use). + fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option, Option, Cost) { + let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); + let map = self.symbol_map * Affine::translate(-base.to_vec2()); + let outer = self.clip_reach.take(); + let before = self.cost(); + let outer_nested = std::mem::take(&mut self.nested); + self.in_symbol += 1; + let art = self.art(name, map, inh, depth); + self.in_symbol -= 1; + let reach = std::mem::replace(&mut self.clip_reach, outer); + let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()).len(); + // The symbol keeps its name: text, as its instances' copies of it are. + let art = art.filter(|_| self.charge_text(label)); + let total = self.cost().minus(before); + let own = total.minus(self.nested); + self.nested = outer_nested.plus(total); + (art, reach, own) + } +} + +/// The box of `r` placed by `xf`. A box that is not finite, or whose placed corners are not (an +/// overflow, which a union or a bounding box would drop as NaN), is the whole plane, so every +/// placement of it is out of range. +pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|p| xf * p); + match corners.iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + true => corners.iter().fold(Rect::from_points(corners[0], corners[0]), |b, p| b.union_pt(*p)), + false => Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY), + } +} + +/// The symbol of each instance in `art`, once per instance. +fn placed_symbols(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |n: &Node| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + out.push(symbol.clone()); + } + }); + out +} + +/// Every symbol of `doc` that no instance on its layers places, directly or through other +/// symbols, removed. +fn drop_unplaced_symbols(doc: &mut Document) { + let index: HashMap<&str, usize> = doc.symbols.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect(); + let mut placed = vec![false; doc.symbols.len()]; + let mut todo: Vec = vec![]; + // Each symbol is queued once, however many instances place it. + let note = |n: &Node, placed: &mut Vec, todo: &mut Vec| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && let Some(&i) = index.get(symbol.as_str()) + && let Some(seen) = placed.get_mut(i) + && !*seen + { + *seen = true; + todo.push(i); + } + }; + doc.walk(|n| note(n, &mut placed, &mut todo)); + while let Some(i) = todo.pop() { + if let Some(s) = doc.symbols.get(i) { + s.art.walk(&mut |n: &Node| note(n, &mut placed, &mut todo)); + } + } + let mut keep = placed.into_iter(); + doc.symbols.retain(|_| keep.next().unwrap_or(false)); } /// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span @@ -704,6 +1183,22 @@ fn fill_span(obj: &mut TextObject, span: Span, s: f64) { } } +/// Does clip boundary `clip` (pixel space) show the whole `w` × `h` image: is it a rectangle +/// square to the image that holds it? +fn covers(clip: &[Point], w: f64, h: f64) -> bool { + if clip.len() != 4 || clip.iter().enumerate().any(|(i, p)| clip[..i].contains(p)) { + return false; + } + let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { return false }; + let corner = |p: &Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1); + // Each point a distinct corner, and each edge along one side: the four corners in order around. + let side = |i: usize| { + let (p, q) = (clip[i], clip[(i + 1) % clip.len()]); + (p.x == q.x) != (p.y == q.y) + }; + clip.len() == 4 && clip.iter().all(corner) && (0..4).all(side) && b.x0 <= 0.0 && b.y0 <= 0.0 && b.x1 >= w && b.y1 >= h +} + fn rgb_color([r, g, b]: [u8; 3]) -> Color { Color::rgb8(r, g, b) } @@ -735,3 +1230,59 @@ fn unique(base: &str, next: &mut HashMap, taken: &HashSet } } } + +#[cfg(test)] +mod tests { + use super::*; + + const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n"; + + fn props() -> Props { + Props { + layer: "0".into(), + color: Col::Rgb([0, 0, 0]), + lineweight: Lw::Default, + linetype: "CONTINUOUS".into(), + ltscale: 1.0, + alpha: Alpha::Opacity(1.0), + } + } + + /// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements. + fn mixed() -> BezPath { + let mut bp = BezPath::new(); + for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] { + bp.move_to(a); + bp.line_to(b); + } + bp + } + + #[test] + fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() { + let (tags, _) = super::super::tags(EMPTY).unwrap(); + let d = Drawing::read(craft_dxf::model::Document::read(&tags)); + let o = ImportOptions::default(); + let (p, inh) = (props(), Inherit::default()); + // Seven objects with six slots free: refused; with seven: drawn, the group left to `item`. + let mut b = Build::new(&d, &o); + b.nodes = MAX_NODES - 6; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none()); + assert_eq!(b.nodes, MAX_NODES - 6); + b.nodes = MAX_NODES - 7; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some()); + assert_eq!(b.nodes, MAX_NODES - 1); + // Eight points with seven left: refused without charging them, so a 4-point path that + // follows still fits. + let mut b = Build::new(&d, &o); + b.elements = MAX_ELEMENTS - 7; + assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none()); + assert_eq!(b.elements, MAX_ELEMENTS - 7); + let mut line = BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((1.0, 0.0)); + line.line_to((1.0, 1.0)); + line.line_to((0.0, 1.0)); + assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some()); + } +} diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index acca831206..bfe6fe9bd3 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, HashMap}; use std::rc::Rc; -use kurbo::{BezPath, PathEl}; +use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape}; use vectorcraft_doc::Justify; use vectorcraft_geom::{Affine, Point, Vec2}; @@ -12,6 +12,7 @@ use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; use super::acis; use super::curve::{self, Vertex}; +use super::hatch::{self, Grad, NoPattern}; use super::reader::{aci_paper, point}; /// How far below the baseline the lowest descender reaches, as a fraction of the cap height. @@ -22,6 +23,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0; const MAX_CELLS: i64 = 10_000; /// The most copies all the array inserts of a file make together. const MAX_TOTAL_CELLS: i64 = 2_000_000; +/// The most winding steps for island nesting: loops times boundary elements times samples. +const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 }; +/// The most segment midpoints sampled just inside each loop for island nesting. +const MAX_ISLAND_SAMPLES: usize = 16; /// Art farther than this from the origin (drawing units) is damaged data, left out. const MAX_COORD: f64 = 1e12; /// How far fit and aligned text may be squeezed or stretched to span their two points: at width @@ -148,6 +153,31 @@ pub(crate) struct InsertItem { pub attribs: Vec, } +/// A raster image: the file its IMAGEDEF names, shown on a parallelogram. +#[derive(Clone, Debug)] +pub(crate) struct ImageItem { + /// The handle of its IMAGEDEF. + pub def: Option, + /// The lower-left corner, and one pixel along the width and up the height (world + /// coordinates, drawing units). + pub insert: Point, + pub u: Vec2, + pub v: Vec2, + /// Its size in pixels (0: its IMAGEDEF's). + pub size: [f64; 2], + /// The clip boundary in pixel space ([`ImageItem::placement`]); `None`: the whole image. + pub clip: Option>, +} + +impl ImageItem { + /// Pixel space (the top-left corner at the origin, x right, y down, one unit a pixel) to world + /// coordinates, for an image `height` pixels high. + pub fn placement(&self, height: f64) -> Affine { + let top = self.insert + self.v * height; + Affine::new([self.u.x, self.u.y, -self.v.x, -self.v.y, top.x, top.y]) + } +} + #[derive(Clone, Debug)] pub(crate) enum Geom { /// A path in world coordinates; `fill`: a filled area (hatch, solid), else a line of @@ -157,8 +187,24 @@ pub(crate) enum Geom { fill: bool, width: f64, }, + /// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates). + Shaded { + bp: BezPath, + shade: Shade, + }, Text(TextItem), Insert(InsertItem), + Image(ImageItem), +} + +/// How a [`Geom::Shaded`] path paints. +#[derive(Clone, Debug)] +pub(crate) enum Shade { + /// The area filled with a gradient. + Gradient(Box), + /// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no + /// length and need round caps to show. + Pattern { dots: bool }, } /// An entity as art: its geometry and its properties. @@ -176,16 +222,26 @@ pub(crate) struct Converter { pub warnings: Vec, /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. cells: i64, + /// The pattern budget shared by entity sections and blocks. + patterns: hatch::Budget, /// The binary solid-modeler data of regions, by handle (DXF 2013 and later). regions: Rc>>, } -const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; -const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour"; +const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries"; +const DENSE_PATTERN: &str = + "pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries"; +const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries"; +const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries"; +const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"; const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; +const FLAT_IMAGES: &str = "images with no width or height are left out"; +const IMAGE_ADJUSTMENTS: &str = "the brightness, contrast and fade of images are left out"; +const OPAQUE_IMAGES: &str = "images set to show opaque keep their file's transparency"; +const INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole"; const REGION_CURVES: &str = "region edges of some curve types come in as straight lines"; const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines"; const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve"; @@ -215,7 +271,7 @@ impl Converter { if !m.common.visible { continue; } - match self.geom(e, &m) { + match self.geom(e, &m).map(usable_paint) { Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY), Some(geom) => out.push(Item { props: Props::read(&m.common), geom }), None if is_known(e.kind) => {} @@ -259,7 +315,7 @@ impl Converter { face(&mut bp, &corners); (!bp.elements().is_empty()).then_some(bp).and_then(path) } - model::EntityKind::Hatch(h) => self.hatch(h, ocs), + model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color), model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text), model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text), model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs), @@ -267,11 +323,39 @@ impl Converter { model::EntityKind::Dimension(d) => { Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })) } + // Group 70 without its Show Image bit: a hidden image (an IMAGE without group 70 shows). + model::EntityKind::Image(_) if g.i(70).is_some_and(|flags| flags & 1 == 0) => None, + model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()), _ if e.kind == "REGION" => self.region(e), _ => None, } } + /// An IMAGE (its points are in world coordinates). + fn image(&mut self, im: &model::Image, has_display: bool) -> Option { + let (u, v) = (point(im.u).to_vec2(), point(im.v).to_vec2()); + let area = u.cross(v); + if !(area.is_finite() && area != 0.0) { + self.warn(FLAT_IMAGES); + return None; + } + if (im.brightness, im.contrast, im.fade) != (50, 50, 0) { + self.warn(IMAGE_ADJUSTMENTS); + } + if has_display && im.display & 8 == 0 { + self.warn(OPAQUE_IMAGES); + } + let clip = if !im.clipping || (has_display && im.display & 4 == 0) { + None + } else if im.clip_inverted { + self.warn(INVERTED_CLIPS); + None + } else { + image_clip(im) + }; + Some(Geom::Image(ImageItem { def: im.image_def, insert: point(im.insert), u, v, size: im.size, clip })) + } + fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option { // Meshes are in world coordinates, seen from above. if p.is_polyface() || p.is_mesh() { @@ -426,27 +510,153 @@ impl Converter { Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 }) } - fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option { - let mut bp = BezPath::new(); + /// A hatch's art; `own`: its color, which a gradient without color records takes. + fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option { + let mut loops = Vec::new(); for l in &h.loops { let Some(path) = boundary(&l.path) else { break }; - bp.extend(path); + loops.push(path); + } + let mut max_depth = match h.style { + 1 => Some(1), + 2 => Some(0), + _ => None, + }; + if max_depth.is_some() { + let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len())); + // Count each loop's samples against every loop, including its own containment checks. + if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK { + self.warn(MUCH_ISLAND_WORK); + max_depth = None; + } + } + let nesting: Vec<_> = if max_depth.is_some() { + loops + .iter() + .map(|path| { + let bounds = path.bounding_box(); + // Center each loop independently so distant loops do not erase small geometry. + let center = bounds.center(); + let local = transformed(path.clone(), Affine::translate(-center.to_vec2())); + let area = local.area(); + // Area divided by perimeter measures thickness independently of the loop's rotation. + let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3); + let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 }; + let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1); + let mut samples: Vec<_> = local + .segments() + .step_by(step) + .filter_map(|segment| { + let tangent = match segment { + PathSeg::Line(line) => line.deriv().eval(0.5), + PathSeg::Quad(quad) => quad.deriv().eval(0.5), + PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5), + } + .to_vec2(); + let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() }; + let length = tangent.hypot(); + if length == 0.0 { + return None; + } + // Positive area puts the interior to the left of the tangent in y-up coordinates. + Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length)) + }) + .take(MAX_ISLAND_SAMPLES) + .filter(|sample| local.winding(*sample) != 0) + .collect(); + if samples.is_empty() + && let Some(PathEl::MoveTo(first)) = local.elements().first() + { + samples.push(*first); + } + (bounds, center, local, area.abs(), samples) + }) + .collect() + } else { + Vec::new() + }; + let mut bp = BezPath::new(); + for (i, path) in loops.iter().enumerate() { + if let Some(limit) = max_depth { + let (bounds, center, _, area, samples) = &nesting[i]; + // Require geometric containment and a majority of samples so a shared + // edge or a single vertex on the boundary does not decide nesting. + let depth = nesting + .iter() + .enumerate() + .filter(|(j, _)| { + let (other_bounds, other_center, other, other_area, _) = &nesting[*j]; + let offset = *center - *other_center; + *j != i + && area < other_area + && bounds.x0 >= other_bounds.x0 + && bounds.y0 >= other_bounds.y0 + && bounds.x1 <= other_bounds.x1 + && bounds.y1 <= other_bounds.y1 + && samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2 + }) + .count(); + if depth > limit { + continue; + } + } + bp.extend(path.iter()); } if bp.elements().is_empty() { return None; } - let bp = transformed(bp, ocs); - if h.gradient.is_some() { - self.warn(GRADIENT_HATCH); - } else if !h.solid { - self.warn(PATTERN_HATCH); - return Some(Geom::Path { bp, fill: false, width: 0.0 }); + if let Some(g) = &h.gradient { + let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g))); + let bp = transformed(bp, ocs); + return Some(match shade { + Some(shade) => Geom::Shaded { bp, shade }, + None => Geom::Path { bp, fill: true, width: 0.0 }, + }); + } + if h.solid { + return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 }); + } + // The pattern lines are in the hatch's plane, as its boundary is. + let doubled; + let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 { + doubled = hatch::doubled(&h.pattern_lines); + &doubled + } else { + &h.pattern_lines + }; + match hatch::pattern(lines, &bp, &mut self.patterns) { + Ok((lines, _)) if lines.elements().is_empty() => None, + Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }), + Err(why) => { + self.warn(match why { + NoPattern::Undefined => PATTERN_HATCH, + NoPattern::TooDense => DENSE_PATTERN, + NoPattern::DrawingPieces => MANY_PATTERNS, + NoPattern::DrawingWork => MUCH_PATTERN_WORK, + }); + Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 }) + } } - Some(Geom::Path { bp, fill: true, width: 0.0 }) } } -/// Is the geometry within [`MAX_COORD`] of the origin? +/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill. +fn usable_paint(g: Geom) -> Geom { + match g { + Geom::Shaded { bp, shade: Shade::Gradient(grad) } => { + let geom = &grad.geom; + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) { + Geom::Shaded { bp, shade: Shade::Gradient(grad) } + } else { + Geom::Path { bp, fill: true, width: 0.0 } + } + } + g => g, + } +} + +/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it. fn in_range(g: &Geom) -> bool { let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD; let origin = |m: &Affine| near(m.translation().to_point()); @@ -454,8 +664,30 @@ fn in_range(g: &Geom) -> bool { Geom::Path { bp, width, .. } => { curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD } + Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))), Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD, Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)), + Geom::Image(i) => { + let [w, h] = i.size; + let far = i.insert + i.u * w + i.v * h; + near(i.insert) && near(far) && [i.u.x, i.u.y, i.v.x, i.v.y, w, h].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + } + } +} + +/// The clip boundary of IMAGE `im` in pixel space ([`ImageItem::placement`]): two opposite corners +/// of a rectangle, or a polygon of three points or more. The boundary's points are pixel centres +/// counted from the top-left pixel, so the image's own corners are at (−0.5, −0.5) and +/// (width − 0.5, height − 0.5). `None` when it has too few points. +fn image_clip(im: &model::Image) -> Option> { + let pts: Vec = im.clip.iter().map(|[x, y]| Point::new(x + 0.5, y + 0.5)).collect(); + match pts.as_slice() { + [a, b] if im.clip_type == 1 => { + let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y)); + Some(vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]) + } + p if p.len() >= 3 => Some(p.to_vec()), + _ => None, } } @@ -479,6 +711,7 @@ fn is_known(kind: &str) -> bool { | "MTEXT" | "INSERT" | "DIMENSION" + | "IMAGE" | "ATTDEF" | "SEQEND" | "VERTEX" diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs new file mode 100644 index 0000000000..80cd9339a9 --- /dev/null +++ b/crates/cad/src/import/hatch.rs @@ -0,0 +1,847 @@ +//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut +//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own +//! plane (its object coordinate system), where the boundary and the pattern lines are given. + +use kurbo::{BezPath, PathEl}; +use vectorcraft_color::{GradientGeom, GradientKind}; +use vectorcraft_geom::{Affine, Point, Vec2}; + +use craft_dxf::model::{self, PatternLine}; + +use super::entity::Col; +use super::reader::aci_paper; + +/// The most dashes and dots one pattern hatch draws. +pub(crate) const MAX_PIECES: usize = 20_000; +/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened. +const MAX_EDGES: usize = 200_000; +/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary +/// edge, and each dash, gap or dot looked at one more. +const MAX_WORK: usize = 20_000_000; +/// The most dashes and dots all pattern hatches draw together. +pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 }; +/// The most clipping and dash steps all pattern hatches take together. +pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 }; +/// How far flattened boundary curves may stray, as a fraction of their loop's larger side. +const FLATNESS: f64 = 1e-4; +/// Spans, line spacings and dash periods shorter than this many units of the last place of their +/// coordinates count as none. +const LOCAL_TINY: f64 = 64.0 * f64::EPSILON; + +/// Why a pattern hatch is not drawn as its pattern. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum NoPattern { + /// The hatch holds no pattern lines. + Undefined, + /// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or + /// [`MAX_WORK`] steps. + TooDense, + /// The drawing reaches its total piece limit. + DrawingPieces, + /// The drawing reaches its total work limit. + DrawingWork, +} + +/// The remaining pattern budget; discarded patterns also use it. +pub(crate) struct Budget { + pieces: usize, + work: usize, + stopped: Option, +} + +impl Default for Budget { + fn default() -> Self { + Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None } + } +} + +impl Budget { + fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> { + if *pieces >= MAX_PIECES { + return Err(NoPattern::TooDense); + } + if self.pieces == 0 { + self.stopped = Some(NoPattern::DrawingPieces); + return Err(NoPattern::DrawingPieces); + } + *pieces += 1; + self.pieces -= 1; + Ok(()) + } + + fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> { + if steps > MAX_WORK - *work { + return Err(NoPattern::TooDense); + } + if steps > self.work { + self.stopped = Some(NoPattern::DrawingWork); + return Err(NoPattern::DrawingWork); + } + *work += steps; + self.work -= steps; + Ok(()) + } +} + +/// Adds a perpendicular family when the pattern holds only one family. +pub(crate) fn doubled(lines: &[PatternLine]) -> Vec { + let mut out = lines.to_vec(); + if let [line] = lines { + out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() }); + } + out +} + +/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill): +/// each family's lines, cut into dashes and dots that start from the line's own base point. +/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot. +pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> { + if lines.is_empty() { + return Err(NoPattern::Undefined); + } + let exhausted = if budget.pieces == 0 { + Some(NoPattern::DrawingPieces) + } else if budget.work == 0 { + Some(NoPattern::DrawingWork) + } else { + None + }; + if let Some(why) = budget.stopped.or(exhausted) { + budget.stopped = Some(why); + return Err(why); + } + let mut out = BezPath::new(); + let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) }; + let size = b.width().max(b.height()); + if !(size > 0.0 && size.is_finite()) { + return Ok((out, false)); + } + let edges = edges(boundary)?; + if edges.is_empty() { + return Ok((out, false)); + } + let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)]; + let center = b.center(); + // The precision of the boundary's coordinates: spacings and periods below it draw nothing apart. + let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size); + let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false); + for l in lines { + let a = l.angle.to_radians(); + let d = Vec2::new(a.cos(), a.sin()); + let n = Vec2::new(-d.y, d.x); + let base = Point::new(l.base[0], l.base[1]); + let offset = Vec2::new(l.offset[0], l.offset[1]); + let step = offset.dot(n); + // A family with numbers out of range is damaged: the others still draw. + if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) { + continue; + } + usable = true; + // Lines no distance apart, or closer than the coordinates can tell apart, fill the area + // past what can be drawn. + if step.abs() <= tiny { + return Err(NoPattern::TooDense); + } + let period: f64 = l.dashes.iter().map(|v| v.abs()).sum(); + if !l.dashes.is_empty() && period <= tiny { + return Err(NoPattern::TooDense); + } + // The same family from the line nearest the boundary's center, a whole number of offsets + // away. The base and the center are each measured from the line through the origin + // first, so a base far away keeps the fraction of the center's position. + let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n)); + let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round()); + let across = (bn + to_origin * step) + (to_center * step - cn); + let last = -(across / step).round(); + let across = across + last * step; + // Where the dashes start on that line, from its point nearest the center. Each line is + // measured from its own point nearest the center, so its spans stay near the boundary + // however long the dash period is. Each term is reduced to within half a period before + // the terms are added, so a distant base or a large offset count keeps its remainder. + let od = offset.dot(d); + let along = if l.dashes.is_empty() { + 0.0 + } else { + let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od)); + sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period) + }; + if !(across.is_finite() && along.is_finite()) { + continue; + } + // The dash start nearest a line's point nearest the center, as a signed distance. + let phase = |k: f64| { + let [p, e] = product_parts(k, od); + sum_rem(&[along, p, e], period) + }; + let base = center + n * across; + // The lines crossing the boundary's box: base + k * step along the normal for whole k. + let h = corners.map(|c| (c - base).dot(n) / step); + let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil(); + let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor(); + if hi < lo { + continue; + } + let count = hi - lo + 1.0; + if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 { + return Err(NoPattern::TooDense); + } + let mut t = Vec::new(); + for k in (lo as i64)..=(hi as i64) { + budget.work(&mut work, edges.len())?; + let q = base + n * (step * k as f64); + crossings(&edges, q, d, n, &mut t); + for &[ta, tb] in t.as_chunks::<2>().0 { + // Spans of no length at the precision of their own coordinates are dropped. + if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) { + continue; + } + let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> { + budget.piece(&mut pieces)?; + out.move_to(q + d * s0); + out.line_to(q + d * s1); + Ok(()) + }; + if l.dashes.is_empty() { + emit(ta, tb, budget)?; + continue; + } + // The dashes run from the line's dash start, element by element, from the period + // the span starts in. + let start = phase(k as f64); + let mut at = start + ((ta - start) / period).floor() * period; + // Periods too short to move along the span, or more dashes than one hatch may + // look at, are refused before any of them is looked at. + let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64; + if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 { + return Err(NoPattern::TooDense); + } + // An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero. + let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> { + budget.work(&mut work, 1)?; + if v > 0.0 { + let (s0, s1) = (s.max(ta), e.min(tb)); + if s1 > s0 { + emit(s0, s1, budget)?; + } + } else if v == 0.0 && s >= ta { + emit(s, s, budget)?; + dots = true; + } + Ok(()) + }; + // When that period starts on the span's start, or past it, the elements that end + // the period before are measured back from its end, so a dot there is kept and a + // long period does not move them. Each element's start and end are the distances + // summed back from that end, so a long element does not move its known end. + if at >= ta { + let (mut back, mut first) = (vec![0.0], l.dashes.len()); + while first > 0 && at - back[back.len() - 1] >= ta { + first -= 1; + back.push(back[back.len() - 1] + l.dashes[first].abs()); + } + for (i, v) in l.dashes[first..].iter().enumerate() { + let rest = back.len() - 1 - i; + element(at - back[rest], at - back[rest - 1], *v, budget)?; + } + } + 'span: loop { + for v in &l.dashes { + if at > tb { + break 'span; + } + element(at, at + v.abs(), *v, budget)?; + at += v.abs(); + } + } + } + } + } + if !usable { + return Err(NoPattern::Undefined); + } + Ok((out, dots)) +} + +/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps +/// are exact: the remainder of a division, then one period added or taken away. +fn near_rem(x: f64, period: f64) -> f64 { + let r = x % period; + if r > period / 2.0 { + r - period + } else if r < -period / 2.0 { + r + period + } else { + r + } +} + +/// `a * b` as the rounded product and its rounding error, which add up to it exactly. +fn product_parts(a: f64, b: f64) -> [f64; 2] { + let p = a * b; + [p, a.mul_add(b, -p)] +} + +/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term +/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so +/// a small term is kept when larger ones cancel. +fn sum_rem(terms: &[f64], period: f64) -> f64 { + let (mut hi, mut lo) = (0.0, 0.0); + for &t in terms { + let t = near_rem(t, period); + let s = hi + t; + let v = s - hi; + lo += (hi - (s - v)) + (t - v); + hi = s; + } + near_rem(near_rem(hi, period) + near_rem(lo, period), period) +} + +/// The boundary's edges as straight segments, each loop closed and its curves flattened to +/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out. +fn edges(boundary: &BezPath) -> Result, NoPattern> { + let mut loops: Vec = Vec::new(); + for el in boundary.elements() { + if matches!(el, PathEl::MoveTo(_)) { + loops.push(BezPath::new()); + } + if let Some(l) = loops.last_mut() { + l.push(*el); + } + } + let mut out = Vec::new(); + let mut over = false; + let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| { + if out.len() >= MAX_EDGES { + over = true; + } else if a != b { + out.push((a, b)); + } + }; + for lp in &loops { + let Some(b) = super::curve::bounds(lp) else { continue }; + let tolerance = b.width().max(b.height()) * FLATNESS; + if !(tolerance > 0.0 && tolerance.is_finite()) { + continue; + } + let (mut start, mut last) = (None::, None::); + kurbo::flatten(lp.iter(), tolerance, |el| match el { + PathEl::MoveTo(p) => { + start = Some(p); + last = Some(p); + } + PathEl::LineTo(p) => { + if let Some(l) = last { + push(l, p, &mut out); + } + last = Some(p); + } + PathEl::ClosePath => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + last = start; + } + _ => {} + }); + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + } + if over { Err(NoPattern::TooDense) } else { Ok(out) } +} + +/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances +/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves +/// the side the previous one came from. +fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec) { + t.clear(); + for (p0, p1) in edges { + let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n)); + if (h0 > 0.0) != (h1 > 0.0) { + let p = p0.lerp(*p1, h0 / (h0 - h1)); + t.push((p - q).dot(d)); + } + } + t.sort_by(f64::total_cmp); +} + +/// The second color of a gradient: a color of its own, or for a one-color gradient the first +/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Second { + Col(Col), + Tint(f64), +} + +/// A gradient hatch's fill, placed in world coordinates (drawing units, y up). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Grad { + pub kind: GradientKind, + /// Linear: where the first stop sits and the last; radial: the center, a point on the outer + /// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen + /// at a slant). + pub geom: GradientGeom, + pub first: Col, + pub second: Second, + /// Each stop's position and whether it takes the second color (else the first). + pub stops: Vec<(f32, bool)>, +} + +impl Grad { + /// `first` shaded or tinted by `tint` (see [`Second::Tint`]). + pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] { + let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 }; + let mix = |c: u8| { + let c = f64::from(c); + let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 }; + v.round().clamp(0.0, 255.0) as u8 + }; + [mix(r), mix(g), mix(b)] + } +} + +fn col(c: model::Color) -> Col { + match c { + model::Color::Rgb(rgb) => Col::Rgb(rgb), + model::Color::Index(i) => Col::Rgb(aci_paper(i)), + model::Color::ByBlock => Col::ByBlock, + model::Color::ByLayer => Col::ByLayer, + } +} + +/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world +/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle +/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way: +/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first; +/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same +/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the +/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift +/// moves the center up and left by up to a quarter of the extent. +pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option { + let angle = if g.angle.is_finite() { g.angle } else { 0.0 }; + let mut frame = boundary.clone(); + frame.apply_affine(Affine::rotate(-angle)); + let r = super::curve::bounds(&frame)?; + let (w, h) = (r.width(), r.height()); + let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 }; + let c = r.center() + Vec2::new(-w, h) * (shift / 4.0); + // How far the shift moves the center left and up. + let (dx, dy) = (c.x - r.center().x, c.y - r.center().y); + let name = g.name.trim().to_uppercase(); + let (inverse, name) = match name.strip_prefix("INV") { + Some(rest) => (true, rest), + None => (false, name.as_str()), + }; + let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::>(); + let (kind, start, end, stops) = match name { + "CYLINDER" => { + (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)])) + } + "SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])), + "HEMISPHERICAL" => { + let center = Point::new(c.x, r.y0 + dy); + (GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)])) + } + "CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])), + _ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])), + }; + let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None }; + geom.transform(ocs * Affine::rotate(angle), kind); + let first = g.colors.first().map_or(own, |c| col(*c)); + let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) }; + Some(Grad { kind, geom, first, second, stops }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> { + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + super::pattern(lines, boundary, &mut budget) + } + + #[test] + fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() { + let lines = [line(0.0, [0.0, 1.0], &[])]; + let boundary = square(10.0); + let mut budget = Budget { pieces: 3, work: 100, stopped: None }; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces)); + assert_eq!(budget.pieces, 0); + assert!(budget.work < 100); + let work = budget.work; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces)); + assert_eq!(budget.work, work, "later hatches do no clipping"); + + let mut budget = Budget { pieces: 100, work: 9, stopped: None }; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!(budget.work, 1, "two lines cost four edges each"); + let pieces = budget.pieces; + assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!((budget.work, budget.pieces), (1, pieces)); + + let gaps = [line(0.0, [0.0, 1.0], &[-0.01])]; + let mut budget = Budget { pieces: 100, work: 20, stopped: None }; + assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork)); + assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces"); + } + + fn square(side: f64) -> BezPath { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.line_to((side, 0.0)); + bp.line_to((side, side)); + bp.line_to((0.0, side)); + bp.close_path(); + bp + } + + fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine { + PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() } + } + + #[test] + fn doubling_adds_a_perpendicular_family_only_when_one_is_present() { + let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]); + level.base = [2.0, 5.0]; + let lines = doubled(&[level.clone()]); + let [first, second] = &lines[..] else { panic!("two families") }; + assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes)); + assert_eq!(second.angle, level.angle + 90.0); + assert_eq!(second.offset, [-level.offset[1], level.offset[0]]); + assert_eq!((second.base, &second.dashes), (level.base, &level.dashes)); + let kept = doubled(&lines); + assert_eq!(kept.len(), lines.len()); + for (a, b) in kept.iter().zip(&lines) { + assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes)); + } + } + + /// The pieces as (start, end) pairs. + fn pieces(bp: &BezPath) -> Vec<(Point, Point)> { + let mut out = vec![]; + let mut from = Point::ZERO; + for el in bp.elements() { + match el { + PathEl::MoveTo(p) => from = *p, + PathEl::LineTo(p) => out.push((from, *p)), + _ => {} + } + } + out + } + + #[test] + fn pattern_lines_stop_at_the_boundary_and_skip_holes() { + // Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square + // hole in the middle. + let mut boundary = square(100.0); + let mut hole = square(20.0); + hole.apply_affine(Affine::translate((40.0, 40.0))); + boundary.extend(hole); + let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] }; + let (bp, dots) = pattern(&[l], &boundary).unwrap(); + assert!(!dots); + let p = pieces(&bp); + // Ten lines, the two through the hole (y 45 and 55) each cut in two. + assert_eq!(p.len(), 12, "{p:?}"); + for (a, b) in &p { + assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9); + } + let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect(); + assert_eq!(middle.len(), 2); + assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}"); + } + + #[test] + fn dashes_start_at_each_lines_base_point() { + // Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them. + let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] }; + let (bp, dots) = pattern(&[l], &square(100.0)).unwrap(); + assert!(dots); + let p = pieces(&bp); + let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::>(); + let first = row(50.0); + assert!(first.len() > 4, "{first:?}"); + // The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary. + assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]); + assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0)); + } + + #[test] + fn a_dash_across_the_boundary_is_cut_there() { + let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap(); + let p = pieces(&bp); + assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9)); + // The second dash, 40 to 70, crosses the boundary at 50 and stops there. + assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}"); + assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}"); + } + + #[test] + fn short_spans_far_apart_keep_their_pieces_and_curves() { + // Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its + // one-unit spans. + let strip = |x: f64| { + let mut s = square(1.0); + s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0)); + s + }; + let mut boundary = strip(0.0); + boundary.extend(strip(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] }; + let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 4, "{p:?}"); + assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}"); + // Unit circles as far apart keep their round outlines: the line through y 0.5 spans + // 2 * sqrt(0.75) of each. + let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1); + let mut boundary = circle(0.0); + boundary.extend(circle(1e10)); + let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] }; + let (bp, _) = pattern(&[l], &boundary).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 2, "{p:?}"); + let chord = 2.0 * 0.75f64.sqrt(); + assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}"); + } + + #[test] + fn close_lines_across_squares_far_apart_are_drawn() { + // Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square. + let mut boundary = square(1.0); + let mut far = square(1.0); + far.apply_affine(Affine::translate((1e10, 0.0))); + boundary.extend(far); + let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap(); + assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp)); + // Dashes 0.25 long with 0.25 gaps: two per line in each square. + let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap(); + assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp)); + } + + #[test] + fn families_based_far_away_draw_the_same_lines() { + // Lines one apart from a base 1e19 up are the lines one apart from the origin. + let mut far = line(0.0, [0.0, 1.0], &[]); + far.base = [0.0, 1e19]; + let (bp, _) = pattern(&[far], &square(100.0)).unwrap(); + let p = pieces(&bp); + assert_eq!(p.len(), 100, "{p:?}"); + assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}"); + // A staggered family based 100 lines away keeps each line's dash phase. + let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]); + near.base = [-497.0, 0.0]; + let mut away = near.clone(); + away.base = [3.0, 1000.0]; + let sorted = |l: PatternLine| { + let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0); + p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal)); + p + }; + let (a, b) = (sorted(near), sorted(away)); + assert_eq!(a.len(), b.len()); + assert!(!a.is_empty()); + assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}"); + } + + #[test] + fn families_based_far_away_keep_lines_off_a_fractional_center() { + // A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not + // through the center. + let mut far = line(0.0, [0.0, 1.0], &[]); + far.base = [0.0, 1e19]; + let (bp, _) = pattern(&[far], &square(3.0)).unwrap(); + let p = pieces(&bp); + assert!(p.len() >= 2, "{p:?}"); + assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}"); + } + + #[test] + fn dash_periods_far_longer_than_the_boundary_still_draw() { + // Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a + // dash, so every row is drawn across the square. + for x in [0.0, -7.5e15] { + let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]); + l.base = [x, 0.0]; + let (bp, _) = pattern(&[l], &square(100.0)).unwrap(); + let p = pieces(&bp); + let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect(); + assert_eq!(rows.len(), 9, "base x {x}: {p:?}"); + assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}"); + } + // From x 5e15 the square lies in a gap: nothing is drawn. + let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]); + l.base = [5e15, 0.0]; + let (bp, _) = pattern(&[l], &square(100.0)).unwrap(); + assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp)); + } + + #[test] + fn large_offset_counts_that_cancel_keep_the_dash_start() { + // A 100 square 2^40 up, its family based on the row through its middle with offsets + // 2^30 along: the row's dashes start at x 0, so it draws 0 to 30. + let b = 2f64.powi(40); + let mut boundary = square(100.0); + boundary.apply_affine(Affine::translate((0.0, b))); + let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]); + l.base = [0.0, b + 50.0]; + let p = pieces(&pattern(&[l], &boundary).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row.len(), 1, "{p:?}"); + assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}"); + } + + #[test] + fn large_phase_terms_that_cancel_keep_a_small_one() { + // Based and offset by 2^54 along and 10 up: the line one offset back runs along the + // bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1. + let big = 2f64.powi(54); + let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]); + l.base = [big, 10.0]; + let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row, [(0.0, 1.0)], "{p:?}"); + } + + #[test] + fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() { + // A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square + // lies in the gap, so nothing is drawn. + let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]); + l.base = [0.0, 0.5]; + let (bp, _) = pattern(&[l], &square(1.0)).unwrap(); + assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp)); + } + + #[test] + fn distant_bases_keep_their_dash_remainder() { + // Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the + // dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x. + for side in [96.0, 98.0] { + let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]); + l.base = [1e19, 0.0]; + let p = pieces(&pattern(&[l], &square(side)).unwrap().0); + let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect(); + assert_eq!(row.len(), 16, "side {side}: {row:?}"); + assert!( + row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9), + "side {side}: {row:?}" + ); + } + } + + #[test] + fn a_dot_on_the_start_of_a_span_is_kept() { + // A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom. + let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap(); + assert!(dots); + let xs: Vec = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect(); + assert_eq!(xs, [0.0, 5.0, 10.0]); + } + + #[test] + fn slanted_lines_fill_a_square_evenly() { + // 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one + // side of the square to another. + let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()]; + let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap(); + let p = pieces(&bp); + assert!((14..=15).contains(&p.len()), "{} lines", p.len()); + let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6); + assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b))); + } + + #[test] + fn too_dense_patterns_and_missing_ones_are_reported() { + assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined)); + // Lines 0.001 apart across a 1,000 square: a million lines. + assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense)); + // Few lines, but dashes far shorter than the square: more pieces than allowed. + assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense)); + // A tiny nonempty dash period is too dense; only an empty list draws continuous lines. + // It is refused once the first line is clipped, before any of its dashes is looked at. + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense)); + assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at"); + // A period below the coordinates' precision is refused before any line is clipped. + let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None }; + assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense)); + assert_eq!(budget.work, usize::MAX, "no work done"); + let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap(); + assert!(!pieces(&bp).is_empty()); + // Lines on top of each other, or as good as, are as dense as can be. + assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense)); + assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense)); + // Only damaged families: no pattern to draw. + assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined)); + } + + fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient { + model::Gradient { + name: name.into(), + angle, + shift, + single: false, + tint: 0.0, + colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])], + } + } + + #[test] + fn gradients_run_across_the_boundary_at_their_angle() { + let box_ = { + let mut b = square(100.0); + b.apply_affine(Affine::scale_non_uniform(2.0, 1.0)); + b + }; + let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0))); + assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255])))); + assert_eq!(g.stops, [(0.0, false), (1.0, true)]); + // At a quarter turn it runs bottom to top. + let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}"); + // Shifted, the center moves up and left: a sphere's center and a cylinder's middle. + let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0))); + assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center"); + let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0)); + // A curved gradient runs bottom to top, so the shift moves it up. + for name in ["CURVED", "INVCURVED"] { + let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}"); + } + // A plane stretched twice as wide stretches the circle into an ellipse with it. + let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap(); + assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom); + } + + #[test] + fn inverse_gradients_swap_their_colors() { + for (name, inv) in + [("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")] + { + let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); + let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap(); + assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}"); + let count = if name == "CYLINDER" { 3 } else { 2 }; + assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}"); + assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops); + } + } + + #[test] + fn one_color_gradients_shade_or_tint_their_color() { + assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]); + assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]); + assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]); + assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]); + let mut g = grad("LINEAR", 0.0, 0.0); + (g.single, g.tint, g.colors) = (true, 0.75, vec![]); + let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap(); + assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color"); + } +} diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index bfa1293b8d..1adc71c563 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -1,5 +1,5 @@ //! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer, -//! linetype and text style tables; the blocks; the entities; the layouts. +//! linetype and text style tables; the blocks; the entities; the layouts; the image files. use std::collections::{HashMap, HashSet}; use std::rc::Rc; @@ -50,6 +50,15 @@ pub(crate) struct BlockDef<'a> { pub xref: bool, } +/// A raster image file that IMAGE entities show (an IMAGEDEF object). +#[derive(Clone, Debug)] +pub(crate) struct ImageFile { + /// The file's path as the drawing stores it (absolute, or relative to the drawing). + pub path: String, + /// Its size in pixels (0 when not given). + pub size: [f64; 2], +} + /// A layout: model space, or a paper layout with the block holding its art. #[derive(Clone, Debug)] pub(crate) struct LayoutDef { @@ -80,6 +89,8 @@ pub(crate) struct Drawing<'a> { pub entities: Vec>, /// Model space first, then the paper layouts in tab order. pub layouts: Vec, + /// The image files by the handle of their IMAGEDEF. + pub images: HashMap, /// How many sections the file has (none: not a drawing). pub sections: usize, /// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in @@ -116,6 +127,11 @@ impl<'a> Drawing<'a> { } let block_names = doc.block_names(); d.layouts = layouts(&doc, &block_names); + for def in doc.objects_of("IMAGEDEF").map(model::objects::ImageDef::read) { + if let Some(h) = def.handle { + d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size }); + } + } d.regions = Rc::new(region_data(&doc)); for b in doc.blocks { if b.name.is_empty() { diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index d53694343a..2731979702 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -4,9 +4,9 @@ use std::sync::Arc; -use kurbo::ParamCurve; +use kurbo::{ParamCurve, Shape}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit}; +use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit}; use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; use super::*; @@ -505,6 +505,593 @@ fn solid_hatches_fill_and_pattern_hatches_outline() { assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none())); } +/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through +/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups). +fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> { + let mut e = hatch("0"); + e.insert(1, (6, linetype)); + let seeds = e.iter().position(|p| *p == (98, "0")).unwrap(); + let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")]; + lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes }); + e.splice(seeds..seeds, lines); + e +} + +#[test] +fn ignore_islands_hatches_fill_and_pattern_through_the_hole() { + let mut e = hatch("1"); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square"); + assert!(path.subpaths[0].closed); + assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none())); + let box_area = bounds(area).area(); + assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled"); + + let mut e = pattern_hatch("CONTINUOUS", &[]); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole"); + let width = bounds(lines).width(); + assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square"); +} + +#[test] +fn hatch_island_styles_select_nested_boundary_levels() { + let mut e = hatch("1"); + let count = e.iter().position(|p| p.0 == 91).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + e[count] = (91, "3"); + let mut loops = Vec::new(); + // Innermost first so nesting depends on geometry, not boundary order or flags. + for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] { + loops.extend([ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, lo), + (20, lo), + (10, hi), + (20, lo), + (10, hi), + (20, hi), + (10, lo), + (20, hi), + (97, "0"), + ]); + } + e.splice(count + 1..end, loops); + // The sides of the squares each style keeps: normal and unknown styles all three, outer the + // outermost and middle ones, ignore the outermost alone. + for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] { + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let mut sides: Vec = match &area.kind { + NodeKind::Compound { children, rule } => { + assert_eq!(*rule, FillRule::EvenOdd); + children.iter().map(|c| bounds(c).width().round()).collect() + } + _ => { + assert_eq!(area.path_data().unwrap().subpaths.len(), 1); + vec![bounds(area).width().round()] + } + }; + sides.sort_by(f64::total_cmp); + assert_eq!(sides, expected, "boundary loops for island style {style}"); + assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none())); + } +} + +#[test] +fn hatch_ignore_islands_drops_small_island_far_from_origin() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Centered, so the art far from the drawing's origin lands on the canvas. + let r = open(&entities(&e), &ImportOptions { center: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + *e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3"); + let mut loops = Vec::new(); + for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Fitted to the artboard: the drawing spans more than the canvas holds at 1:1. + let r = open(&entities(&e), &ImportOptions { fit: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") }; + assert_eq!(children.len(), 2, "the island is removed and both outer squares remain"); +} + +#[test] +fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + *e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3"); + let mut loops = Vec::new(); + for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + // Fitted to the artboard: the drawing spans more than the canvas holds at 1:1. + let r = open(&entities(&e), &ImportOptions { fit: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") }; + assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain"); +} + +#[test] +fn hatch_ignore_islands_keeps_squares_sharing_an_edge() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // The first vertex lies on the second square's left edge. + for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") }; + assert_eq!(children.len(), 2, "adjacent squares are both boundaries"); +} + +#[test] +fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // The island's first vertex touches the outer square's right edge, where + // winding is zero. Its other vertices and all segment midpoints are inside. + for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the touching island is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_thin_island() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + for vertices in [ + [("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")], + [("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")], + ] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the thin island is removed"); +} + +#[test] +fn hatch_ignore_islands_drops_rotated_thin_island() { + let mut e = hatch("1"); + let start = e.iter().position(|p| p.0 == 92).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + let mut loops = Vec::new(); + // These are the previous test's corners turned 45 degrees about the origin. + for vertices in [ + [("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")], + [ + ("7.07106639765", "7.07106922608"), + ("63.6396088926", "63.6396117210"), + ("63.6396046499", "63.6396159636"), + ("7.07106215421", "7.07107346952"), + ], + ] { + loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in vertices { + loops.extend([(10, x), (20, y)]); + } + loops.push((97, "0")); + } + e.splice(start..end, loops); + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2"); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let path = area.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed"); +} + +#[test] +fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() { + let mut e = hatch("1"); + let count = e.iter().position(|p| p.0 == 91).unwrap(); + let hole = e.iter().position(|p| *p == (92, "0")).unwrap(); + let end = e.iter().position(|p| p.0 == 75).unwrap(); + e[count] = (91, "16"); + // Keep the outer square and add 15 inner squares. With at least five path elements + // per square, 16 loops require at least 1,280 steps, over the test-time limit. + // Without the fallback, ignore style removes the inner squares. + let inner = [ + (92, "2"), + (72, "0"), + (73, "1"), + (93, "4"), + (10, "20"), + (20, "20"), + (10, "80"), + (20, "20"), + (10, "80"), + (20, "80"), + (10, "20"), + (20, "80"), + (97, "0"), + ]; + e.splice(hole..end, inner.repeat(15)); + for style in ["2", "0"] { + *e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style); + let r = open(&entities(&e), &points()); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let count = match &area.kind { + NodeKind::Compound { children, .. } => children.len(), + _ => area.path_data().unwrap().subpaths.len(), + }; + assert_eq!(count, 16, "every boundary loop is kept for style {style}"); + if style == "2" { + assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]); + } else { + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } + } +} + +#[test] +fn pattern_hatches_draw_their_lines_inside_the_boundary() { + // A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them. + let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")]; + let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + // Ten lines; the four that cross the hole (y 35 to 65) are cut in two. + assert_eq!(children.len(), 14); + assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]); + assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled"); + assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines"); + let h = height(&r.document); + for c in children { + let pts = path_points(c); + let (a, b) = (pts[0], *pts.last().unwrap()); + let y = h - a.y; + assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}"); + assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}"); + let mid = Point::new((a.x + b.x) / 2.0, y); + assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}"); + } + assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round)); + // A pattern of dots (no length) shows them with round caps. + let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points()); + let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings); + // Dashes and dots together: the dots take round caps on a path of their own, and the dashes + // keep butt caps, so they do not grow into their gaps. + let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")]; + let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) }; + assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round)); + assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round)); + let length = |n: &Node| { + let pts = path_points(n); + pts[0].distance(*pts.last().unwrap()) + }; + let pieces = |n: &Node| match &n.kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(), + _ => vec![n.clone()], + }; + assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes"); + assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots"); + // Without its pattern lines a pattern hatch still comes in as its boundary, with a note. + let r = open(&entities(&hatch("0")), &points()); + assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings); +} + +#[test] +fn user_defined_double_hatches_draw_level_and_vertical_lines() { + for double in ["1", "0"] { + let mut e = pattern_hatch("CONTINUOUS", &[]); + let kind = e.iter().position(|p| *p == (76, "1")).unwrap(); + e[kind] = (76, "0"); + e.insert(kind + 1, (77, double)); + let r = open(&entities(&e), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) }; + let (mut level, mut vertical) = (0, 0); + for c in children { + let pts = path_points(c); + let (a, b) = (pts[0], *pts.last().unwrap()); + if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 { + level += 1; + } else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 { + vertical += 1; + } else { + panic!("level or vertical piece: {a:?} {b:?}"); + } + } + assert!(level > 0, "level pieces with double = {double}"); + assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}"); + } +} + +#[test] +fn pattern_hatches_share_the_drawings_budget() { + // Keep the fixture's square alone so every fallback is one closed path. + let mut hatch = pattern_hatch("CONTINUOUS", &[]); + let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap(); + let end = hatch.iter().position(|p| p.0 == 75).unwrap(); + hatch.drain(hole..end); + *hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1"); + let limit = super::hatch::MAX_TOTAL_PIECES; + let count = limit / 10 + 5; + let e = hatch.repeat(count); + let r = open(&entities(&e), &points()); + assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings); + assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert_eq!(art.len(), count, "each hatch keeps its place"); + let mut pieces = 0; + let mut boundaries = 0; + for n in art { + if let NodeKind::Compound { children, .. } = &n.kind { + assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries"); + pieces += children.len(); + assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed)))); + } else { + let path = n.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed); + boundaries += 1; + } + } + assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}"); + assert!(boundaries >= 5, "hatches past the budget keep their boundaries"); +} + +/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from +/// a true color (red) to color 5 (blue), or from red alone with `tint`. +fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> { + let mut e = hatch("1"); + e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]); + e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]); + e +} + +fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint { + match n.appearance.fill().map(|f| &f.paint) { + Some(Paint::Gradient(g)) => (**g).clone(), + other => panic!("not a gradient: {other:?}"), + } +} + +#[test] +fn gradient_hatches_keep_their_gradient() { + let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + let g = gradient_of(area); + let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect(); + assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear); + assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5"); + // Level, across the square from left to right through its middle. + let (h, geom) = (height(&r.document), g.geom.unwrap()); + assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}"); + // A quarter turn runs it up the square: from the bottom (larger y in the document) to the top. + let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points()); + let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap(); + assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}"); + // A one-color sphere tinted to white: white in the center, red at the edge. + let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points()); + let g = gradient_of(&r.document.layers[0].children().unwrap()[0]); + let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect(); + assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]])); + assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9); +} + +#[test] +fn block_gradient_stops_keep_the_inserts_color() { + for (color, layer) in [("0", "Doors"), ("256", "0")] { + for (second, tint) in [(false, None), (true, None), (false, Some("1"))] { + let mut hatch = gradient_hatch("LINEAR", "0", tint); + // The hatch's explicit color and other properties do not need insert inheritance. + hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]); + hatch.retain(|p| p.0 != 421); + let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap(); + *stop = (63, color); + let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")]; + let r = open(&with_door(&hatch, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [symbol] = &r.document.symbols[..] else { panic!("one symbol") }; + let g = gradient_of(&symbol.art); + let stop = &g.gradient.stops[usize::from(second)]; + let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] }; + assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}"); + } + } +} + +#[test] +fn gradient_hatches_far_out_keep_their_fill() { + // A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the + // strip still comes in, centered on the artboard. + let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")]; + e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]); + for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] { + e.extend([(10, x), (20, y)]); + } + e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]); + e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]); + e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]); + let r = open(&entities(&e), &ImportOptions { center: true, ..points() }); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") }; + assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial); + assert_eq!(bounds(area).width().round(), 10.0); +} + +/// [`with_door`] with a dashed linetype `DASHED` in the drawing. +fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec { + let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")]; + blocks.extend_from_slice(block_art); + blocks.push((0, "ENDBLK")); + let tables = [ + (0, "TABLE"), + (2, "LTYPE"), + (0, "LTYPE"), + (2, "DASHED"), + (73, "2"), + (40, "15"), + (49, "10"), + (49, "-5"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (2, "Doors"), + (70, "0"), + (62, "5"), + (6, "CONTINUOUS"), + (0, "ENDTAB"), + ]; + drawing(&[], &tables, &blocks, inserts) +} + +/// Whether `n` or any object inside it has a dashed stroke. +fn dashed(n: &Node) -> bool { + n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c))) +} + +#[test] +fn block_pattern_hatches_ignore_the_inserts_linetype() { + let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")]; + // Pattern lines draw without a linetype: inserts of other colors share one symbol. + let mut lines = pattern_hatch("BYBLOCK", &[]); + lines.splice(1..1, [(8, "Doors"), (370, "25")]); + let r = open(&with_door(&lines, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(r.document.symbols.len(), 1); + // A pattern hatch drawn as its boundary strokes it in the insert's linetype. + let mut boundary = hatch("0"); + boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]); + let r = open(&with_door(&boundary, &inserts), &points()); + assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); + + // Inserts of one color, one dashed and one continuous. + let inserts = + [(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")]; + let r = open(&with_dashed_door(&lines, &inserts), &points()); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") }; + assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes"); + // The boundary drawn for each insert takes that insert's linetype. + let r = open(&with_dashed_door(&boundary, &inserts), &points()); + assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings); + let looks: Vec = leaves(&r.document) + .iter() + .map(|n| { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) }; + dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art) + }) + .collect(); + assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not"); +} + #[test] fn hatch_declaring_many_absent_source_handles_parses_quickly() { let base = hatch("1"); diff --git a/crates/cad/src/import/tests_dwg.rs b/crates/cad/src/import/tests_dwg.rs index 00ff6aa7da..9089b444a9 100644 --- a/crates/cad/src/import/tests_dwg.rs +++ b/crates/cad/src/import/tests_dwg.rs @@ -1,5 +1,5 @@ -//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF -//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD +//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer (2004 and 2018) or +//! acadrust's (R12, R13 and R14), come in as the DXF does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD //! on aarch64. #![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] @@ -12,6 +12,11 @@ use crate::{DxfOptions, DxfVersion}; /// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse. fn dxf() -> Vec { + dxf_as(DxfVersion::R2000) +} + +/// [`dxf`] written as a DXF of `version`. +fn dxf_as(version: DxfVersion) -> Vec { let mut d = Document::new(200.0, 100.0); let layer = d.add_layer(Some("Walls")); let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0); @@ -20,7 +25,7 @@ fn dxf() -> Vec { for n in [rect, oval] { d.insert(Some(layer), usize::MAX, n).unwrap(); } - let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; + let o = DxfOptions { version, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() }; crate::export(&d, &o).unwrap().bytes } @@ -55,19 +60,52 @@ fn art(doc: &Document) -> Vec { .collect() } +/// `dxf` as an R12, R13 or R14 DWG file, the version the DXF declares, written by acadrust: the +/// reader craft-dwg reads DWG with. craft-dwg's own writer starts at 2000. +fn old_dwg(dxf: &[u8]) -> Vec { + let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.to_vec())).and_then(acadrust::DxfReader::read).unwrap(); + acadrust::DwgWriter::write_to_vec(&doc).unwrap() +} + +/// `dwg`, a DWG file of `version`, imports as the art `dxf` imports as, and its info names its +/// version and layer. +fn assert_comes_in_as(dxf: &[u8], dwg: &[u8], version: DxfVersion) { + assert!(crate::is_dwg(dwg) && !crate::is_dwg(dxf)); + assert_eq!(craft_dwg::version(dwg).as_deref(), Some(version.acadver())); + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let want = art(&import(dxf, &o).unwrap().document); + assert_eq!(want.len(), 1, "{want:?}"); + // An R12 DXF writes layer names in capitals. + assert!(want[0].0.as_deref().is_some_and(|n| n.eq_ignore_ascii_case("Walls")), "{want:?}"); + assert_eq!(want[0].1.len(), 2, "{want:?}"); + assert_eq!(art(&import(dwg, &o).unwrap().document), want, "{}", version.id()); + let i = info(dwg).unwrap(); + assert_eq!(i.version, version.id(), "{i:?}"); + assert!(i.layers.iter().any(|l| Some(l) == want[0].0.as_ref()), "{i:?}"); +} + #[test] fn a_dwg_drawing_comes_in_as_its_dxf_does() { let (dxf, dwg) = (dxf(), dwg()); - assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf)); - let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; - let want = art(&import(&dxf, &o).unwrap().document); - assert_eq!(want.len(), 1, "{want:?}"); - assert_eq!(want[0].0.as_deref(), Some("Walls")); - assert_eq!(want[0].1.len(), 2, "{want:?}"); - assert_eq!(art(&import(&dwg, &o).unwrap().document), want); + assert_comes_in_as(&dxf, &dwg, DxfVersion::R2004); let i = info(&dwg).unwrap(); assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model"))); - assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}"); +} + +#[test] +fn r12_r13_and_r14_dwg_drawings_come_in_as_their_dxf_does() { + crate::dwg::allow_in_process(); + for version in [DxfVersion::R12, DxfVersion::R13, DxfVersion::R14] { + let dxf = dxf_as(version); + assert_comes_in_as(&dxf, &old_dwg(&dxf), version); + } +} + +#[test] +fn a_2018_dwg_drawing_comes_in_as_its_dxf_does() { + crate::dwg::allow_in_process(); + let dxf = dxf_as(DxfVersion::R2018); + assert_comes_in_as(&dxf, &craft_dwg::dxf_to_dwg_as(&dxf, "AC1032").unwrap(), DxfVersion::R2018); } #[test] @@ -77,9 +115,24 @@ fn a_damaged_dwg_is_an_error_that_names_dwg() { let e = import(&cut, &ImportOptions::default()).unwrap_err(); assert!(e.contains("DWG"), "{e}"); assert!(info(&cut).is_err()); - // An R1.x or R2.x drawing is refused without reading it. - for old in [&b"AC1.50\x00\x00\x00\x00"[..], b"AC2.10\x00\x00\x00\x00", b"MC0.0\x00\x00\x00\x00"] { + // A drawing of a version the DWG reader skips is refused by its version, without reading it. + for (old, name) in [ + (&b"AC1.50\x00\x00\x00\x00"[..], "DWG R2.05 (AC1.50)"), + (b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"), + (b"AC1004\x00\x00\x00\x00", "DWG R9 (AC1004)"), + ] { let e = import(old, &ImportOptions::default()).unwrap_err(); - assert!(e.contains("version can't be read") && e.contains("DXF"), "{e}"); + assert!(e.starts_with(&format!("this drawing is {name},")) && e.contains("DXF"), "{e}"); + assert_eq!(info(old).unwrap_err(), e); } + assert_eq!(import(b"AC1018", &ImportOptions::default()).unwrap_err(), "DWG: the file is cut short"); +} + +#[test] +fn a_dwg_drawing_with_an_ad_version_code_comes_in_as_its_ac_one_does() { + let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() }; + let ac = dwg(); + let mut ad = ac.clone(); + ad[1] = b'D'; + assert_eq!(art(&import(&ad, &o).unwrap().document), art(&import(&ac, &o).unwrap().document)); } diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs new file mode 100644 index 0000000000..9d85ca08ba --- /dev/null +++ b/crates/cad/src/import/tests_image.rs @@ -0,0 +1,620 @@ +//! Raster images: an IMAGE comes in as an image linked to the file its IMAGEDEF names, placed as +//! its corner and pixel vectors say and clipped by its clip boundary; images the export wrote come +//! back where they were. + +use std::sync::Arc; + +use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Unit}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use super::*; +use crate::{DxfOptions, DxfVersion}; + +/// A DXF file of `entities` and `objects` (each a run of pairs). +fn drawing(entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec { + with_blocks(&[], entities, objects) +} + +/// A DXF file of `blocks`, `entities` and `objects` (each a run of pairs). +fn with_blocks(blocks: &[(i32, &str)], entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec { + let mut p: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")]; + p.extend([(0, "SECTION"), (2, "BLOCKS")]); + p.extend_from_slice(blocks); + p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES")]); + p.extend_from_slice(entities); + p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]); + p.extend_from_slice(objects); + p.extend([(0, "ENDSEC"), (0, "EOF")]); + p.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() +} + +/// An IMAGEDEF with handle `handle` naming `file`, 30 × 10 pixels. +fn def<'a>(handle: &'a str, file: &'a str) -> Vec<(i32, &'a str)> { + vec![(0, "IMAGEDEF"), (5, handle), (100, "AcDbRasterImageDef"), (1, file), (10, "30"), (20, "10")] +} + +/// An IMAGE of IMAGEDEF `def` with its lower-left corner at (10, 20) and 2-unit pixels, `size` +/// pixels (none given: `None`), followed by `more` groups. +fn image<'a>(def: &'a str, size: Option<(&'a str, &'a str)>, more: &[(i32, &'a str)]) -> Vec<(i32, &'a str)> { + let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "0"), (22, "2")]; + if let Some((w, h)) = size { + e.extend([(13, w), (23, h)]); + } + e.push((340, def)); + e.extend_from_slice(more); + e +} + +/// Points at 1:1, not centred: drawing (x, y) lands at document (x, artboard height − y). +fn points() -> ImportOptions { + ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() } +} + +fn nodes(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| out.push(n.clone())); + out +} + +fn images(doc: &Document) -> Vec { + nodes(doc) + .into_iter() + .filter_map(|n| match n.kind { + NodeKind::Image(im) => Some(*im), + _ => None, + }) + .collect() +} + +/// Where image `im`'s pixel corner `(x, y)` lands. +fn at(im: &ImageObject, x: f64, y: f64) -> Point { + im.xf * Point::new(x, y) +} + +fn near(a: Point, b: Point) -> bool { + a.distance(b) < 1e-9 +} + +#[test] +fn an_image_comes_in_linked_to_its_file_with_its_top_left_pixel_at_the_top_left() { + let bytes = drawing(&image("1F", Some(("30", "10")), &[]), &def("1F", r"photos\scan.png")); + let r = import(&bytes, &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); + let doc = &r.document; + assert_eq!(doc.layers.iter().filter_map(|l| l.name.as_deref()).collect::>(), ["Photos"]); + let ims = images(doc); + assert_eq!(ims.len(), 1); + let im = &ims[0]; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(r"photos\scan.png")); + assert_eq!((im.width, im.height), (30, 10)); + // The drawing's 60 × 20 units from (10, 20): y up there, y down here. + let h = doc.artboards[0].rect.height(); + assert!(near(at(im, 0.0, 0.0), Point::new(10.0, h - 40.0)), "{:?}", at(im, 0.0, 0.0)); + assert!(near(at(im, 30.0, 10.0), Point::new(70.0, h - 20.0)), "{:?}", at(im, 30.0, 10.0)); + // Until its file is read it shows the placeholder. + assert!(doc.images.get(&im.key).is_some_and(ImageBlob::is_proxy)); +} + +#[test] +fn an_image_without_its_own_size_takes_its_file_s_and_two_images_of_one_file_share_its_data() { + let mut e = image("1F", None, &[]); + e.extend(image("1F", Some(("30", "10")), &[])); + let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document; + let ims = images(&doc); + assert_eq!(ims.iter().map(|im| (im.width, im.height)).collect::>(), [(30, 10), (30, 10)]); + assert_eq!(ims[0].key, ims[1].key); + assert_eq!(doc.images.len(), 1); +} + +#[test] +fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() { + // Pixels 5 to 14 across and 2 to 6 down: a 20 × 10 unit window. + let part = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]); + let r = import(&drawing(&part, &def("1F", "scan.png")), &points()).unwrap(); + let all = nodes(&r.document); + let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group"); + let children = group.children().unwrap(); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::Image(_))); + let h = r.document.artboards[0].rect.height(); + let clip = children[0].geometric_bounds().unwrap(); + // x 10 + 2·5 to 10 + 2·15; y down from the image's top (20 + 2·10) 2·2 to 2·7. + let want = Rect::new(20.0, h - 40.0 + 4.0, 40.0, h - 40.0 + 14.0); + assert!([(clip.x0, want.x0), (clip.y0, want.y0), (clip.x1, want.x1), (clip.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-9), "{clip:?}"); + // The default boundary, the whole image, makes no group; clipping off ignores a boundary. + let whole = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "9.5")]); + let off = image("1F", Some(("30", "10")), &[(280, "0"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]); + for e in [whole, off] { + let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document; + assert!(!nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })), "no clip group"); + assert_eq!(images(&doc).len(), 1); + } +} + +#[test] +fn a_clip_boundary_with_a_repeated_corner_still_clips_the_image() { + let boundary = image( + "1F", + Some(("30", "10")), + &[ + (280, "1"), + (71, "2"), + (91, "4"), + (14, "-0.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "-0.5"), + (14, "-0.5"), + (24, "-0.5"), + (14, "-0.5"), + (24, "9.5"), + ], + ); + let doc = import(&drawing(&boundary, &def("1F", "scan.png")), &points()).unwrap().document; + let all = nodes(&doc); + let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group"); + let children = group.children().unwrap(); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::Image(_))); +} + +#[test] +fn image_display_flags_control_clipping_only_when_present() { + for (display, clipping, clipped) in [(None, "1", true), (Some("9"), "1", false), (Some("13"), "1", true), (Some("13"), "0", false)] { + let mut boundary = vec![(280, clipping), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]; + if let Some(flags) = display { + boundary.push((70, flags)); + } + let e = image("1F", Some(("30", "10")), &boundary); + let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 1); + assert_eq!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), clipped, "{display:?}, {clipping}"); + } +} + +#[test] +fn images_requested_opaque_warn_once_and_other_images_do_not() { + for (display, opaque) in [(None, false), (Some("9"), false), (Some("1"), true), (Some("5"), true)] { + let flags: Vec<_> = display.map(|flags| (70, flags)).into_iter().collect(); + let mut e = image("1F", Some(("30", "10")), &flags); + e.extend(image("1F", Some(("30", "10")), &flags)); + let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 2); + let warnings: Vec<_> = r.warnings.iter().filter(|w| w.contains("opaque") && w.contains("transparency")).collect(); + assert_eq!(warnings.len(), usize::from(opaque), "{display:?}: {:?}", r.warnings); + } +} + +#[test] +fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_with_a_warning() { + let tri = image( + "1F", + Some(("30", "10")), + &[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")], + ); + let doc = import(&drawing(&tri, &def("1F", "scan.png")), &points()).unwrap().document; + let clip = nodes(&doc).into_iter().find(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).expect("a clip path"); + let NodeKind::Path { path, .. } = &clip.kind else { panic!("not a path") }; + let im = &images(&doc)[0]; + let mut corners: Vec = path.to_bezpath().elements().iter().filter_map(|el| el.end_point()).collect(); + // The path may draw its closing edge as a line back to the start. + if corners.len() > 1 && corners.first() == corners.last() { + corners.pop(); + } + assert_eq!(corners.len(), 3, "{corners:?}"); + for (c, (x, y)) in corners.iter().zip([(0.0, 0.0), (30.0, 0.0), (0.0, 10.0)]) { + assert!(near(*c, at(im, x, y)), "{c:?}"); + } + // The same triangle closed by repeating its first point still clips: three corners of the + // image's box and a repeat are not the box. + let closed = image( + "1F", + Some(("30", "10")), + &[ + (280, "1"), + (71, "2"), + (91, "4"), + (14, "-0.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "9.5"), + (14, "-0.5"), + (24, "-0.5"), + ], + ); + let doc = import(&drawing(&closed, &def("1F", "scan.png")), &points()).unwrap().document; + assert!(nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), "a clip group"); + // A clip point far out of range leaves the image out. + let far = image( + "1F", + Some(("30", "10")), + &[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")], + ); + let r = import(&drawing(&far, &def("1F", "scan.png")), &points()).unwrap(); + assert!(images(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let mut inverted = tri.clone(); + inverted.push((290, "1")); + let r = import(&drawing(&inverted, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(r.warnings.iter().any(|w| w.contains("inverted image clips")), "{:?}", r.warnings); +} + +#[test] +fn images_without_usable_file_references_do_not_expand_the_artboard() { + for objects in [def("1F", "scan.png"), def("2A", " ")] { + let mut far = image("2A", Some(("30", "10")), &[]); + for (code, value) in &mut far { + if *code == 10 || *code == 20 { + *value = "100000"; + } + } + let mut entities = vec![(0, "LINE"), (10, "0"), (20, "0"), (11, "100"), (21, "50")]; + entities.extend(far); + let r = import(&drawing(&entities, &objects), &points()).unwrap(); + assert!(images(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("name no image file")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. }))); + let board = r.document.artboards[0].rect; + assert!(board.width() < 1000.0 && board.height() < 1000.0, "{board:?}"); + } +} + +/// Entities, objects, and the warning they give. +type Case<'a> = (Vec<(i32, &'a str)>, Vec<(i32, &'a str)>, &'a str); + +#[test] +fn images_that_name_no_file_or_have_no_size_or_area_are_left_out_with_warnings() { + let cases: [Case; 4] = [ + (image("2A", Some(("30", "10")), &[]), def("1F", "scan.png"), "name no image file"), + (image("1F", Some(("30", "10")), &[]), def("1F", " "), "name no image file"), + (image("1F", Some(("0", "10")), &[]), vec![(0, "IMAGEDEF"), (5, "1F"), (1, "scan.png")], "no size in pixels"), + ( + vec![(0, "IMAGE"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "4"), (22, "0"), (13, "30"), (23, "10"), (340, "1F")], + def("1F", "scan.png"), + "no width or height", + ), + ]; + for (e, o, why) in cases { + let r = import(&drawing(&e, &o), &points()).unwrap(); + assert!(images(&r.document).is_empty(), "{why}"); + assert!(r.warnings.iter().any(|w| w.contains(why)), "{why}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "an IMAGE is not an unknown entity: {:?}", r.warnings); + } + // Brightness, contrast and fade are noted. + let faded = image("1F", Some(("30", "10")), &[(283, "40")]); + let r = import(&drawing(&faded, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 1); + assert!(r.warnings.iter().any(|w| w.contains("fade")), "{:?}", r.warnings); +} + +#[test] +fn an_image_whose_show_image_flag_is_off_is_hidden() { + let o = def("1F", "scan.png"); + for (flags, shown) in [("3", 1), ("1", 1), ("2", 0), ("0", 0)] { + let r = import(&drawing(&image("1F", Some(("30", "10")), &[(70, flags)]), &o), &points()).unwrap(); + assert_eq!(images(&r.document).len(), shown, "group 70 = {flags}"); + assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "{:?}", r.warnings); + } +} + +#[test] +fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_on_the_canvas() { + // The block's image sits 10,000,000 units out, and the insert moves it back next to the origin. + let tri = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + let mut far = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10000010"), (20, "20")]; + far.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + let head = far.len(); + far.extend_from_slice(&tri); + let block_of = |image: &[(i32, &'static str)]| { + let mut block = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]; + block.extend_from_slice(image); + block.push((0, "ENDBLK")); + block + }; + let insert = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-10000000"), (20, "0")]; + let r = import(&with_blocks(&block_of(&far), &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let art = &r.document.symbols.first().expect("a symbol").art; + assert!(matches!(art.kind, NodeKind::Group { clip: true, .. }), "{:?}", art.kind); + // A clip point far from its own image in the block still leaves the image out. + let mut farther = far[..head].to_vec(); + farther.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + let r = import(&with_blocks(&block_of(&farther), &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + // A wide image whose corner is far out, cropped to a part near the origin, comes in too. + let mut wide = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "-5000000"), (20, "0")]; + wide.extend([(11, "1000"), (21, "0"), (12, "0"), (22, "1000"), (13, "10000"), (23, "10"), (340, "1F")]); + wide.extend([(280, "1"), (71, "2"), (91, "3"), (14, "5200"), (24, "0"), (14, "5400"), (24, "0"), (14, "5200"), (24, "5")]); + let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&block_of(&wide), &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + assert!(r.document.symbols.first().is_some_and(|s| matches!(s.art.kind, NodeKind::Group { clip: true, .. }))); + // A block's image near the origin whose clip reaches out of range where the insert places it + // is left out with that warning, and the block's other art stays. + let mut reaching = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20")]; + reaching.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + reaching.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + reaching.extend([(0, "LINE"), (8, "Photos"), (10, "0"), (20, "0"), (11, "50"), (21, "50")]); + let r = import(&with_blocks(&block_of(&reaching), &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let placed = nodes(&r.document); + assert!(!placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Image(_)))); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's line"); + // The block's symbol has no instance left, so it is not kept with the image it holds. + assert!(r.document.symbols.is_empty(), "{:?}", r.document.symbols.iter().map(|s| &s.name).collect::>()); +} + +#[test] +fn a_symbol_that_only_placements_drawn_as_art_use_is_not_charged_twice() { + // Block B holds a 600,000-point polyline and an image whose clip reaches out of range where an + // insert at the origin places it, so that insert draws B's art instead of an instance. + let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]; + owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]); + owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]); + owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]); + owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into())]); + owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]); + for i in 0..600_000 { + owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]); + } + owned.push((0, "ENDBLK".into())); + let block: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&block, &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + // 1,200,000 points if the unused symbol stayed charged: past the tests' limit of 1,000,000. + assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's polyline"); + assert!(r.document.symbols.is_empty()); + // A second insert that places B in range makes the symbol again, which is charged again: its + // polyline no longer fits, and the first insert's stays. + let both = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-2000000"), (20, "0")]; + let r = import(&with_blocks(&block, &both, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + let placed = nodes(&r.document); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the first insert's polyline"); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the second insert's instance"); + assert_eq!(r.document.symbols.len(), 1); +} + +#[test] +fn a_symbol_that_only_a_removed_symbol_placed_is_removed_with_it() { + // Block B holds a 600,000-point polyline and an image whose clip reaches out of range where the + // drawing's insert of block A, which places B, puts it. That insert draws A's art and removes + // A's symbol; B's symbol, which only A's art placed, goes too, so drawing B's art fits. + let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]; + owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]); + for i in 0..600_000 { + owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]); + } + owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]); + owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]); + owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]); + owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into()), (0, "ENDBLK".into())]); + owned.extend([(0, "BLOCK".into()), (2, "A".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]); + owned.extend([(0, "INSERT".into()), (8, "Photos".into()), (2, "B".into()), (10, "0".into()), (20, "0".into()), (0, "ENDBLK".into())]); + let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&blocks, &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "B's polyline"); + assert!(r.document.symbols.is_empty()); +} + +/// Block B holds an image clipped by a triangle with a corner at (`far`, −0.5) in pixel space, and +/// block A places B by `inner` beside an image of its own clipped near it; the drawing places A +/// at the origin scaled by `outer`. +fn nested(far: &'static str, inner: &[(i32, &'static str)], outer: &'static str) -> Vec { + let clipped = |x: &'static str, corner: &'static str| { + let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, x), (20, "20")]; + e.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + e.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, corner), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + e + }; + let mut blocks = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend(clipped("10", far)); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "A"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]); + blocks.extend_from_slice(inner); + blocks.extend(clipped("100", "29.5")); + blocks.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0"), (41, outer), (42, outer)]; + with_blocks(&blocks, &insert, &def("1F", "scan.png")) +} + +#[test] +fn a_block_s_clip_point_beyond_any_usable_range_leaves_its_image_out_even_where_inserts_scale_it_back() { + // B's clip corner is 2e19 units out in its own space, and two inserts at the smallest scale + // would bring it back next to the origin. + let r = import(&nested("1e19", &[(41, "1e-12"), (42, "1e-12")], "1e-12"), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let mut held = 0; + for s in &r.document.symbols { + s.art.walk(&mut |n: &Node| held += usize::from(matches!(n.kind, NodeKind::Image(_)))); + } + assert_eq!(held + images(&r.document).len(), 1, "A's own image"); +} + +#[test] +fn a_clip_reach_placed_by_an_overflowing_transform_is_unbounded() { + use super::build::placed_reach; + let out = |b: Rect| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()); + // Across, the terms of every corner overflow with opposite signs to NaN, which a union with + // another symbol's reach would drop; the reach is unbounded instead. + let h = 1e300; + let xf = Affine::new([h, 1.0, -h, 1.0, 0.0, 0.0]); + let r = Rect::new(1e10, 1e10, 2e10, 2e10); + let near = Rect::new(0.0, 0.0, 10.0, 10.0); + let whole = placed_reach(xf, r); + assert!(out(whole.union(near)), "{whole:?}"); + // An unbounded reach stays unbounded wherever it is placed. + assert!(out(placed_reach(Affine::scale(1e-12), whole).union(near))); + assert!(out(placed_reach(Affine::IDENTITY, whole).union(near))); + // A placement that stays finite is the box of the placed corners. + let b = placed_reach(Affine::new([0.0, 1.0, -1.0, 0.0, 5.0, 0.0]), near); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (-5.0, 0.0, 5.0, 10.0)); +} + +#[test] +fn clip_paths_count_against_the_path_point_limit() { + // A 1,000-point clip in an anonymous block placed 1,100 times: 1,001,000 path elements, past + // the tests' limit of 1,000,000. + let mut clip: Vec<(i32, String)> = vec![(280, "1".into()), (71, "2".into()), (91, "1000".into())]; + for i in 0..1000 { + let a = f64::from(i) * std::f64::consts::TAU / 1000.0; + clip.extend([(14, format!("{}", 14.5 + 10.0 * a.cos())), (24, format!("{}", 4.5 + 4.0 * a.sin()))]); + } + let clip: Vec<(i32, &str)> = clip.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let mut block = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + block.extend(image("1F", Some(("30", "10")), &clip)); + block.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "1100"), (44, "100")]; + let r = import(&with_blocks(&block, &insert, &def("1F", "scan.png")), &points()).unwrap(); + let clips = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).count(); + assert!((900..1000).contains(&clips), "{clips} clip paths"); + assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); +} + +#[test] +fn an_insert_drawn_as_art_gets_back_its_unused_symbol_s_objects_at_the_object_limit() { + // Block B holds a line and an image whose clip reaches out of range where B's insert places + // it: 4 objects as a symbol. 99,996 lines before it leave exactly room for that symbol under + // the tests' limit of 100,000 objects, so its insert draws B's art in the room the unused + // symbol gives back. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + blocks.push((0, "ENDBLK")); + // An insert makes at most 10,000 copies: nine of 100 × 100 and one of 84 × 119. + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("84", "119")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + let lines = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).count(); + assert_eq!(lines, 99_997, "the lines and B's line"); + assert!(r.document.symbols.is_empty()); +} + +#[test] +fn copies_drawn_as_art_past_the_object_limit_stop_without_looking_at_the_block() { + // Block B: 200 lines and an image whose clip reaches out of range unless its copy sits left of + // the origin. 99,796 lines, B's symbol and the first copy's instance fill the tests' limit of + // 100,000 objects; the next 9,999 copies would each look at B's 201 items, past the tests' + // block-work limit of 1,000,000. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + for _ in 0..200 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + } + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + blocks.push((0, "ENDBLK")); + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("79", "124")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-35"), (20, "0"), (70, "10000"), (44, "10")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn copies_of_a_symbol_taken_out_at_the_object_limit_are_not_drawn_again() { + // Block B: an image whose clip reaches out of range only for the first copy, and 200 lines. + // 99,800 lines and the first copy, drawn as art in the room its unused symbol gives back, + // fill the tests' limit of 100,000 objects; each of the next 9,999 copies would draw the + // symbol again from B's 201 items, past the tests' block-work limit of 1,000,000. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + for _ in 0..200 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + } + blocks.push((0, "ENDBLK")); + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("98", "100")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-25"), (20, "0"), (70, "10000"), (44, "-10")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +/// A document with a 4 × 2 pixel image, 5 pt pixels, its top-left corner at (10, 20). +fn image_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 0, 255, 255].repeat(8), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = Document::new(200.0, 100.0); + let layer = d.add_layer(Some("Photos")); + let im = ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.insert(Some(layer), usize::MAX, n).unwrap(); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }); + d +} + +/// Import `bytes`, written from [`image_doc`], and check its one image: linked to `name`, the file +/// the export wrote, and the size and way up it had. +fn written_and_read(bytes: &[u8], name: &str) { + let doc = import(bytes, &points()).unwrap().document; + let ims = images(&doc); + assert_eq!(ims.len(), 1, "{:?}", nodes(&doc).iter().map(|n| &n.kind).collect::>()); + let im = &ims[0]; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(name)); + assert_eq!((im.width, im.height), (4, 2)); + // 20 × 10 pt with the top-left pixel at the top-left, as it was. + let (tl, br) = (at(im, 0.0, 0.0), at(im, 4.0, 2.0)); + assert!((br.x - tl.x - 20.0).abs() < 1e-6 && (br.y - tl.y - 10.0).abs() < 1e-6, "{tl:?} {br:?}"); +} + +#[test] +fn an_image_the_export_wrote_comes_back_linked_to_the_file_it_wrote() { + let d = image_doc(); + let out = crate::export(&d, &DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }).unwrap(); + assert_eq!(out.images.len(), 1); + written_and_read(&out.bytes, &out.images[0].name); +} + +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn an_image_in_a_dwg_drawing_comes_in_as_in_its_dxf() { + let d = image_doc(); + let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }; + let out = crate::export(&d, &o).unwrap(); + crate::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&out.bytes, "AC1018").unwrap(); + written_and_read(&dwg, &out.images[0].name); +} diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 10adb09199..ebd2671ae2 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -15,6 +15,8 @@ spine-count = [] symbol-read-count = [] # `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only). locked-artboard-count = [] +# `vectorcraft_doc::swatches::swatch_scans` for other crates' tests (dev-dependencies only). +swatch-scans = [] [dependencies] vectorcraft-geom = { workspace = true } @@ -39,3 +41,6 @@ flate2 = { workspace = true } zune-jpeg = { workspace = true } jpeg-encoder = { workspace = true } proptest = { workspace = true } +# The counter vectorcraft-ui-egui's tests turn on, also when this crate is tested without +# vectorcraft-ui-egui (`cargo xtask ci shard`). +vectorcraft-doc = { path = ".", features = ["swatch-scans"] } diff --git a/crates/doc/src/corners.rs b/crates/doc/src/corners.rs index 56bbb29845..a4f4a683d6 100644 --- a/crates/doc/src/corners.rs +++ b/crates/doc/src/corners.rs @@ -6,8 +6,9 @@ use std::borrow::Cow; use std::collections::BTreeSet; use vectorcraft_geom::corners::{Corner, cut_corners, fitted_radii, path_corners}; +use vectorcraft_geom::kurbo::ParamCurveNearest; use vectorcraft_geom::shapes::{self, CornerKind}; -use vectorcraft_geom::{Affine, PathData, Point, Rect}; +use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, SubPath}; use crate::node::{LiveShape, Node, NodeKind}; use crate::selection::AnchorRef; @@ -198,6 +199,46 @@ impl<'a> LiveCorners<'a> { &self.sources } + /// Whether any corner has a radius stored, so the path as drawn has its corners cut (or + /// cuts them again when an edit bends a straightened corner back). + pub fn is_cut(&self) -> bool { + self.radii.iter().any(|r| *r > 0.0) + } + + /// The anchors of `base` (subpath, anchor) that `anchors` of the path as drawn come from. + pub fn outline_anchors(&self, anchors: &BTreeSet) -> BTreeSet { + let ks: BTreeSet = anchors.iter().filter_map(|(si, ai)| self.sources.get(*si)?.get(*ai).copied()).collect(); + let mut out = BTreeSet::new(); + let mut first = 0; + for (si, sp) in self.base.subpaths.iter().enumerate() { + out.extend(ks.range(first..first + sp.anchors.len()).map(|k| (si, k - first))); + first += sp.anchors.len(); + } + out + } + + /// The first anchor of the path as drawn that anchor `(si, ai)` of `base` gives. + pub fn drawn_anchor(&self, (si, ai): AnchorRef) -> Option { + let first: usize = self.base.subpaths.get(..si)?.iter().map(|sp| sp.anchors.len()).sum(); + let k = first + ai; + self.sources.get(si)?.iter().position(|s| *s == k).map(|drawn| (si, drawn)) + } + + /// [`LiveCorners::drawn_anchor`] of each of `anchors`, counting the subpaths' anchors once. + pub fn drawn_anchors(&self, anchors: &BTreeSet) -> BTreeSet { + let mut out = BTreeSet::new(); + let mut first = 0; + for (si, sp) in self.base.subpaths.iter().enumerate() { + let Some(sources) = self.sources.get(si) else { break }; + for &(_, ai) in anchors.range((si, 0)..(si + 1, 0)) { + let k = first + ai; + out.extend(sources.iter().position(|s| *s == k).map(|drawn| (si, drawn))); + } + first += sp.anchors.len(); + } + out + } + /// The radius and kind `corners` share (each `None` when they differ, or for no corners). /// Radius is what was set ([`LiveCorners::radius`]: document lengths, or a fraction in 0..1 /// when [`LiveCorners::radii_relative`]), not the fitted draw size ([`LiveCorners::drawn_radius`]). @@ -325,13 +366,8 @@ pub fn edit_corner_anchors( anchors: &BTreeSet, edit: impl FnOnce(&mut PathData, &BTreeSet), ) -> Option<()> { - live.as_ref()?; - if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() { - let [a, b, c, d, _, _] = xf.as_coeffs(); - let scale = (a * a + b * b).max(c * c + d * d).max(1e-12); - if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale { - return None; - } + if live.as_deref().is_none_or(uneven_rectangle) { + return None; } let (mut base, moved, mut radii, kinds, relative) = { let lc = LiveCorners::new(path, live.as_deref())?; @@ -369,6 +405,156 @@ pub fn edit_corner_anchors( Some(()) } +/// Whether `live` is a rectangle whose transform shears it or scales it unevenly. +fn uneven_rectangle(live: &LiveShape) -> bool { + let LiveShape::Rectangle { xf, .. } = live else { return false }; + let [a, b, c, d, _, _] = xf.as_coeffs(); + let scale = (a * a + b * b).max(c * c + d * d).max(1e-12); + ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale +} + +/// Change the anchors of the uncut outline of a path with cut Live Corners and cut the corners +/// again. `edit` gets the outline in document space and returns, for each of its anchors after +/// the change, the index of the anchor before the change it is (`None` for an anchor it added). +/// Each corner keeps its radius and kind, and an added anchor has none; relative radii keep their +/// document lengths. A live rectangle or polygon becomes a [`LiveShape::Path`] with that outline, +/// and a path left with no radius and no corner kind other than round (or with no anchor) is a +/// plain path. Returns `None`, leaving the path unchanged, as [`edit_corner_anchors`] does, or when +/// `edit` returns `None` or does not list one entry per anchor. +fn rebuild_corner_outline( + path: &mut PathData, + live: &mut Option>, + edit: impl FnOnce(&mut PathData) -> Option>>, +) -> Option<()> { + if live.as_deref().is_none_or(uneven_rectangle) { + return None; + } + let (mut base, lengths, kinds, relative) = { + let lc = LiveCorners::new(path, live.as_deref())?; + if !lc.is_cut() { + return None; + } + let base = lc.base.transformed(lc.xf); + let mut radii = lc.radii.clone(); + radii.resize(base.anchor_count(), 0.0); + let lengths = if lc.relative { + let mut l = LiveShape::Path { base: base.clone(), radii, kinds: vec![], radii_relative: true }; + convert_radii_relative(&mut l, false); + let LiveShape::Path { radii, .. } = l else { return None }; + radii + } else { + radii + }; + (base, lengths, lc.kinds.clone(), lc.relative) + }; + let from = edit(&mut base)?; + if from.len() != base.anchor_count() { + return None; + } + let radii: Vec = from.iter().map(|f| f.and_then(|i| lengths.get(i).copied()).unwrap_or(0.0)).collect(); + let kinds: Vec = from.iter().map(|f| f.and_then(|i| kinds.get(i).copied()).unwrap_or_default()).collect(); + if radii.iter().all(|r| *r <= 0.0) && kinds.iter().all(|k| *k == CornerKind::Round) { + *path = base; + *live = None; + return Some(()); + } + let mut l = LiveShape::Path { base, radii, kinds, radii_relative: false }; + convert_radii_relative(&mut l, relative); + *path = l.to_path(); + *live = Some(Box::new(l)); + Some(()) +} + +/// Add an anchor at `t` (0..1) on segment `seg` of subpath `si` of a path with cut Live Corners: +/// it goes on the side of the uncut outline that the segment is part of, at the point of the +/// segment at `t`, and the corners are cut again, keeping their radii and kinds +/// ([`rebuild_corner_outline`]). Returns the new anchor's index in subpath `si` of the path as +/// drawn, or `None`, leaving the path unchanged, for a segment that is a corner's cut, a segment +/// that does not exist, or a path [`edit_corner_anchors`] leaves as it is. +pub fn insert_corner_anchor(path: &mut PathData, live: &mut Option>, si: usize, seg: usize, t: f64) -> Option { + let (target, first, local) = { + let lc = LiveCorners::new(path, Some(live.as_deref()?))?; + let sp = path.subpaths.get(si)?; + let from = lc.sources.get(si)?; + if seg >= sp.segment_count() || from.len() != sp.anchors.len() { + return None; + } + let (ka, kb) = (*from.get(seg)?, *from.get((seg + 1) % from.len())?); + // Both ends from one corner: the segment is that corner's cut. + if ka == kb { + return None; + } + let first: usize = lc.base.subpaths.get(..si)?.iter().map(|s| s.anchors.len()).sum(); + let outline = lc.base.subpaths.get(si)?; + let local = ka.checked_sub(first).filter(|a| *a < outline.anchors.len())?; + if !outline.has_segment(local, true) || kb != first + (local + 1) % outline.anchors.len() { + return None; + } + (sp.segment(seg).eval(t.clamp(0.0, 1.0)), first, local) + }; + let new_index = first + local + 1; + let (mut p, mut l) = (path.clone(), live.clone()); + rebuild_corner_outline(&mut p, &mut l, |base| { + let sp = base.subpaths.get_mut(si)?; + // A straight side is a cubic with its handles on its ends too, so the parameter of the + // point nearest `target` puts the new anchor there on either kind of side. + let tb = sp.segment(local).nearest(target, 1e-9).t; + sp.insert_anchor(local, tb.clamp(0.0, 1.0)); + Some((0..base.anchor_count()).map(|j| if j < new_index { Some(j) } else { (j > new_index).then(|| j - 1) }).collect()) + })?; + let drawn = match LiveCorners::new(&p, l.as_deref()) { + Some(lc) => lc.sources.get(si)?.iter().position(|k| *k == new_index)?, + None => local + 1, + }; + *path = p; + *live = l; + Some(drawn) +} + +/// Remove the anchors of the uncut outline that `anchors` (of the path as drawn) come from, so a +/// cut corner goes when either of its anchors is removed, and cut the remaining corners again, +/// keeping their radii and kinds ([`rebuild_corner_outline`]). `remove` takes the listed anchors +/// (in ascending order) out of one subpath of the outline, refitting the curve round each; a +/// subpath left with fewer than two anchors is removed, and a path left with none is an empty plain +/// path. Returns `None`, leaving the path unchanged, when no anchor maps to the outline, when +/// `remove` does not remove exactly the anchors listed, or for a path [`edit_corner_anchors`] +/// leaves as it is. +pub fn remove_corner_anchors( + path: &mut PathData, + live: &mut Option>, + anchors: &BTreeSet, + mut remove: impl FnMut(&mut SubPath, &[usize]), +) -> Option<()> { + let outline = LiveCorners::new(path, Some(live.as_deref()?))?.outline_anchors(anchors); + if outline.is_empty() { + return None; + } + let (mut p, mut l) = (path.clone(), live.clone()); + rebuild_corner_outline(&mut p, &mut l, |base| { + let mut from = vec![]; + let mut first = 0; + for (si, sp) in base.subpaths.iter_mut().enumerate() { + let n = sp.anchors.len(); + let gone: Vec = outline.range((si, 0)..=(si, usize::MAX)).map(|&(_, ai)| ai).collect(); + if !gone.is_empty() { + remove(sp, &gone); + if sp.anchors.len() + gone.len() != n { + return None; + } + } + if sp.anchors.len() >= 2 { + from.extend((0..n).filter(|ai| gone.binary_search(ai).is_err()).map(|ai| Some(first + ai))); + } + first += n; + } + base.subpaths.retain(|sp| sp.anchors.len() >= 2); + Some(from) + })?; + *path = p; + *live = l; + Some(()) +} + #[cfg(test)] mod tests { use super::*; @@ -431,6 +617,21 @@ mod tests { assert_eq!((path, live), (star, None)); } + /// Mapping a set of outline anchors gives the same anchors as drawn as mapping each one. + #[test] + fn drawn_anchors_match_drawn_anchor_across_subpaths() { + let mut star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0); + star.subpaths.extend(shapes::star(Point::new(300.0, 100.0), 50.0, 25.0, 4, 0.0).subpaths); + let (mut path, mut live) = (star, None); + set_corners(&mut path, &mut live, &set(&[0, 2, 10, 13]), Some(5.0), None); + let c = LiveCorners::new(&path, live.as_deref()).unwrap(); + let refs: BTreeSet = (0..3).flat_map(|si| (0..12).map(move |ai| (si, ai))).collect(); + let one_by_one: BTreeSet = refs.iter().filter_map(|r| c.drawn_anchor(*r)).collect(); + assert_eq!(one_by_one.len(), 18, "ten and eight outline anchors"); + assert_eq!(c.drawn_anchors(&refs), one_by_one); + assert_eq!(c.drawn_anchors(&BTreeSet::from([(1, 3)])), BTreeSet::from([(1, c.drawn_anchor((1, 3)).unwrap().1)])); + } + /// A polygon's corners are cut in the document and survive a change of sides when shared. #[test] fn polygon_corners_follow_their_sides() { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7bddc2c482..5466d2122b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -103,7 +103,7 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use compound_shape::ShapeMode; -pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii}; +pub use corners::{LiveCorners, edit_corner_anchors, insert_corner_anchor, rebase_relative_radii, remove_corner_anchors}; pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, @@ -119,7 +119,7 @@ pub use node::Knockout; pub use node::Scaling; pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3a4b2abd03..2fdb579ee1 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -25,7 +25,9 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use attributes::{ + ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies, +}; #[cfg(test)] pub(crate) use changed::COUNTERPART_LOOKUPS; pub use changed::changed_nodes; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 67d3d02308..62edeb3795 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -3,7 +3,7 @@ use super::live_shape::LiveShape; use super::{Deserialize, Node, Serialize}; /// Window → Attributes: an object's settings that don't change how it prints. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ObjectAttributes { /// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]). @@ -45,6 +45,34 @@ pub struct ObjectAttributes { pub tags: Vec, } +impl Clone for ObjectAttributes { + fn clone(&self) -> Self { + ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1)); + Self { + show_center: self.show_center, + image_map: self.image_map, + url: self.url.clone(), + note: self.note.clone(), + data: self.data.clone(), + events: self.events.clone(), + classes: self.classes.clone(), + foreign: self.foreign.clone(), + tags: self.tags.clone(), + } + } +} + +thread_local! { + /// [`attribute_copies`] of this thread. + static ATTRIBUTE_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold +/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes. +pub fn attribute_copies() -> u64 { + ATTRIBUTE_COPIES.get() +} + /// The most tags one object has. pub const MAX_TAGS: usize = 64; diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 0ee84dc32c..a9bbc30c04 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -16,6 +16,23 @@ use vectorcraft_color::{Color, Paint, Swatch, tint_percent}; use crate::{AppearanceItem, Document, Node, NodeId, NodeKind}; +#[cfg(any(test, feature = "swatch-scans"))] +thread_local! { + /// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by + /// name on this thread. + static SWATCH_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by +/// name on this thread, for other crates' tests that count how much work their lookups by name do (the +/// `swatch-scans` feature, dev-dependencies only). A lookup compares the swatches up to the one it finds, or all of +/// them for a name the document does not hold. +#[cfg(any(test, feature = "swatch-scans"))] +#[doc(hidden)] +pub fn swatch_scans() -> usize { + SWATCH_SCANS.with(std::cell::Cell::get) +} + impl Document { /// Every swatch: the ungrouped ones first, then each colour group's in order. pub fn swatches_iter(&self) -> impl Iterator { @@ -27,7 +44,12 @@ impl Document { /// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`]) /// included. pub fn swatch(&self, name: &str) -> Option<&Swatch> { - self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration)) + let found = self.swatches_iter().find(|s| { + #[cfg(any(test, feature = "swatch-scans"))] + SWATCH_SCANS.with(|c| c.set(c.get() + 1)); + s.name == name + }); + found.or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration)) } pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> { self.swatches_iter_mut().find(|s| s.name == name) @@ -74,7 +96,12 @@ impl Document { } /// Is `name` used by a swatch or a colour group (they share one namespace)? pub fn swatch_name_taken(&self, name: &str) -> bool { - self.swatch(name).is_some() || self.swatch_groups.iter().any(|g| g.name == name) + self.swatch(name).is_some() + || self.swatch_groups.iter().any(|g| { + #[cfg(any(test, feature = "swatch-scans"))] + SWATCH_SCANS.with(|c| c.set(c.get() + 1)); + g.name == name + }) } /// `base`, or the first of "base 2", "base 3"… no swatch or colour group uses. pub fn free_swatch_name(&self, base: &str) -> String { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 2487dcd01d..a06b163888 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,11 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"] # feature still recognizes the files and refuses them with a message. The apps list it beside # `bundled-fonts`. heif = ["dep:heic-rs", "dep:rayon"] +# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges +# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm` +# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in +# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`). +cgm = ["vectorcraft-metafile/cgm"] [dependencies] craft-codepage = { workspace = true } diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 9fa5806c52..8fcbd68e8a 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -16,6 +16,10 @@ mod shapes; mod typetools; mod units; +pub(crate) use color::screen_marks::{ + LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer, + managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks, +}; pub(crate) use image::{DecodedImages, refresh_color_masks}; pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8dff9593e9..99b7b355f5 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -4,15 +4,17 @@ //! 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, 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, and Randomize Fill Colors -//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu, -//! Object › Plug-ins › Color Effects, are the UI's. +//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks +//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, Apply +//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and +//! Randomize Fill Colors ([`random_fill`]) gives each filled path its own color at random. Its +//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; mod print_fixes; mod random_fill; +pub mod screen_marks; #[cfg(test)] mod tests; @@ -106,6 +108,7 @@ pub fn specs() -> Vec { ] .into_iter() .chain(legend::specs()) + .chain(screen_marks::specs()) .collect() } diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs new file mode 100644 index 0000000000..f5f58b2571 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -0,0 +1,515 @@ +//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects › +//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an +//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot +//! inks (each name in its own ink) and give the file name with the date and time. The marks are +//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the +//! stack, so they print and export with the rest. Running it again replaces that artboard's marks, +//! in one undo step, and makes none when the marks would come out the same. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, Point, Rect, shapes}; + +use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param}; +use crate::{DocState, Result, Session}; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.color.screenMarks", + "Create Screen Print Marks", + ["Object", "Plug-ins", "Color Effects"], + None, + "{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}", + has_doc, + screen_marks + )] +} + +/// The command. +pub const COMMAND: &str = "addon.color.screenMarks"; + +/// Where a target can go, in the order the command draws them. +pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"]; +/// The targets drawn when `positions` is left out. +pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"]; +/// The name of the layer the marks go on, and of each artboard's group. +pub const LAYER_NAME: &str = "Screen Print Marks"; +/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id). +pub const KEY: &str = "vc-screen-print-marks"; +/// Most spot inks one line names. +const MAX_INKS: usize = 256; + +fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive) -> Result { + match p.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && range.contains(n)) + .ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))), + } +} + +/// One of `options` for `key`, else `default`. +fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> { + match text_param(p, key, COMMAND)? { + None => Ok(default), + Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))), + } +} + +/// The target positions `p` asks for, in [`POSITIONS`] order. +fn positions(p: &Value) -> Result> { + let asked: Vec<&str> = match p.get("positions") { + None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::>()? + } + Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")), + }; + for (i, w) in asked.iter().enumerate() { + if !POSITIONS.contains(w) { + return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", ")))); + } + if asked[..i].contains(w) { + return Err(bad(COMMAND, format!("`positions` names `{w}` twice"))); + } + } + Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect()) +} + +/// The paint of ink `name`: [Registration], or a spot swatch linked to it. +fn ink_paint(doc: &Document, name: &str) -> Result { + if name == REGISTRATION { + return Ok(Paint::registration()); + } + let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?; + if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() { + return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch"))); + } + super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e)) +} + +/// The document's spot inks in panel order, each with the paint that links to it: spot color +/// swatches that are not tints, [Registration] left out. +fn spot_inks(doc: &Document) -> Vec<(String, Paint)> { + doc.swatches_iter() + .filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some()) + .map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone()))) + .collect() +} + +/// The index of the view's active artboard: when the document no longer has it, the one the +/// document opened on, else the first. +fn active_artboard(st: &DocState) -> Option { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0)) +} + +/// The settings every artboard's marks are drawn with. +struct Marks { + positions: Vec<&'static str>, + size: f64, + weight: f64, + inset: f64, + ink: Paint, + /// The lines of type, top to bottom: each a list of (text, fill) runs. + lines: Vec>, + style: CharStyle, + system_layout: bool, + top: bool, + left: bool, +} + +impl Marks { + /// The center of the target at `position` on artboard `r`. + fn center(&self, r: Rect, position: &str) -> Point { + let near = self.inset + self.size / 2.0; + let x = if position.ends_with("Left") || position == "left" { + r.x0 + near + } else if position.ends_with("Right") || position == "right" { + r.x1 - near + } else { + r.center().x + }; + let y = if position.starts_with("top") { + r.y0 + near + } else if position.starts_with("bottom") { + r.y1 - near + } else { + r.center().y + }; + Point::new(x, y) + } + + /// The target at `c`: a circle half the target's width and a cross the target's width, stroked. + fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node { + let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight); + let (half, ring) = (self.size / 2.0, self.size / 4.0); + let paths = [ + shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)), + shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)), + shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)), + ]; + let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect(); + let mut g = Node::group(alloc(), children); + g.name = Some("Registration Target".into()); + g + } + + /// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or + /// its bottom corner there when `from_bottom`, with its box. + fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) { + let runs: Vec = runs + .iter() + .map(|(text, fill)| { + let mut style = self.style.clone(); + style.fill = fill.clone(); + style.stroke = Paint::None; + TextRun::new(text.clone(), style) + }) + .collect(); + let mut t = TextObject::point(Point::ZERO, "", self.style.clone()); + t.runs = runs; + t.para = super::super::super::create::new_type_para(); + t.system_layout = self.system_layout; + super::super::super::typecmd::refresh_bounds(&mut t); + let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2)); + let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 }; + let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 }; + t.xf = Affine::translate((dx, dy)); + (t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy)) + } + + /// The lines placed in a column from `y`, at `x`: down from `y` at the top, up + /// from it at the bottom. Each with its box. + fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> { + let gap = self.style.size * 0.25; + let mut placed = Vec::with_capacity(self.lines.len()); + if self.top { + for runs in &self.lines { + let (t, b) = self.line(runs, Point::new(x, y), false); + y += b.height() + gap; + placed.push((t, b)); + } + } else { + for runs in self.lines.iter().rev() { + let (t, b) = self.line(runs, Point::new(x, y), true); + y -= b.height() + gap; + placed.insert(0, (t, b)); + } + } + placed + } + + /// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last). + fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node { + let mut children: Vec> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect(); + if !self.lines.is_empty() { + // The lines start past a target in the corner they start from. + let corner = match (self.top, self.left) { + (true, true) => "topLeft", + (true, false) => "topRight", + (false, true) => "bottomLeft", + (false, false) => "bottomRight", + }; + let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 }; + let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip }; + let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) }; + let mut placed = self.column(x, edge + sign * self.inset); + // Lines that would cross the center target on their side move in past it, unless they + // would then cross another target or leave the artboard. + let side = if self.top { "top" } else { "bottom" }; + // A target's paint: its two bars and the box of its ring, each with half the stroke weight. + let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0); + let crosses = |placed: &[(TextObject, Rect)], w: &str| { + let c = self.center(r, w); + let paint = [ + Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2), + Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2), + Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring), + ]; + placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0)) + }; + if self.positions.contains(&side) && crosses(&placed, side) { + let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25)); + if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) { + placed = moved; + } + } + children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t)))))); + } + let mut g = Node::group(alloc(), children); + g.name = Some(LAYER_NAME.into()); + g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string()))); + g + } +} + +/// The marks layer: the top-level layer whose data says so. +fn marks_layer(doc: &Document) -> Option<&Arc> { + doc.layers.iter().find(|l| tag(l) == Some("layer")) +} + +/// What `n`'s data holds under [`KEY`]. +fn tag(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// The id of the artboard marks group `n` belongs to, from its data. +fn owner(n: &Node) -> Option { + tag(n)?.parse().ok() +} + +/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to. +pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap { + marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect() +} + +/// The id of the marks layer of `d`, when it has one. +pub(crate) fn layer_id(d: &Document) -> Option { + marks_layer(d).map(|l| l.id) +} + +/// Is `n` the marks group of one of the artboards with ids `boards`? +pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool { + owner(n).is_some_and(|o| boards.contains(&o)) +} + +/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order, +/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the +/// marks layer is locked or hidden, only with `locked_and_hidden`. +pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> { + let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden)); + let kids = layer.and_then(|l| l.children()).into_iter().flatten(); + kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect() +} + +/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data +/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call +/// it on each copy they make. → whether `n` was such a group. +pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool { + if owner(n) != Some(from) { + return false; + } + let (from, to) = (from.to_string(), to.to_string()); + n.edit_attrs(|a| { + for (k, v) in a.data.iter_mut() { + if k == KEY && *v == from { + v.clone_from(&to); + } + } + }); + true +} + +/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened +/// again can give a new artboard one of those ids, and its marks are drawn afresh. +pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet) { + // Groups moved off the marks layer keep their tag and count too. + let mut groups: Vec = vec![]; + for l in &d.layers { + l.walk(&mut |n: &Node| { + if owner(n).is_some_and(|o| gone.contains(&o)) { + groups.push(n.id); + } + }); + } + for id in groups { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY)); + } + } +} + +/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard, +/// the marks layer, when the document has none. +pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) { + if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) { + return; + } + if let Some(l) = d.node_mut(layer) { + l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into()))); + } +} + +/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way. +fn without_ids(n: &Node) -> Node { + let mut n = n.clone(); + n.id = NodeId(0); + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(without_ids(c)); + } + } + n +} + +fn screen_marks(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let positions = positions(p)?; + let size = number(p, "size", 36.0, 4.0..=1000.0)?; + let weight = number(p, "weight", 1.0, 0.1..=20.0)?; + let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?; + let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?; + let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top"; + let left = choice(p, "textAlign", ["left", "right"], "left")? == "left"; + let want_inks = switch_or(p, "inks", false, C)?; + let want_info = switch_or(p, "info", false, C)?; + let all = switch_or(p, "allArtboards", false, C)?; + let given_time = date_param(p, "time", C)?; + let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string(); + // Defaults are for values left out; only `time` takes null (no date). + if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) { + return Err(bad(C, format!("`{key}` must not be null: leave it out for the default"))); + } + let artboard = index_opt(p, "artboard", C)?; + if all && artboard.is_some() { + return Err(bad(C, "give `artboard` or `allArtboards`, not both")); + } + // The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one; + // recorded actions leave it out and use the active artboard when played. + let recorded = index_opt(p, "activeArtboard", C)?; + let artboard = match artboard { + None if !all => { + let i = match recorded { + Some(i) => Some(i), + None => active_artboard(s.doc()?), + }; + if let Some(i) = i { + s.note_journal("activeArtboard", json!(i)); + } + i + } + given => given, + }; + let st = s.doc()?; + let doc = &st.doc; + if doc.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + let boards: Vec<(Rect, u32)> = if all { + doc.artboards.iter().map(|a| (a.rect, a.id)).collect() + } else { + let i = artboard.unwrap_or(0); + let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?; + vec![(a.rect, a.id)] + }; + let ink = ink_paint(doc, &ink_name)?; + let inks = if want_inks { spot_inks(doc) } else { vec![] }; + if inks.len() > MAX_INKS { + return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks"))); + } + let file = st + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).file_name()) + .map(|f| f.to_string_lossy().into_owned()) + .unwrap_or_else(|| doc.title.clone()); + let system_layout = doc.setup.system_layout; + if positions.is_empty() && inks.is_empty() && !want_info { + let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" }; + return Err(bad(C, format!("nothing to draw: {why}"))); + } + let mut lines: Vec> = vec![]; + if !inks.is_empty() { + let last = inks.len() - 1; + lines.push( + inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(), + ); + } + if want_info { + let date = clock_date(s, "time", given_time).map(|t| { + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC") + }); + let text = match date { + Some(date) => format!("{file} {date}"), + None => file, + }; + lines.push(vec![(text, ink.clone())]); + } + let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?; + let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left }; + let names: Vec = inks.into_iter().map(|(name, _)| name).collect(); + + // The marks as they would come out, to tell whether anything changes. + let st = s.doc()?; + let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default())); + let drawn: Vec = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect(); + // Only the stroked targets reach past their paths, by half the target weight. The lines of type + // have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well. + let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD); + let beyond = |n: &Node| match &n.kind { + NodeKind::Text(t) => { + n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0)) + } + _ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)), + }; + if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) { + return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)"))); + } + // Each existing group under the artboard it belongs to, worked out once. + let mut owned: std::collections::HashMap>> = std::collections::HashMap::new(); + for k in layer.iter().flat_map(|(_, kids)| kids) { + if let Some(board) = owner(k) { + owned.entry(board).or_default().push(k); + } + } + if let Some((layer, _)) = &layer { + let same = boards + .iter() + .zip(&drawn) + .all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new))); + if same { + let ids: Vec = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect(); + return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names })); + } + } + let owned: std::collections::HashMap> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect(); + let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| { + let layer = match marks_layer(d).map(|l| l.id) { + Some(id) => id, + None => { + let id = d.alloc_id(); + let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8); + let mut l = Node::layer(id, LAYER_NAME, color); + l.locked = true; + l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into()))); + d.insert(None, 0, l)?; + id + } + }; + let mut ids = Vec::with_capacity(boards.len()); + for (r, board) in &boards { + let kids = d.children(Some(layer)).cloned().unwrap_or_default(); + let old: Vec = owned.get(board).cloned().unwrap_or_default(); + let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX); + // Only what the selection holds of the marks leaves it; the rest of the selection stays as it is. + let mut held = vec![]; + for k in kids.iter().filter(|k| old.contains(&k.id)) { + k.walk(&mut |n: &Node| { + if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) { + held.push(n.id); + } + }); + } + if !held.is_empty() { + sel.remove_all(held); + } + d.remove_many(&old)?; + let g = marks.group(*r, *board, &mut || d.alloc_id()); + ids.push(g.id.0); + d.insert(Some(layer), at, g)?; + } + Ok((layer, ids)) + })?; + Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs new file mode 100644 index 0000000000..bb98d0786d --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -0,0 +1,935 @@ +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{Node, NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{COMMAND, LAYER_NAME}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn run(s: &mut Session, p: Value) -> Value { + s.execute(COMMAND, &p).unwrap() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn node(s: &Session, id: u64) -> Node { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone() +} + +/// The targets of group `g`: each one's three paths. +fn targets(g: &Node) -> Vec> { + g.children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Registration Target")) + .map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect()) + .collect() +} + +/// The type lines of group `g`, top to bottom as stored. +fn lines(g: &Node) -> Vec { + g.children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((**t).clone()), + _ => None, + }) + .collect() +} + +fn bounds(n: &Node) -> Rect { + n.geometric_bounds().unwrap() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The swatch solid paint `p` links to. +fn swatch_of(p: &Paint) -> Option { + match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + } +} + +#[test] +fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() { + let mut s = session(); + let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let undo = undo_len(&s); + let r = run(&mut s, json!({})); + assert_eq!(r["changed"], json!(true)); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept"); + let doc = &s.doc().unwrap().doc; + let layer = &doc.layers[0]; + assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack"); + assert_eq!(layer.name.as_deref(), Some(LAYER_NAME)); + assert!(layer.locked && layer.visible, "the marks layer is locked"); + assert_eq!(doc.layers.len(), 2); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one group for the active artboard"); + let g = node(&s, ids[0].as_u64().unwrap()); + assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str())); + let t = targets(&g); + assert_eq!(t.len(), 4, "top, bottom, left and right by default"); + assert!(lines(&g).is_empty(), "no type lines unless asked for"); + for paths in &t { + assert_eq!(paths.len(), 3, "a ring and two cross lines"); + for p in paths { + assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]"); + assert!(p.appearance.fill_paint().is_none()); + assert!(close(p.appearance.stroke_width(), 1.0)); + } + } + // The top target: its 36 pt box 18 pt in from the top edge, centered across. + let top = &t[0]; + let ring = bounds(&top[0]); + assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}"); + let across = bounds(&top[1]); + assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}"); + let down = bounds(&top[2]); + assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}"); + // Left, right and bottom. + let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect(); + assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]); + assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]); + assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks"); +} + +#[test] +fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let t = targets(&g); + assert_eq!(t.len(), 2); + // Drawn in POSITIONS order: top left first. A negative inset puts the targets outside. + let tl = bounds(&t[0][0]).center(); + let br = bounds(&t[1][0]).center(); + assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}"); + assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}"); + assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width"); + assert!(close(bounds(&t[0][1]).width(), 20.0)); + for p in t.iter().flatten() { + assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch"); + assert!(close(p.appearance.stroke_width(), 0.5)); + } +} + +#[test] +fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() { + let mut s = session(); + let first = run(&mut s, json!({"size": 30})); + let layer = first["layer"].clone(); + let undo = undo_len(&s); + let again = run(&mut s, json!({"size": 30})); + assert_eq!(again["changed"], json!(false)); + assert_eq!(again["ids"], first["ids"], "the same group stays"); + assert_eq!(undo_len(&s), undo, "nothing changed: no undo step"); + let r = run(&mut s, json!({"size": 40, "positions": ["top"]})); + assert_eq!(r["changed"], json!(true)); + assert_eq!(r["layer"], layer, "the same layer is reused"); + assert_eq!(undo_len(&s), undo + 1); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.layers.len(), 2, "no second marks layer"); + let kids = doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1, "the earlier marks are replaced"); + let t = targets(&kids[0]); + assert_eq!(t.len(), 1); + assert!(close(bounds(&t[0][1]).width(), 40.0)); + assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone"); +} + +#[test] +fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() { + let mut s = session(); + let p = json!({"positions": ["topLeft"]}); + let first = run(&mut s, p.clone()); + let before = node(&s, first["ids"][0].as_u64().unwrap()); + s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap(); + let undo = undo_len(&s); + let again = run(&mut s, p); + assert_eq!(again["changed"], json!(false)); + assert_eq!(again["ids"], first["ids"], "the same group stays"); + assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged"); + assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize"); +} + +#[test] +fn replacing_the_marks_keeps_a_selected_slice_selected() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("object.slice.make", &json!({})).unwrap(); + s.execute("select.object.slices", &json!({})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(!before.slices.is_empty()); + let r = run(&mut s, json!({"size": 50})); + assert_eq!(r["changed"], json!(true)); + assert!(s.doc().unwrap().selection == before, "the selection is kept as it was"); +} + +#[test] +fn marks_past_the_canvas_edge_are_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string(); + assert!(err.contains("edge of the canvas"), "{err}"); + assert!(s.doc().unwrap().doc == before); + run(&mut s, json!({"artboard": 1, "positions": ["right"]})); +} + +#[test] +fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() { + let mut s = session(); + // The artboard ends 10 pt inside the canvas edge. + s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap(); + let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20}); + let r = run(&mut s, p); + assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1); +} + +#[test] +fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() { + let mut s = session(); + // The artboard ends at the canvas edge. + s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap(); + // The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that. + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15})); + assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1); + // 5 pt inside the edge, the stroke reaches 5 pt past it. + let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string(); + assert!(err.contains("edge of the canvas"), "{err}"); +} + +#[test] +fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap(); + let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]})); + assert_eq!(r["ids"].as_array().unwrap().len(), 2); + let second = node(&s, r["ids"][1].as_u64().unwrap()); + let c = bounds(&targets(&second)[0][0]).center(); + assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}"); + let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]})); + assert_eq!(only["ids"].as_array().unwrap().len(), 1); + let doc = &s.doc().unwrap().doc; + let kids = doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2, "the first artboard's marks stay"); + assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap())); + let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center(); + assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}"); +} + +#[test] +fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap(); + s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap(); + // A tint swatch marked spot, as a file can hold one, is still a tint of its ink. + let st = s.doc_mut().unwrap(); + let mut tints = 0; + for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) { + w.spot = true; + tints += 1; + } + assert_eq!(tints, 1); + let title = s.doc().unwrap().doc.title.clone(); + // 2026-03-04 05:06 UTC. + let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760})); + assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out"); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + assert!(targets(&g).is_empty()); + let l = lines(&g); + assert_eq!(l.len(), 2); + let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect(); + assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]); + assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC")); + assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate"); + assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0))); + // At the bottom left by default: the file line is the lower one, both 18 pt in. + let doc = &s.doc().unwrap().doc; + let kids = g.children().unwrap(); + let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect(); + assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line"); + assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}"); + // No date without a time. + let r = run(&mut s, json!({"positions": [], "info": true, "time": null})); + assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title); +} + +#[test] +fn lines_at_the_top_right_start_past_a_corner_target() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap(); + let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let target = bounds(&targets(&g)[0][1]); + // 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size). + assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}"); + assert!(text.x1 < target.x0, "the line clears the corner target"); + assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}"); + assert!(close(lines(&g)[0].runs[0].style.size, 12.0)); +} + +#[test] +fn lines_move_up_past_a_bottom_center_target_they_would_cross() { + let mut s = session(); + let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}"); + assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}"); +} + +#[test] +fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() { + let mut s = session(); + s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap(); + let p = json!({"positions": [], "info": true, "time": 1772600760}); + let original = run(&mut s, p.clone()); + let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap())); + let mut with_target = p; + with_target["positions"] = json!(["bottom"]); + let r = run(&mut s, with_target); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap(); + let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}"); + assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}"); + assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard"); +} + +#[test] +fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap(); + let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24}); + let r = run(&mut s, p); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap(); + let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap(); + assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}"); +} + +#[test] +fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks"); + let copy = run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy"); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); + assert_eq!(kids(&s), 2); + assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay"); +} + +#[test] +fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::(); + let before = kids(&s); + run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy"); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged"); +} + +#[test] +fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() { + let mut s = session(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked"); + run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy"); +} + +#[test] +fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() { + let mut s = session(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None; + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked"); +} + +#[test] +fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({})); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap()); + s.execute("edit.paste", &json!({})).unwrap(); + let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len()))); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer"); + assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty"); +} + +#[test] +fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() { + for props in [json!({}), json!({"visible": false}), json!({"locked": true})] { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone(); + let mut set = props.clone(); + set["id"] = plain.clone(); + s.execute("layer.setProps", &set).unwrap(); + let plain = NodeId(plain.as_u64().unwrap()); + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 2, "{props}"); + assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}"); + let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(made.len(), 1, "a marks layer is made: {props}"); + assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}"); + let made = made[0].id.0; + let r = run(&mut s, json!({"artboard": 1, "size": 30})); + assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}"); + } +} + +#[test] +fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap(); + s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + for paste in 1..=2 { + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let marks = super::layer_id(doc).expect("a marks layer is made"); + let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}"); + for l in named { + let items = l.children().unwrap().len(); + assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks); + } + let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap(); + assert_eq!(ordinary.children().unwrap().len(), paste, "the ordinary layer holds one rectangle per paste: paste {paste}"); + assert!( + ordinary.children().unwrap().iter().all(|k| k.children().is_none()), + "only the rectangle goes into the ordinary layer: paste {paste}" + ); + } +} + +#[test] +fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap()); + for paste in 1..=2 { + s.execute("edit.paste", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let marks = super::layer_id(doc).expect("a marks layer is made"); + assert_ne!(marks, ordinary); + let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::>(); + assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}"); + assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}"); + } +} + +#[test] +fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() { + let mut s = session(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}"); + let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true}); + s.execute("artboard.move", &p).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + assert_eq!(kids(&s), 2, "the copy carries a copy of the marks"); + run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks"); +} + +#[test] +fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string(); + assert!(err.contains("locked or hidden"), "{err}"); + assert!(s.doc().unwrap().doc == before, "nothing is pasted"); +} + +#[test] +fn marks_pasted_after_their_layer_was_deleted_are_found_again() { + let mut s = session(); + let r = run(&mut s, json!({})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards.len(), 2); + run(&mut s, json!({"artboard": 1, "size": 30})); + let doc = &s.doc().unwrap().doc; + let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect(); + assert_eq!(layers.len(), 1, "one marks layer"); + assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy"); +} + +#[test] +fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + let g = node(&s, r["ids"][0].as_u64().unwrap()); + let b = bounds(&g); + assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}"); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out"); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out"); + let again = run(&mut s, json!({"positions": ["right"], "inset": -200})); + assert_eq!(again["changed"], json!(false)); +} + +#[test] +fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap(); + run(&mut s, json!({"artboard": 1, "positions": ["left"]})); + s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks"); + let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30})); + assert_eq!(copy["changed"], json!(true)); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks"); +} + +#[test] +fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let p = json!({"positions": ["right"], "inset": -200}); + run(&mut s, p.clone()); + s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks"); + run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks"); + assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); +} + +/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an +/// Alt-drag for `artboard.move`, and the artboards' art for the others. +fn copy_params(command: &str, target: Value) -> Value { + let mut p = match command { + "artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}), + _ => json!({"art": true, "lockedAndHidden": true}), + }; + if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) { + p.extend(t.clone()); + } + p +} + +#[test] +fn overlapping_artboard_copies_keep_one_marks_group_per_owner() { + for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap(); + let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]})); + let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]})); + let before = s.doc().unwrap().doc.clone(); + let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())]; + let p = copy_params(command, json!({"indices": [0, 1]})); + s.execute(command, &p).unwrap(); + if command == "artboard.copy" { + s.execute("edit.paste", &json!({})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let groups = d.layers[0].children().unwrap(); + assert_eq!(groups.len(), 4, "{command}"); + for (source, original) in originals.iter().enumerate() { + assert!(d.node(original.id).unwrap() == original, "{command}"); + let copied_board = &d.artboards[source + 2]; + let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect(); + assert_eq!(copies.len(), 1, "{command}: owner {source}"); + let offset = copied_board.rect.origin() - d.artboards[source].rect.origin(); + assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks"); + } +} + +#[test] +fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() { + for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200})); + let original = node(&s, r["ids"][0].as_u64().unwrap()); + let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200})); + let foreign = node(&s, other["ids"][0].as_u64().unwrap()); + assert!(bounds(&original).y1 < 0.0); + assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign))); + let before = s.doc().unwrap().doc.clone(); + let p = copy_params(command, json!({"index": 0})); + let reply = s.execute(command, &p).unwrap(); + if command == "artboard.cut" { + assert_eq!(reply["copied"], json!(1)); + assert!(s.doc().unwrap().doc.node(original.id).is_none()); + } + if matches!(command, "artboard.copy" | "artboard.cut") { + s.execute("edit.paste", &json!({})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let copied_board = d.artboards.last().unwrap(); + let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect(); + assert_eq!(copies.len(), 1, "{command}"); + assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged"); + let offset = copied_board.rect.origin() - before.artboards[0].rect.origin(); + assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + if command == "artboard.cut" { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(s.doc().unwrap().doc == before, "{command}"); + } +} + +#[test] +fn moving_an_artboard_uses_marks_ownership_instead_of_containment() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200})); + let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200})); + let own = node(&s, outside["ids"][0].as_u64().unwrap()); + let foreign = node(&s, other["ids"][0].as_u64().unwrap()); + assert!(bounds(&own).y1 < 0.0); + assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign))); + let before = s.doc().unwrap().doc.clone(); + for (move_art, all) in [(false, true), (true, false)] { + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap(); + assert!(node(&s, own.id.0) == own); + assert!(node(&s, foreign.id.0) == foreign); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before); + } + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let start = bounds(&own); + let moved = bounds(&node(&s, own.id.0)); + let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0); + assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard"); + let board = s.doc().unwrap().doc.artboards[0].rect; + assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved"); + assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard"); + assert!(node(&s, foreign.id.0) == foreign); + assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before); +} + +#[test] +fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let p = json!({"positions": ["right"], "inset": -200}); + run(&mut s, p.clone()); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap(); + assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden"); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard"); + run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30})); + assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks"); + assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged"); +} + +#[test] +fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"positions": ["right"], "inset": -200})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len(); + let before = kids(&s); + s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group"); +} + +#[test] +fn marks_of_a_deleted_artboard_are_copied_like_other_art() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + run(&mut s, json!({"positions": ["right"], "inset": -200})); + s.execute("artboard.delete", &json!({"indices": [0]})).unwrap(); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks"); +} + +#[test] +fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() { + let mut s = session(); + run(&mut s, json!({})); + s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap(); + let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + let source = run(&mut s, json!({})); + assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's"); + assert_eq!(kids(&s), 2); + run(&mut s, json!({"artboard": 1})); + assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy"); +} + +#[test] +fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() { + let mut s = session(); + let original = run(&mut s, json!({})); + let id = original["ids"][0].as_u64().unwrap(); + let before = node(&s, id); + s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap(); + run(&mut s, json!({"artboard": 1})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group"); + assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + run(&mut s, json!({"artboard": 0})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); +} + +#[test] +fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60})); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 2); + for id in ids { + assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept"); + } + let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60})); + assert_eq!(again["changed"], json!(false)); +} + +#[test] +fn bad_params_are_refused_and_leave_the_document_unchanged() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = undo_len(&s); + for bad in [ + json!({"positions": ["middle"]}), + json!({"positions": ["top", "top"]}), + json!({"positions": "top"}), + json!({"positions": [1]}), + json!({"size": 2}), + json!({"size": "36"}), + json!({"weight": 0}), + json!({"inset": 5000}), + json!({"textSize": 100}), + json!({"textPlace": "middle"}), + json!({"textAlign": 1}), + json!({"ink": "Nope"}), + json!({"ink": "Process"}), + json!({"ink": 3}), + json!({"inks": "yes"}), + json!({"info": 1}), + json!({"time": "today", "info": true}), + json!({"artboard": 5}), + json!({"artboard": -1}), + json!({"artboard": 0, "allArtboards": true}), + json!({"positions": null}), + json!({"artboard": null}), + json!({"size": null}), + json!({"positions": [], "inks": false, "info": false}), + json!({"positions": [], "inks": true}), + ] { + assert!(s.execute(COMMAND, &bad).is_err(), "{bad}"); + } + assert!(s.doc().unwrap().doc == before); + assert_eq!(undo_len(&s), undo); + // An ink line with no spot inks draws the targets and no line. + let r = run(&mut s, json!({"inks": true})); + assert_eq!(r["inks"], json!([])); + assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty()); +} + +#[test] +fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]})); + let gone = s.doc().unwrap().doc.artboards[1].id; + s.execute("artboard.delete", &json!({"indices": [1]})).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art"); + // A reopened file does not remember the deleted id, so a new artboard can take it. + assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard"); +} + +#[test] +fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]})); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + let other = s.doc().unwrap().doc.layers[1].id.0; + s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap(); + s.execute("artboard.delete", &json!({"indices": [1]})).unwrap(); + assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None); +} + +#[test] +fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let own = node(&s, r["ids"][0].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard"); +} + +#[test] +fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled"); +} + +#[test] +fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200})); + let own = node(&s, r["ids"][0].as_u64().unwrap()); + s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began"); + s.execute("edit.undo", &json!({})).unwrap(); + let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap(); + assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too"); +} + +#[test] +fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() { + let mut s = session(); + for _ in 0..2 { + s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap(); + } + let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]})); + // A file saved before deleting an artboard cleared its marks' tag. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2); + let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]); + s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap())); + assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed"); +} + +#[test] +fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap(); + let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap(); + let (own, foreign) = (node(&s, own), node(&s, foreign)); + s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap(); + let start = bounds(&own); + let moved = bounds(&node(&s, own.id.0)); + assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it"); + assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay"); +} + +#[test] +fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let start = s.journal.len(); + run(&mut s, json!({"positions": ["right"]})); + let (cmd, recorded) = s.journal.last().unwrap().clone(); + assert_eq!(cmd, COMMAND); + assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on"); + // A replay on another active artboard marks the recorded one. + let first = s.doc().unwrap().doc.artboards[0].id; + s.doc_mut().unwrap().active_artboard = Some(first); + let replayed = run(&mut s, recorded); + assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same"); + // A recorded action leaves it out and marks the artboard active when it plays. + let action = s.journal_for_action(start); + assert_eq!(action.len(), 2, "the action holds the first run and the replay"); + assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none())); +} diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index f5b3d9fa38..f8ac3f152b 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result Vec { vec![ diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 3f100acc5a..edffa17055 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -24,6 +24,37 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) } +/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it +/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the +/// changes [`silent`] makes without an undo step. +pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool { + let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY)); + if a == b { + return false; + } + let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before)); + g.visible = was.visible; + g.plane = was.plane; + g.inferred = was.inferred; + g.locked = was.locked; + g.lock_station = was.lock_station; + g.snap = was.snap; + g.rulers = was.rulers; + g.attached.clear(); + was.attached.clear(); + if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() { + return false; + } + let mut rest = now.clone(); + let mut normalized_before = before.clone(); + PerspectiveGrid::current(before).store(&mut normalized_before); + match normalized_before.unknown.get(persp::DOC_KEY) { + Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()), + None => rest.unknown.remove(persp::DOC_KEY), + }; + rest == normalized_before +} + /// Change view state of the grid without an undo step. pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result { let st = s.doc_mut()?; diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 13291b5307..4311fdf290 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -31,7 +31,7 @@ mod freehand; mod quickpen; mod smooth; -pub(super) use anchors::{following_anchors, remove_anchors_of}; +pub(super) use anchors::remove_anchors_following; pub use commands::specs; pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path}; pub(super) use cut::{components, erase_outline}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index a1271a39a9..9d23053e2c 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -129,7 +129,12 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { sel.segments.remove(&id); return Ok(false); } - let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let path = match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, .. }) => path, + Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))), + None => return Err(EngineError::NoNode(id)), + }; + let sp = path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; if ai >= sp.anchors.len() { return Err(EngineError::Other("no such anchor".into())); } @@ -160,15 +165,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { let mut gone = Vec::new(); let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::>()); for (id, anchors) in jobs { - let shape: Vec<(usize, bool)> = - d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); - let next = following_anchors(&shape, &anchors); - if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? { - gone.push(id); - } else if !next.is_empty() { + match remove_anchors_following(d, sel, &mut emptied, id, anchors, false)? { + None => gone.push(id), // The next anchor along is selected, so the next Remove Anchor Points goes on from // there without picking it first (#2241). - sel.anchors.insert(id, next); + Some(next) if !next.is_empty() => { + sel.anchors.insert(id, next); + } + Some(_) => {} } } emptied.finish(d)?; @@ -225,12 +229,41 @@ pub(in crate::cmd) fn remove_anchors_of( sel: &mut Selection, emptied: &mut Beside, id: NodeId, - mut anchors: Vec<(usize, usize)>, + anchors: Vec<(usize, usize)>, curvature: bool, ) -> Result { - // The last first, so the indexes still to come stay valid. - anchors.sort_unstable_by(|a, b| b.cmp(a)); + Ok(remove_anchors_following(d, sel, emptied, id, anchors, curvature)?.is_none()) +} + +/// [`remove_anchors_of`], returning `None` when the path went, else the anchors that follow the +/// removed ones in each subpath ([`following_anchors`]), numbered as the path is after the removal. +/// A path with cut Live Corners keeps them ([`vectorcraft_doc::remove_corner_anchors`]): the anchors +/// of its uncut outline that `anchors` come from are removed, so removing either anchor of a cut +/// corner removes that corner, and the following anchors are those of the outline. +pub(in crate::cmd) fn remove_anchors_following( + d: &mut Document, + sel: &mut Selection, + emptied: &mut Beside, + id: NodeId, + mut anchors: Vec<(usize, usize)>, + curvature: bool, +) -> Result>> { + anchors.sort_unstable(); anchors.dedup(); + if let Some(next) = remove_live_corner_anchors(d, id, &anchors, curvature) { + if d.node(id).and_then(Node::path_data).is_none_or(PathData::is_empty) { + emptied.put(d, id, vec![])?; + return Ok(None); + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + return Ok(Some(next)); + } + let shape: Vec<(usize, bool)> = + d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default(); + let next = following_anchors(&shape, &anchors); + // The last first, so the indexes still to come stay valid. + anchors.reverse(); let path = path_mut(d, id)?; let mut rest = &anchors[..]; while let Some(&(si, _)) = rest.first() { @@ -246,14 +279,41 @@ pub(in crate::cmd) fn remove_anchors_of( } } path.subpaths.retain(|sp| sp.anchors.len() >= 2); - let gone = path.is_empty(); - if gone { + if path.is_empty() { emptied.put(d, id, vec![])?; - } else { - sel.anchors.remove(&id); - sel.segments.remove(&id); + return Ok(None); } - Ok(gone) + sel.anchors.remove(&id); + sel.segments.remove(&id); + Ok(Some(next)) +} + +/// Remove `anchors` (ascending, no repeats) of path `id` when it has cut Live Corners, keeping +/// them live ([`vectorcraft_doc::remove_corner_anchors`]), and return the anchors as drawn that +/// follow the removed ones; `None`, changing nothing, when the corners can't stay live. +fn remove_live_corner_anchors(d: &mut Document, id: NodeId, anchors: &[(usize, usize)], curvature: bool) -> Option> { + let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None }; + // A plain path has no corners to keep. + live.as_ref()?; + let set: BTreeSet<(usize, usize)> = anchors.iter().copied().collect(); + let lc = vectorcraft_doc::LiveCorners::new(path, live.as_deref())?; + let shape: Vec<(usize, bool)> = lc.base.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect(); + let outline: Vec<(usize, usize)> = lc.outline_anchors(&set).into_iter().collect(); + drop(lc); + vectorcraft_doc::remove_corner_anchors(path, live, &set, |sp, gone| { + if curvature { + for &ai in gone.iter().rev() { + vectorcraft_tools::draw2::curvature_remove(sp, ai); + } + } else { + po::remove_anchors(sp, gone); + } + })?; + let next = following_anchors(&shape, &outline); + Some(match vectorcraft_doc::LiveCorners::new(path, live.as_deref()) { + Some(lc) => lc.drawn_anchors(&next), + None => next, + }) } pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index eda5d19d23..46d862ae27 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Delete Anchor Point", [], None, - "{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least", + "{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least; on a path with rounded Live Corners, the corner the anchor belongs to is removed and the other corners stay live", has_doc, remove_anchor ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Remove Anchor Points", ["Object", "Path"], None, - "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}", + "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path; on a path with rounded Live Corners, the corners the anchors belong to are removed and the other corners stay live → {removedObjects}", has_anchors, remove_anchors ), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 55726c31c9..dc0bf5c730 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -189,7 +189,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted, except the Screen Print Marks layer for the marks copied with their artboard). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -1363,17 +1363,15 @@ fn clear(s: &mut Session, p: &Value) -> Result { } s.edit("Clear", |d, sel| { let clipped = clipped_ancestors(d, ids.iter().copied()); - let parents: Vec<_> = if keep_empty { - Vec::new() - } else { - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() - }; + let emptied = if keep_empty { Vec::new() } else { emptied_compounds(d, &ids) }; + // A compound path inside another emptied one leaves with it. + let outer: Vec = emptied + .iter() + .copied() + .filter(|p| !d.ancestry(*p).unwrap_or_default().iter().rev().skip(1).any(|a| emptied.binary_search(a).is_ok())) + .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)?; - } - } + d.remove_many(&outer)?; if with_guides { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); @@ -1390,6 +1388,27 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// The compound paths that deleting the objects `ids` together leaves with no members, sorted by +/// id: a compound path counts when each of its members is deleted or is such a compound path, so +/// a compound path holding only an emptied inner one is emptied too. +fn emptied_compounds(d: &Document, ids: &[NodeId]) -> Vec { + let mut gone: BTreeSet = ids.iter().copied().collect(); + let mut emptied = BTreeSet::new(); + loop { + let parents: BTreeSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); + let found: BTreeSet = parents + .into_iter() + .filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + .filter(|p| d.children(Some(*p)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id)))) + .collect(); + if found.is_empty() { + return emptied.into_iter().collect(); + } + gone.extend(found.iter().copied()); + emptied.extend(found); + } +} + /// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else /// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a /// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined` @@ -1638,9 +1657,16 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho && inside.is_none() && (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); + // Screen print marks copied with an artboard that is pasted once go back into the marks layer, + // locked or hidden as it is. + let pasted_once: Vec = match boards { + Some((all, _)) => all.iter().map(|a| a.id).filter(|id| all.iter().filter(|a| a.id == *id).count() == 1).collect(), + None => vec![], + }; + let marks: Vec = clip.nodes.iter().map(|n| super::addons::screen_marks_of(n, &pasted_once)).collect(); // Each object's remembered layer, found before anything is pasted: a hidden or locked one // refuses the whole paste. - let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] }; + let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, &marks, same_doc)? } else { vec![] }; // Front/back: relative to the selection (top-most / bottom-most selected object); with // nothing selected, the top / bottom of the current layer. Art other than paths goes beside // the compound path that holds the selected object, not into it. @@ -1681,13 +1707,22 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let mut imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; - let artboards: Vec = boards + let made_boards: Vec<(u32, usize)> = boards .into_iter() .flat_map(|(all, dv)| all.iter().map(move |a| (a, dv))) - .map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv)) + .map(|(a, dv)| (a.id, super::panelcmds::push_artboard_copy(d, a, a.rect + dv))) + .collect(); + let artboards: Vec = made_boards.iter().map(|(_, i)| *i).collect(); + // Screen print marks copied with an artboard pasted once belong to the pasted artboard. + let board_ids: Vec<(u32, u32)> = made_boards + .iter() + .filter(|(src, _)| made_boards.iter().filter(|(s, _)| s == src).count() == 1) + .filter_map(|(src, i)| d.artboards.get(*i).map(|a| (*src, a.id))) .collect(); // The layers made for remembered layers the document lacks, by parent and name. let mut made = HashMap::new(); + // The marks layer made for screen print marks, kept apart from ordinary layers of its name. + let mut made_marks: HashMap<(Option, String), NodeId> = HashMap::new(); // Objects pasted into each parent so far (keeps their order in front and back pastes). let mut placed: BTreeMap, usize> = BTreeMap::new(); let mut new_ids = vec![]; @@ -1702,6 +1737,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // A pasted symbol set packs from the density recorded for it at Copy. d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c, d); + let marks = board_ids.iter().any(|(from, to)| super::addons::retag_screen_marks(&mut c, *from, *to)); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { // A cross-document drag carries the graphic's appearance with it, @@ -1710,7 +1746,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } let layer = match remembered.get(k) { Some(Some(Remembered::Layer(l))) => Some(*l), - Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?, + Some(Some(Remembered::Make { parent, names })) => make_remembered(d, &mut made, &mut made_marks, marks, *parent, names)?, _ => None, }; // In a clip group or a clipping layer the bottom child is the clipping path: art pasted @@ -1850,18 +1886,27 @@ enum Remembered { Make { parent: Option, names: Vec }, } -/// [`remembered_layer`] for each object's source layer, worked out once for each layer. -fn remembered_layers(d: &Document, sources: &[Option], same_doc: bool) -> Result>> { - let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new(); +/// [`remembered_layer`] for each object's source layer, worked out once for each layer. The objects +/// `marks` marks are screen print marks groups, which may go back into the marks layer while it +/// is locked or hidden. +fn remembered_layers(d: &Document, sources: &[Option], marks: &[bool], same_doc: bool) -> Result>> { + let mut found: HashMap<(&SourceLayer, bool), Remembered> = HashMap::new(); sources .iter() - .map(|src| { + .enumerate() + .map(|(k, src)| { + // A marks group goes into the marks layer even when the layer it was copied from has + // no name. + if marks.get(k).copied().unwrap_or(false) && src.is_none() { + return Ok(Some(marks_layer_target(d))); + } let Some(src) = src else { return Ok(None) }; - if let Some(r) = found.get(src) { + let key = (src, marks.get(k).copied().unwrap_or(false)); + if let Some(r) = found.get(&key) { return Ok(Some(r.clone())); } - let r = remembered_layer(d, src, same_doc)?; - found.insert(src, r.clone()); + let r = remembered_layer(d, src, key.1, same_doc)?; + found.insert(key, r.clone()); Ok(Some(r)) }) .collect() @@ -1872,8 +1917,15 @@ fn remembered_layers(d: &Document, sources: &[Option], same_doc: bo /// it still where they were (by id) are kept. Below them, and in another document from the top, /// each name is matched among the layers inside the one above (the topmost of the same name whose /// layers match the most names, a shown and unlocked one first). The names left unmatched are -/// made. A matched layer that is hidden or locked, or inside one that is, is an error. -fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result { +/// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen +/// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is, +/// or into a new top-level marks layer when the document has none. +fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result { + // A marks group goes into the document's marks layer, never into an ordinary layer of the + // same name. + if marks { + return Ok(marks_layer_target(d)); + } let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last()); let kept = if same_doc && src.ids.last().is_some_and(held) { src.ids.len() @@ -1898,6 +1950,15 @@ fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result