mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into feat/pict-export
This commit is contained in:
commit
442845c121
136 files changed
+10001
-1086
No files matched your search
@@ -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"
|
||||
},
|
||||
|
||||
+27
-29
@@ -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 (<os>)` 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 (<os>)` 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 (<os>)` leg runs the other `cargo xtask ci` steps beside
|
||||
# them, with a dependency cache of its own. `gate (<os>)` passes when the build and every
|
||||
# test leg that ran passed; `lint (<os>)` 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 <k>/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 <k>/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'
|
||||
|
||||
@@ -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 | |
|
||||
|
||||
Generated
+2
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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<H> Viewports<H> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<i32>, work: Option<i32>| 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<Edge> {
|
||||
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<Edge> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="3" width="18" height="4.5" stroke-width="1.25" /><path d="M6 7.5V16H10" stroke-width="1.25" /><rect x="10" y="11" width="11" height="10" stroke-width="1.25" /><path d="M15.5 13.5V18.5M13 16H18" stroke-width="1.5" /></svg>
|
||||
|
After Width: | Height: | Size: 419 B |
@@ -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 }
|
||||
+179
-6
@@ -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<u8> {
|
||||
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
|
||||
/// (<https://en.wikipedia.org/wiki/.dwg#Version_history>).
|
||||
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<String> {
|
||||
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<Held, String> {
|
||||
}
|
||||
|
||||
fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
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<u8>, 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<String> {
|
||||
let total: usize = left_out.values().sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let kinds: Vec<String> = 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}");
|
||||
}
|
||||
}
|
||||
@@ -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<craft_dxf::Tag>, Vec<String>), 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<DxfInfo, String> {
|
||||
}
|
||||
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;
|
||||
+578
-27
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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<String, usize>,
|
||||
/// Blocks being drawn, outermost first.
|
||||
stack: Vec<String>,
|
||||
/// 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<Rect>,
|
||||
symbol_reach: HashMap<String, Rect>,
|
||||
/// 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<String, Cost>,
|
||||
uses: HashMap<String, usize>,
|
||||
nested: Cost,
|
||||
/// Each symbol's place in the document's symbols, and the symbols whose art was taken out.
|
||||
symbol_slot: HashMap<String, usize>,
|
||||
empty: HashSet<String>,
|
||||
/// 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<Arc<Node>> {
|
||||
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<Arc<Node>> {
|
||||
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<Node>) -> 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>), 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<Rect> {
|
||||
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<Option<Rect>> = 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<Node> {
|
||||
/// 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<Node> {
|
||||
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<Node> {
|
||||
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<String> {
|
||||
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<Node> {
|
||||
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<Vec<Point>> = 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<Node> {
|
||||
@@ -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<Rect>| 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<String> {
|
||||
/// 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<String> {
|
||||
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<Node>, Option<Rect>, 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<String> {
|
||||
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<usize> = vec![];
|
||||
// Each symbol is queued once, however many instances place it.
|
||||
let note = |n: &Node, placed: &mut Vec<bool>, todo: &mut Vec<usize>| {
|
||||
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<String, usize>, taken: &HashSet<String>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
+249
-16
@@ -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<Item>,
|
||||
}
|
||||
|
||||
/// 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<u64>,
|
||||
/// 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<Vec<Point>>,
|
||||
}
|
||||
|
||||
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<Grad>),
|
||||
/// 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<String>,
|
||||
/// 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<HashMap<u64, Vec<u8>>>,
|
||||
}
|
||||
|
||||
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<Geom> {
|
||||
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<Geom> {
|
||||
// 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<Geom> {
|
||||
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<Geom> {
|
||||
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<Vec<Point>> {
|
||||
let pts: Vec<Point> = 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"
|
||||
|
||||
@@ -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<NoPattern>,
|
||||
}
|
||||
|
||||
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<PatternLine> {
|
||||
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<Vec<(Point, Point)>, NoPattern> {
|
||||
let mut loops: Vec<BezPath> = 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::<Point>, None::<Point>);
|
||||
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<f64>) {
|
||||
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<Grad> {
|
||||
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::<Vec<_>>();
|
||||
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::<Vec<_>>();
|
||||
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<f64> = 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");
|
||||
}
|
||||
}
|
||||
@@ -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<EntityRecord<'a>>,
|
||||
/// Model space first, then the paper layouts in tab order.
|
||||
pub layouts: Vec<LayoutDef>,
|
||||
/// The image files by the handle of their IMAGEDEF.
|
||||
pub images: HashMap<u64, ImageFile>,
|
||||
/// 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() {
|
||||
|
||||
@@ -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<f64> = 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<u8> {
|
||||
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<bool> = 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");
|
||||
|
||||
@@ -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<u8> {
|
||||
dxf_as(DxfVersion::R2000)
|
||||
}
|
||||
|
||||
/// [`dxf`] written as a DXF of `version`.
|
||||
fn dxf_as(version: DxfVersion) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<LayerArt> {
|
||||
.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<u8> {
|
||||
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));
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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<u8> {
|
||||
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::<String>().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<Node> {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| out.push(n.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
fn images(doc: &Document) -> Vec<ImageObject> {
|
||||
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::<Vec<_>>(), ["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::<Vec<_>>(), [(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<Point> = 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::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[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<u8> {
|
||||
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::<Vec<_>>());
|
||||
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);
|
||||
}
|
||||
@@ -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"] }
|
||||
+209
-8
@@ -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<AnchorRef>) -> BTreeSet<AnchorRef> {
|
||||
let ks: BTreeSet<usize> = 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<AnchorRef> {
|
||||
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<AnchorRef>) -> BTreeSet<AnchorRef> {
|
||||
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<AnchorRef>,
|
||||
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
|
||||
) -> 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<Box<LiveShape>>,
|
||||
edit: impl FnOnce(&mut PathData) -> Option<Vec<Option<usize>>>,
|
||||
) -> 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<f64> = from.iter().map(|f| f.and_then(|i| lengths.get(i).copied()).unwrap_or(0.0)).collect();
|
||||
let kinds: Vec<CornerKind> = 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<Box<LiveShape>>, si: usize, seg: usize, t: f64) -> Option<usize> {
|
||||
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<Box<LiveShape>>,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
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<usize> = 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<AnchorRef> = (0..3).flat_map(|si| (0..12).map(move |ai| (si, ai))).collect();
|
||||
let one_by_one: BTreeSet<AnchorRef> = 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() {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ObjectTag>,
|
||||
}
|
||||
|
||||
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<u64> = 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;
|
||||
|
||||
|
||||
@@ -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<usize> = 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<Item = &Swatch> {
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.chain(screen_marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<f64>) -> Result<f64> {
|
||||
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<Vec<&'static str>> {
|
||||
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::<Result<_>>()?
|
||||
}
|
||||
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<Paint> {
|
||||
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<usize> {
|
||||
let d = &st.doc;
|
||||
let at = |id: Option<u32>| 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<Vec<(String, Paint)>>,
|
||||
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<TextRun> = 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<Arc<Node>> = 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<Node>> {
|
||||
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<u32> {
|
||||
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<NodeId, u32> {
|
||||
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<NodeId> {
|
||||
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<u32>) {
|
||||
// Groups moved off the marks layer keep their tag and count too.
|
||||
let mut groups: Vec<NodeId> = 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<Value> {
|
||||
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<(String, Paint)>> = 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<String> = 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<Node> = 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<u32, Vec<&Arc<Node>>> = 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<u64> = 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<u32, Vec<NodeId>> = 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<NodeId> = 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;
|
||||
@@ -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<Vec<Node>> {
|
||||
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<vectorcraft_doc::TextObject> {
|
||||
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<String> {
|
||||
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::<usize>();
|
||||
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::<Vec<_>>();
|
||||
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()));
|
||||
}
|
||||
@@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
let id = s.edit(label, |d, sel| {
|
||||
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
let mut image = if is_trace_group(&src) {
|
||||
src.children()
|
||||
.and_then(|c| c.first())
|
||||
@@ -1225,17 +1225,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
|
||||
// appearance items, visibility and lock.
|
||||
if !expand && is_trace_group(&src) {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
// Tracing again keeps the tracing's note, tags and URL, including when expanding.
|
||||
// Without expansion, it also keeps the tracing's other object settings.
|
||||
if is_trace_group(&src) {
|
||||
// The attributes move from `src`, this edit's own copy of the tracing, without another copy.
|
||||
if src.extras().attrs.is_some() {
|
||||
g.extras_mut().attrs = src.extras_mut().attrs.take();
|
||||
}
|
||||
if !expand {
|
||||
g.visible = src.visible;
|
||||
g.locked = src.locked;
|
||||
g.opacity = src.opacity;
|
||||
g.blend = src.blend;
|
||||
g.isolate = src.isolate;
|
||||
g.knockout = src.knockout;
|
||||
g.knockout_shape = src.knockout_shape;
|
||||
g.appearance = src.appearance.clone();
|
||||
}
|
||||
}
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
|
||||
@@ -26,7 +26,9 @@ pub use perspective::perspective_click;
|
||||
use perspective::{
|
||||
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
|
||||
};
|
||||
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
|
||||
pub(crate) use perspective::{
|
||||
finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
|
||||
@@ -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<PerspectiveGrid> {
|
||||
let st = s.doc_mut()?;
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -129,7 +129,12 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
let mut gone = Vec::new();
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
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<bool> {
|
||||
// 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<Option<BTreeSet<(usize, usize)>>> {
|
||||
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<BTreeSet<(usize, usize)>> {
|
||||
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<Value> {
|
||||
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
+107
-25
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
}
|
||||
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<NodeId> = 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<Value> {
|
||||
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<NodeId> {
|
||||
let mut gone: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut emptied = BTreeSet::new();
|
||||
loop {
|
||||
let parents: BTreeSet<NodeId> = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect();
|
||||
let found: BTreeSet<NodeId> = 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<u32> = 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<bool> = 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<usize> = 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<usize> = 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<NodeId>, String), NodeId> = HashMap::new();
|
||||
// Objects pasted into each parent so far (keeps their order in front and back pastes).
|
||||
let mut placed: BTreeMap<Option<NodeId>, 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<NodeId>, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
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<SourceLayer>], marks: &[bool], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
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<SourceLayer>], 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<Remembered> {
|
||||
/// 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<Remembered> {
|
||||
// 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<R
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a screen print marks group goes: the document's marks layer, locked or hidden as it is,
|
||||
/// or a new top-level marks layer when the document has none.
|
||||
fn marks_layer_target(d: &Document) -> Remembered {
|
||||
match super::addons::screen_marks_layer(d) {
|
||||
Some(l) => Remembered::Layer(l),
|
||||
None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
|
||||
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
|
||||
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
|
||||
@@ -1908,7 +1969,9 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.node(p).and_then(Node::children),
|
||||
};
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
|
||||
// Ordinary art never goes into the screen print marks layer by its name.
|
||||
let marks_layer = parent.is_none().then(|| super::addons::screen_marks_layer(d)).flatten();
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str()) && Some(l.id) != marks_layer) {
|
||||
let (end, n, open) = named_chain(d, Some(l.id), rest);
|
||||
let chain = (end, n + 1, open && l.visible && !l.locked);
|
||||
if (chain.1, chain.2) > (best.1, best.2) {
|
||||
@@ -1918,6 +1981,25 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
best
|
||||
}
|
||||
|
||||
/// Makes the layers of a `Remembered::Make` for one pasted object. The marks layer for a screen
|
||||
/// print marks group (`marks`) is made apart from ordinary layers of its name (`made_marks`) and
|
||||
/// becomes the marks layer, so Create Screen Print Marks finds the copy there.
|
||||
fn make_remembered(
|
||||
d: &mut Document,
|
||||
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
made_marks: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
marks: bool,
|
||||
parent: Option<NodeId>,
|
||||
names: &[String],
|
||||
) -> Result<Option<NodeId>> {
|
||||
let is_marks = marks && parent.is_none() && matches!(names, [n] if n == super::addons::SCREEN_MARKS_LAYER);
|
||||
let last = make_layers(d, if is_marks { made_marks } else { made }, parent, names)?;
|
||||
if let (true, Some(l)) = (is_marks, last) {
|
||||
super::addons::adopt_screen_marks_layer(d, l);
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
|
||||
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
|
||||
/// none when `names` is empty.
|
||||
|
||||
@@ -400,3 +400,59 @@ fn selected_roots_are_found_once_for_each_document_and_selection() {
|
||||
selected_roots(&s).unwrap();
|
||||
assert_eq!(roots_found() - before, 2, "an edit finds the roots once again");
|
||||
}
|
||||
|
||||
/// Clear removes a compound path whose members are cleared paths and a compound path the clear
|
||||
/// empties, whichever order the ids come in, and the tracing guard's set counts both as deleted.
|
||||
#[test]
|
||||
fn clear_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
for reversed in [false, true] {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let mut ids: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
if reversed {
|
||||
ids.reverse();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.parent_of(inner), Some(outer), "the inner compound path is a member of the outer one");
|
||||
let want: Vec<NodeId> = BTreeSet::from([outer, inner]).into_iter().collect();
|
||||
assert_eq!(emptied_compounds(d, &ids), want, "reversed: {reversed}");
|
||||
run(&mut s, "edit.clear", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes (reversed: {reversed})");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too (reversed: {reversed})");
|
||||
}
|
||||
}
|
||||
|
||||
/// With a direct-selected anchor of another path in the selection, Clear still removes the outer
|
||||
/// compound path that an emptied inner one leaves empty.
|
||||
#[test]
|
||||
fn clear_with_direct_anchors_removes_a_compound_path_emptied_through_an_emptied_inner_one() {
|
||||
let mut s = new_doc();
|
||||
let outer_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (outer, outer_members) = compound(&mut s, &outer_paths);
|
||||
let inner_paths = [(); 2].map(|()| rect(&mut s));
|
||||
let (inner, inner_members) = compound(&mut s, &inner_paths);
|
||||
let other = rect(&mut s);
|
||||
s.edit("Nest", |d, _| {
|
||||
let taken = d.remove_many(&[inner])?;
|
||||
d.insert(Some(outer), 1, (*taken[0]).clone())?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let whole: Vec<NodeId> = outer_members.iter().chain(&inner_members).copied().collect();
|
||||
select_direct(&mut s, &whole, &[(other, two_anchors())]);
|
||||
run(&mut s, "edit.clear", json!({}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(inner).is_none(), "the emptied inner compound path goes");
|
||||
assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too");
|
||||
assert!(d.node(other).is_some(), "the path with anchors picked keeps its other sides");
|
||||
}
|
||||
@@ -13,10 +13,10 @@
|
||||
//! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend.
|
||||
//! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`.
|
||||
//! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`.
|
||||
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker).
|
||||
//! - `dxf`: DXF and DWG export options, `document.exportDxf`, and the formats that can't be written (PageMaker).
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT and CGM open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
@@ -246,6 +246,9 @@ mod tests_svgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(all(test, feature = "cgm"))]
|
||||
mod tests_cgm;
|
||||
#[cfg(test)]
|
||||
mod tests_dwgimport;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -283,20 +283,6 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
thread_local! {
|
||||
/// The paths [`read_file`] has read on this thread, in order.
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn regular_write_target(path: &str) -> Result<()> {
|
||||
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
@@ -314,6 +300,12 @@ pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
|
||||
f()
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
thread_local! {
|
||||
/// The paths [`read_file`] has read on this thread, in order.
|
||||
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
|
||||
@@ -570,6 +570,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "tga"
|
||||
| "psd"
|
||||
| "dxf"
|
||||
| "dwg"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "pict"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As
|
||||
//! → DXF Options): the options parsed from the params, one drawing per artboard with Use
|
||||
//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to
|
||||
//! use instead.
|
||||
//! DXF and DWG export for every path (`document.export {format: dxf|dwg}`, `document.exportDxf`,
|
||||
//! Export As → DXF Options and DWG Options): the options parsed from the params, one drawing per
|
||||
//! artboard with Use Artboards, and the formats that can't be written (PageMaker) with what to use
|
||||
//! instead. A DWG file is the DXF drawing converted by craft-dwg (`vectorcraft_cad::dwg::from_dxf`),
|
||||
//! from version 2000.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -22,14 +23,27 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, groupBlocks?: false (Always Export Group as Block Reference: each group a block of its contents, nested groups blocks inside it, placed by an INSERT on the group's layer), selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
"{path?, format?: dxf (default)|dwg (a DWG file of the same drawing, version 2000 to 2018; records the DWG writer can't write in that version are left out with a warning), dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, groupBlocks?: false (Always Export Group as Block Reference: each group a block of its contents, nested groups blocks inside it, placed by an INSERT on the group's layer), selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf} (or dwg). A key DXF doesn't take is refused",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
}
|
||||
|
||||
/// The DXF options `document.formats` lists.
|
||||
pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
pub(crate) const OPTIONS: &[FormatOption] = &DXF_OPTIONS;
|
||||
|
||||
/// The DWG options `document.formats` lists: the DXF ones, with the versions a DWG is written as.
|
||||
pub(crate) const DWG_OPTIONS: &[FormatOption] = &{
|
||||
let mut o = DXF_OPTIONS;
|
||||
assert!(matches!(o[VERSION].name.as_bytes(), b"version"), "VERSION is the index of the version option");
|
||||
o[VERSION] = FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "2000, 2004, 2007, 2010, 2013 or 2018" };
|
||||
o
|
||||
};
|
||||
|
||||
/// Where the version option is in [`DXF_OPTIONS`].
|
||||
const VERSION: usize = 5;
|
||||
|
||||
const DXF_OPTIONS: [FormatOption; 18] = [
|
||||
super::ARTBOARD,
|
||||
super::ARTBOARDS,
|
||||
super::RANGE,
|
||||
@@ -119,16 +133,24 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
|
||||
}
|
||||
|
||||
/// Formats VectorCraft opens but doesn't write (by id or extension), with what to export instead.
|
||||
/// Ids and extensions VectorCraft opens but doesn't write, with what to export instead: `.dws`
|
||||
/// drawing standards files and `.dwt` templates are DWG drawings, and only `.dwg` is written.
|
||||
const READ_ONLY_HINTS: &[(&[&str], &str)] =
|
||||
&[(&["dwg", "dws", "dwt"], "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
&[(&["dws", "dwt"], ".dws and .dwt files open but can't be written: export DWG, or export DXF instead, which CAD apps open")];
|
||||
|
||||
/// The hint for an id or extension (any case, leading dot allowed) that names a read-only kind of
|
||||
/// file, even when its format is written under another extension (`.dws` is read as `dwg`).
|
||||
pub fn read_only_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint)
|
||||
}
|
||||
|
||||
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG,
|
||||
/// also a `.dws` or `.dwt` file).
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (a `.dws`
|
||||
/// or `.dwt` file).
|
||||
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint))
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| read_only_hint(&k))
|
||||
}
|
||||
|
||||
impl Unsupported {
|
||||
@@ -166,39 +188,42 @@ pub(crate) fn text(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `field` read by `read`, or an error listing what it may be.
|
||||
fn choice<T>(field: &str, v: Option<String>, read: impl Fn(&str) -> Option<T>, default: T, allowed: &str) -> Result<T> {
|
||||
/// `field` of a `kind` (DXF or DWG) export read by `read`, or an error listing what it may be.
|
||||
fn choice<T>(kind: &str, field: &str, v: Option<String>, read: impl Fn(&str) -> Option<T>, default: T, allowed: &str) -> Result<T> {
|
||||
match v {
|
||||
None => Ok(default),
|
||||
Some(s) => read(&s).ok_or_else(|| bad(C, format!("DXF {field} `{s}`: {allowed}"))),
|
||||
Some(s) => read(&s).ok_or_else(|| bad(C, format!("{kind} {field} `{s}`: {allowed}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice.
|
||||
fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("DXF options: {e}")))? } else { Params::default() };
|
||||
/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice; with
|
||||
/// `dwg`, a version a DWG file is written as.
|
||||
fn parse(p: &Value, dwg: bool) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
let kind = if dwg { "DWG" } else { "DXF" };
|
||||
let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("{kind} options: {e}")))? } else { Params::default() };
|
||||
// The options a preset sets are the defaults of those `p` leaves out.
|
||||
let d = choice("dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options();
|
||||
let d = choice(kind, "dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options();
|
||||
let scale = q.scale.unwrap_or(d.scale);
|
||||
if !(scale.is_finite() && vectorcraft_cad::SCALE_RANGE.contains(&scale)) {
|
||||
return Err(bad(C, format!("DXF scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end())));
|
||||
return Err(bad(C, format!("{kind} scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end())));
|
||||
}
|
||||
let version = q.version.as_ref().map(text);
|
||||
let version = if dwg {
|
||||
let read = |s: &str| DxfVersion::from_id(s).filter(|v| vectorcraft_cad::dwg::writes(*v));
|
||||
choice(kind, "version", version, read, d.version, &vectorcraft_cad::dwg::written_versions())?
|
||||
} else {
|
||||
choice(kind, "version", version, DxfVersion::from_id, d.version, "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018")?
|
||||
};
|
||||
let opts = DxfOptions {
|
||||
version: choice(
|
||||
"version",
|
||||
q.version.as_ref().map(text),
|
||||
DxfVersion::from_id,
|
||||
d.version,
|
||||
"R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018",
|
||||
)?,
|
||||
unit: choice("unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?,
|
||||
version,
|
||||
unit: choice(kind, "unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?,
|
||||
scale,
|
||||
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
|
||||
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
colors: choice(kind, "colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice(kind, "rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
include_images: q.include_images.unwrap_or(d.include_images),
|
||||
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
|
||||
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
preserve: choice(kind, "preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
|
||||
outline_text: q.outline_text.unwrap_or(d.outline_text),
|
||||
group_blocks: q.group_blocks.unwrap_or(d.group_blocks),
|
||||
@@ -207,21 +232,27 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
Ok((opts, q.boards))
|
||||
}
|
||||
|
||||
/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error).
|
||||
/// Is `p` a DWG export (`format: dwg`, or `.dwg` and the other names of the DWG format)?
|
||||
fn is_dwg(p: &Value) -> bool {
|
||||
p.get("format").and_then(Value::as_str).and_then(super::format).is_some_and(|f| f.id == "dwg")
|
||||
}
|
||||
|
||||
/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error);
|
||||
/// with `format: dwg`, as DWG options.
|
||||
pub fn check(p: &Value) -> std::result::Result<(), String> {
|
||||
parse(p).map(|_| ()).map_err(|e| e.to_string())
|
||||
parse(p, is_dwg(p)).map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The DXF options in `p` (the region and crop left at their defaults).
|
||||
pub fn options(p: &Value) -> std::result::Result<DxfOptions, String> {
|
||||
parse(p).map(|(o, _)| o).map_err(|e| e.to_string())
|
||||
parse(p, false).map(|(o, _)| o).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Encode `doc` as DXF: one drawing whose origin is the chosen artboard's bottom-left corner
|
||||
/// (default the first), or with `use_artboards` one drawing per chosen artboard (default all)
|
||||
/// holding the art over it.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let (opts, pick) = parse(p)?;
|
||||
/// Encode `doc` as DXF, or with `dwg` as DWG: one drawing whose origin is the chosen artboard's
|
||||
/// bottom-left corner (default the first), or with `use_artboards` one drawing per chosen artboard
|
||||
/// (default all) holding the art over it.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, dwg: bool) -> Result<Encoded> {
|
||||
let (opts, pick) = parse(p, dwg)?;
|
||||
let n = doc.artboards.len();
|
||||
let rect = |b: usize| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)));
|
||||
let drawings: Vec<(Option<usize>, Rect, bool)> = match use_artboards {
|
||||
@@ -234,7 +265,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
let b = match pick.resolve(n).map_err(|e| bad(C, e))?.as_deref() {
|
||||
None => 0,
|
||||
Some([b]) => *b,
|
||||
Some(_) => return Err(bad(C, "a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard")),
|
||||
Some(_) => return Err(bad(C, "a DXF or DWG drawing has one origin: pass useArtboards: true for one drawing per artboard")),
|
||||
};
|
||||
vec![(Some(b), rect(b)?, false)]
|
||||
}
|
||||
@@ -242,9 +273,23 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
|
||||
let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
let mut left_out = vectorcraft_cad::dwg::Unwritten::new();
|
||||
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
|
||||
enc.files.push((board, out.bytes));
|
||||
for w in out.warnings {
|
||||
let mut warnings = out.warnings;
|
||||
let bytes = if dwg {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let (bytes, unwritten) = vectorcraft_cad::dwg::from_dxf(&out.bytes, opts.version).map_err(|e| bad(C, e))?;
|
||||
for (kind, n) in unwritten {
|
||||
*left_out.entry(kind).or_insert(0) += n;
|
||||
}
|
||||
// The DXF writer's version notes ("true colour needs DXF 2004 or later") hold for the DWG.
|
||||
warnings = warnings.into_iter().map(|w| w.replacen("needs DXF ", "needs DWG ", 1)).collect();
|
||||
bytes
|
||||
} else {
|
||||
out.bytes
|
||||
};
|
||||
enc.files.push((board, bytes));
|
||||
for w in warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
@@ -259,11 +304,12 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
enc.warnings.extend(vectorcraft_cad::dwg::left_out_warning(&left_out, enc.files.len()));
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut q = if p.is_object() { p.clone() } else { json!({}) };
|
||||
q["format"] = json!("dxf");
|
||||
q["format"] = json!(if is_dwg(p) { "dwg" } else { "dxf" });
|
||||
super::export::export(s, &q)
|
||||
}
|
||||
@@ -76,6 +76,16 @@ pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec<S
|
||||
Ok((r.document, r.warnings))
|
||||
}
|
||||
|
||||
/// A note for each linked image of a DXF or DWG drawing whose file is missing (the `missing` rows
|
||||
/// of [`crate::cmd::links::resolve`]): it shows a placeholder.
|
||||
pub(crate) fn missing_image_notes(missing: &[Value]) -> Vec<String> {
|
||||
missing
|
||||
.iter()
|
||||
.filter_map(|row| row["name"].as_str())
|
||||
.map(|name| format!("linked image '{name}' wasn't found: a placeholder keeps its place until it is relinked"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
const INFO: &str = "document.dxfInfo";
|
||||
|
||||
fn dxf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -135,6 +135,27 @@ pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `\` separates folders in a path: on Windows and on the web, where paths may come from
|
||||
/// Windows. On other platforms `\` is a character of a file name.
|
||||
const BACKSLASH_SEPARATES: bool = cfg!(any(windows, target_arch = "wasm32"));
|
||||
|
||||
/// The length of `path`'s folder part, its last separator included.
|
||||
fn dir_len(path: &str, backslash: bool) -> usize {
|
||||
let at = if backslash { path.rfind(['/', '\\']) } else { path.rfind('/') };
|
||||
at.map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dir_tests {
|
||||
#[test]
|
||||
fn a_backslash_is_part_of_a_file_name_where_it_does_not_separate_folders() {
|
||||
assert_eq!(super::dir_len("out/a\\b.svg", false), 4, "the file a\\b.svg is in out/");
|
||||
assert_eq!(super::dir_len("a\\b.svg", false), 0);
|
||||
assert_eq!(super::dir_len("out\\a\\b.svg", true), 6);
|
||||
assert_eq!(super::dir_len("b.svg", true), 0);
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoded {
|
||||
pub(super) fn one(bytes: Vec<u8>) -> Self {
|
||||
Self { files: vec![(None, bytes)], ..Self::default() }
|
||||
@@ -180,7 +201,7 @@ impl Encoded {
|
||||
/// under their own names, then the image maps as `{image stem}.html` or `.map`.
|
||||
pub fn named<'a>(&'a self, doc: &Document, path: &str) -> Vec<(String, Cow<'a, [u8]>)> {
|
||||
// Siblings keep the path's own separators (this runs on every platform and on the web).
|
||||
let dir = &path[..path.rfind(['/', '\\']).map_or(0, |i| i + 1)];
|
||||
let dir = &path[..dir_len(path, BACKSLASH_SEPARATES)];
|
||||
let sibling = |name: &str| format!("{dir}{name}");
|
||||
let mut out: Vec<(String, Cow<[u8]>)> = match self.files.as_slice() {
|
||||
[(_, bytes)] => vec![(path.to_string(), Cow::Borrowed(bytes.as_slice()))],
|
||||
@@ -1115,7 +1136,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards =
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1155,7 +1176,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
"txt" => super::text::encode(doc, p)?,
|
||||
"svg" | "svgz" => return super::svg::encode(doc, p, f.id == "svgz").map_err(|e| bad(C, e)),
|
||||
"dxf" => return super::dxf::encode(doc, p, use_artboards),
|
||||
"dxf" | "dwg" => return super::dxf::encode(doc, p, use_artboards, f.id == "dwg"),
|
||||
// EPS reads its own `useArtboards` (the art's bounds unless asked).
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
|
||||
@@ -587,13 +587,27 @@ pub const FORMATS: &[Format] = &[
|
||||
raster: false,
|
||||
options: metafile::OPTIONS,
|
||||
},
|
||||
// Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths,
|
||||
// type and images. Behind the `cgm` feature until craft-libs#5410 merges.
|
||||
#[cfg(feature = "cgm")]
|
||||
reader("cgm", "CGM", &["cgm"], "image/cgm", false),
|
||||
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
|
||||
// reader with the DXF import options; `.dws` drawing standards files are DWG drawings too.
|
||||
// Exports don't write them.
|
||||
reader("dwg", "DWG", &["dwg", "dws"], "image/vnd.dwg", false),
|
||||
// Exports write the DXF writer's drawing, converted by craft-dwg, as versions 2000 to 2018,
|
||||
// to `.dwg` only: exporting to `dws` answers with the read-only hint.
|
||||
Format {
|
||||
id: "dwg",
|
||||
label: "DWG",
|
||||
extensions: &["dwg", "dws"],
|
||||
mime: "image/vnd.dwg",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: dxf::DWG_OPTIONS,
|
||||
},
|
||||
// `.dwt` drawing templates, DWG drawings read as `dwg` is; a template opens as a new untitled
|
||||
// document. Exports don't write them.
|
||||
reader("dwt", "DWG Template", &["dwt"], "image/vnd.dwg", false),
|
||||
@@ -650,6 +664,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
@@ -676,7 +692,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers
|
||||
/// offer VectorCraft for them.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here
|
||||
/// when the `cgm` feature is turned on (craft-libs#5410).
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
@@ -757,6 +774,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
"hgl",
|
||||
@@ -1181,6 +1200,12 @@ pub fn format_for_name(name: &str) -> Option<&'static Format> {
|
||||
pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::result::Result<&'static Format, String> {
|
||||
// Formats that can't be written say what to use instead.
|
||||
let unknown = |what: String, key: &str| unsupported(key).map_or(what, |u| u.hint.to_string());
|
||||
// A read-only kind of file read under a written format's id (`.dws` is read as `dwg`), named by
|
||||
// the format or by the path the file would be written to.
|
||||
let path_ext = path.map(extension).filter(|e| !e.is_empty());
|
||||
if let Some(hint) = format_param.into_iter().chain(path_ext.as_deref()).find_map(super::dxf::read_only_hint) {
|
||||
return Err(hint.to_string());
|
||||
}
|
||||
let f = match (format_param, path.map(extension).filter(|e| !e.is_empty())) {
|
||||
(Some(f), _) => format(f).ok_or_else(|| unknown(format!("unknown format `{f}` (see document.formats)"), f))?,
|
||||
(None, Some(e)) => format(&e).ok_or_else(|| unknown(format!("unknown extension `.{e}`: pass `format` (see document.formats)"), &e))?,
|
||||
|
||||
@@ -134,6 +134,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if let Some(kind) = vectorcraft_metafile::sniff(bytes) {
|
||||
return format(kind.id());
|
||||
}
|
||||
if vectorcraft_metafile::is_cgm(bytes) {
|
||||
return format("cgm");
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
return format(if psdread::is_psb(bytes) { "psb" } else { "psd" });
|
||||
}
|
||||
@@ -581,6 +584,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings) = super::metafile::import_pict(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"cgm" => {
|
||||
let (doc, warnings) = super::metafile::import_cgm(bytes)?;
|
||||
(doc, warnings, false)
|
||||
}
|
||||
"hpgl" => {
|
||||
let i = vectorcraft_cad::hpgl::import(bytes).map_err(err)?;
|
||||
(i.document, i.warnings, false)
|
||||
@@ -920,6 +927,9 @@ impl ReadFile {
|
||||
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
|
||||
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
|
||||
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
|
||||
if matches!(self.loaded.format.id, "dxf" | "dwg") {
|
||||
self.loaded.warnings.extend(super::dxfimport::missing_image_notes(&self.links.missing));
|
||||
}
|
||||
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
|
||||
if !self.loaded.warnings.contains(¬e) {
|
||||
self.loaded.warnings.push(note);
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
|
||||
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
|
||||
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
|
||||
//! QuickDraw pictures (PICT) are written (`format: pict`) and open and place the same way.
|
||||
//! QuickDraw pictures (PICT) are written (`format: pict`) and open and place the same way. Binary
|
||||
//! Computer Graphics Metafiles (CGM) open and place the same way; they are never written.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -78,3 +79,9 @@ pub(super) fn import_pict(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_pict(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
|
||||
/// A binary CGM's first picture as a document, and the import's warnings.
|
||||
pub(super) fn import_cgm(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
let p = vectorcraft_metafile::import_cgm(bytes).map_err(super::err)?;
|
||||
Ok((p.document, p.warnings))
|
||||
}
|
||||
@@ -1086,17 +1086,15 @@ impl SaveJob {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force, and as a write target, before
|
||||
// the first file is written. A refused file is not handed to `write`, so a writer that does
|
||||
// not check the file access writes none of the files; the error is the file access's own
|
||||
// refusal, as the writers that check it give.
|
||||
// the first file is written. A refused file, or a folder at a file's path, is not handed to
|
||||
// `write`, so a writer that does not check the file access writes none of the files; the
|
||||
// error is the file access's own refusal, as the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e };
|
||||
for (p, _) in &files {
|
||||
super::may_write(p).map_err(|e| named(e, p))?;
|
||||
}
|
||||
for (p, _) in &files {
|
||||
super::access::regular_write_target(p).map_err(|e| named(e, p))?;
|
||||
if let Some(refused) = files.iter().find_map(|(p, _)| {
|
||||
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
|
||||
}) {
|
||||
return Err(refused);
|
||||
}
|
||||
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "pict"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 9] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg", "pict"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -534,7 +534,8 @@ fn export_extensions_name_every_writable_format() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pct"
|
||||
"pct",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
for e in exts {
|
||||
@@ -572,7 +573,8 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pict"
|
||||
"pict",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
@@ -659,7 +661,7 @@ fn export_without_path_returns_bytes_and_never_retargets() {
|
||||
let r = s.execute("document.export", &json!({"format": "jpg"})).unwrap();
|
||||
assert_eq!(&b64(&r)[..2], [0xFF, 0xD8]);
|
||||
assert!(r.get("path").is_none());
|
||||
assert!(s.execute("document.export", &json!({"path": dir.join("x.dwg").to_string_lossy()})).is_err(), "DWG can't be written");
|
||||
assert!(s.execute("document.export", &json!({"path": dir.join("x.pmd").to_string_lossy()})).is_err(), "PageMaker can't be written");
|
||||
// A never-saved document hands its native bytes back.
|
||||
let mut s = session(10.0, 10.0, 1);
|
||||
let r = s.execute("document.save", &json!({})).unwrap();
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Binary CGM files through the commands: `document.open` by extension or by content, File › Place
|
||||
//! as one group clipped to the picture's frame, the dialogs' filters and the format list, and
|
||||
//! files that aren't binary CGM, or a CGM export, refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(bytes)
|
||||
}
|
||||
|
||||
/// One element, padded to an even length.
|
||||
fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = ((class << 12) | (id << 5) | data.len() as u16).to_be_bytes().to_vec();
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn words(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A binary CGM whose picture is 1000 × 500 units at 0.2 mm a unit (200 × 100 mm): a solid
|
||||
/// rectangle and a line.
|
||||
fn picture() -> Vec<u8> {
|
||||
let mut b = el(0, 1, b"\x04logo");
|
||||
b.extend(el(1, 1, &words(&[1])));
|
||||
b.extend(el(0, 3, b"\x01p"));
|
||||
b.extend(el(2, 1, &[words(&[1]), 0.2f32.to_be_bytes().to_vec()].concat()));
|
||||
b.extend(el(2, 6, &words(&[0, 0, 1000, 500])));
|
||||
b.extend(el(0, 4, &[]));
|
||||
b.extend(el(5, 22, &words(&[1])));
|
||||
b.extend(el(4, 11, &words(&[100, 100, 400, 300])));
|
||||
b.extend(el(4, 1, &words(&[0, 450, 1000, 450])));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
#[test]
|
||||
fn document_open_reads_a_picture() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": "part.cgm", "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("cgm"), Some("part.cgm")), "{r}");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let st = s.doc().unwrap();
|
||||
let size = st.doc.artboards[0].rect.size();
|
||||
assert!((size.width - 200.0 * MM).abs() < 1e-3 && (size.height - 100.0 * MM).abs() < 1e-3, "{size:?}");
|
||||
let mut paths = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.push(n.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 2);
|
||||
let b = paths[0].geometric_bounds().unwrap();
|
||||
assert!((b.x0 - 20.0 * MM).abs() < 1e-3 && (b.width() - 60.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
assert!(st.path.is_none(), "opened as artwork: Save asks for a name");
|
||||
|
||||
// A CGM opens by its content under a name no format reads.
|
||||
for name in ["part.CGM", "part.bin", "part"] {
|
||||
let r = Session::new().execute("document.open", &json!({"name": name, "dataBase64": b64(&picture())})).unwrap();
|
||||
assert_eq!(r["format"].as_str(), Some("cgm"), "{name}: {r}");
|
||||
}
|
||||
assert_eq!(detect("part.dat", &picture()).map(|f| f.id), Some("cgm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_place_places_a_picture_as_one_clipped_group() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let p = json!({"name": "part.cgm", "dataBase64": b64(&picture()), "at": [400, 400]});
|
||||
let info = s.execute("file.place.info", &p).unwrap();
|
||||
assert_eq!(info["format"], "cgm", "{info}");
|
||||
assert!((info["width"].as_f64().unwrap() - 200.0 * MM).abs() < 1e-3, "{info}");
|
||||
let r = s.execute("file.place", &p).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("cgm"), Some(1)), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let group = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(group.name.as_deref(), Some("part.cgm"));
|
||||
let NodeKind::Group { clip: true, .. } = &group.kind else { panic!("a clipping group, got {:?}", group.kind) };
|
||||
let b = group.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 200.0 * MM).abs() < 1e-3 && (b.height() - 100.0 * MM).abs() < 1e-3, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_cgm_are_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let e = s.execute("document.open", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).expect_err("refused");
|
||||
assert!(e.to_string().contains("not a CGM file"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), (100.0, 50.0).into());
|
||||
assert!(s.execute("file.place", &json!({"name": "old.cgm", "dataBase64": b64(&[0; 64])})).is_err());
|
||||
let e = s.execute("document.open", &json!({"name": "text.cgm", "dataBase64": b64(b"BEGMF 'x';")})).expect_err("refused");
|
||||
assert!(e.to_string().contains("only binary CGM files"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "cgm"})).expect_err("refused").to_string();
|
||||
assert!(e.contains("CGM files can be opened but not written"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dialogs_and_the_format_list_name_cgm() {
|
||||
assert!(OPEN_EXTS.contains(&"cgm") && PLACE_EXTS.contains(&"cgm") && UNASSOCIATED_EXTS.contains(&"cgm"));
|
||||
assert_eq!(format_for_name("a.cgm").map(|f| f.id), Some("cgm"));
|
||||
let filter = ("CGM", &["cgm"][..]);
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "cgm").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
|
||||
assert_eq!(f["mime"], "image/cgm");
|
||||
assert!(writable_format(None, Some("x/part.cgm")).is_err());
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG
|
||||
//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read
|
||||
//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32
|
||||
//! and FreeBSD on aarch64.
|
||||
//! drawing as the DXF it converts to, with the DXF options; `document.export` writes the DXF
|
||||
//! writer's drawing as a DWG of version 2000 or later. 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"))))]
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -102,12 +102,73 @@ fn a_dwg_opened_is_never_written_back_as_dwg() {
|
||||
s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("not DWG"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The bytes of the one file `document.export` handed back.
|
||||
fn exported(r: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dxf", &plan(), json!({})).unwrap();
|
||||
let dxf = exported(&s.execute("document.export", &json!({"format": "dxf", "version": "2000"})).unwrap());
|
||||
let r = s.execute("document.export", &json!({"format": "dwg", "version": "2000"})).unwrap();
|
||||
let dwg = exported(&r);
|
||||
assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1015"));
|
||||
assert!(r["warnings"].as_array().is_none_or(|w| w.iter().all(|w| !w.as_str().unwrap_or("").starts_with("DWG:"))), "{r}");
|
||||
open(&mut s, "again.dxf", &dxf, json!({})).unwrap();
|
||||
let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len());
|
||||
open(&mut s, "again.dwg", &dwg, json!({})).unwrap();
|
||||
assert_eq!(layer_names(&s), want_layers);
|
||||
assert_eq!(leaves(&s).len(), want_leaves);
|
||||
// The default version is 2018, and `.dwg` in the path picks the format.
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-export-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("out.dwg");
|
||||
let r = s.execute("document.export", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["format"], "dwg");
|
||||
assert_eq!(craft_dwg::version(&std::fs::read(&path).unwrap()).as_deref(), Some("AC1032"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A canceled export stops before converting any drawing to DWG.
|
||||
#[test]
|
||||
fn a_canceled_dwg_export_converts_no_drawing() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = crate::cancel::scope(&token, None, || super::dxf::encode(doc, &json!({}), Some(true), true));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{:?}", r.map(|e| e.files.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_before_2000_is_refused_and_nothing_is_written() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dxf", &plan(), json!({})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-r14-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("old.dwg");
|
||||
for version in ["R12", "R13", "R14"] {
|
||||
let e = s.execute("document.export", &json!({"path": path.to_string_lossy(), "version": version})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("DWG version `{version}`")) && e.contains("2000") && e.contains("2018"), "{e}");
|
||||
}
|
||||
assert!(!path.exists());
|
||||
// The same versions are DXF versions.
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "version": "R14"})).unwrap();
|
||||
assert!(String::from_utf8_lossy(&exported(&r)).contains("AC1014"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_info_and_place_read_a_dwg() {
|
||||
let mut s = Session::new();
|
||||
@@ -129,15 +190,17 @@ fn dxf_info_and_place_read_a_dwg() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwg_is_read_only_and_detected_by_content() {
|
||||
fn dwg_is_read_and_written_and_detected_by_content() {
|
||||
let f = format("dwg").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(f.read && f.write);
|
||||
let version = f.options.iter().find(|o| o.name == "version").unwrap();
|
||||
assert!(!version.description.contains("R14") && version.description.contains("2000"), "{}", version.description);
|
||||
assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg"));
|
||||
assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
assert!(r["readable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
|
||||
}
|
||||
|
||||
@@ -204,5 +267,9 @@ fn dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf() {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"format": ext})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{ext}: {e}");
|
||||
let path = std::env::temp_dir().join(format!("vc-dwg-alias-{}.{ext}", std::process::id()));
|
||||
let e = s.execute("document.export", &json!({"format": "dwg", "path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "format dwg to a .{ext} path: {e}");
|
||||
assert!(!path.exists(), "nothing is written to {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! DXF export through the commands: options, artboards, selection, images, and the formats that
|
||||
//! can't be written (DWG, which opens, and PageMaker).
|
||||
//! can't be written (PICT, which opens, and PageMaker).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -320,12 +320,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwg_and_pagemaker_say_what_to_use_instead() {
|
||||
fn pict_and_pagemaker_say_what_to_use_instead() {
|
||||
let mut s = two_boards();
|
||||
for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] {
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}");
|
||||
}
|
||||
// PCX opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pcx"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PCX files can be opened but not written"), "{e}");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! DXF through the commands: `document.open` with the DXF options, `document.dxfInfo`,
|
||||
//! File → Place of a drawing (fitted, centred or at its origin), the format table, binary files,
|
||||
//! and a drawing `document.export` wrote opened again.
|
||||
//! a drawing `document.export` wrote opened again, and the image files a drawing links to.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
@@ -268,3 +268,102 @@ fn a_drawing_export_writes_opens_again() {
|
||||
let union = all.iter().copied().reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!((union.width() - 350.0).abs() < 2.0 && (union.y1 - h + 200.0).abs() < 2.0, "{union:?} on {h}");
|
||||
}
|
||||
|
||||
/// A folder of a drawing linking `img\photo.png`, a 30 × 20 pixel PNG beside it, and `gone.png`,
|
||||
/// which isn't there (removed when dropped).
|
||||
struct Linked(std::path::PathBuf);
|
||||
|
||||
impl Linked {
|
||||
fn new(tag: &str) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-dxfimage-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("img")).unwrap();
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
30,
|
||||
20,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[230u8, 20, 20, 255].repeat(600),
|
||||
)
|
||||
.unwrap();
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
std::fs::write(dir.join("img").join("photo.png"), png).unwrap();
|
||||
let image = |def: &'static str, x: &'static str| {
|
||||
vec![(0, "IMAGE"), (8, "0"), (10, x), (20, "0"), (11, "1"), (21, "0"), (12, "0"), (22, "1"), (13, "30"), (23, "20"), (340, def)]
|
||||
};
|
||||
let mut pairs: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
|
||||
pairs.extend([(0, "SECTION"), (2, "ENTITIES")]);
|
||||
pairs.extend(image("1F", "0"));
|
||||
pairs.extend(image("2A", "100"));
|
||||
pairs.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "1F"), (1, r"img\photo.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "IMAGEDEF"), (5, "2A"), (1, "gone.png"), (10, "30"), (20, "20")]);
|
||||
pairs.extend([(0, "ENDSEC"), (0, "EOF")]);
|
||||
let text: String = pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect();
|
||||
std::fs::write(dir.join("plan.dxf"), text).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
fn drawing(&self) -> String {
|
||||
self.0.join("plan.dxf").to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Linked {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The images of the active document: each one's link's file name, size, and whether its pixels
|
||||
/// are its file's (not the placeholder).
|
||||
fn images(s: &Session) -> Vec<(String, (u32, u32), bool)> {
|
||||
let st = s.doc().unwrap();
|
||||
let mut out = vec![];
|
||||
st.doc.visit_images(|_, im| {
|
||||
let read = st.doc.images.get(&im.key).is_some_and(|b| !b.is_proxy());
|
||||
out.push((im.link.as_ref().map(|l| l.name().to_string()).unwrap_or_default(), (im.width, im.height), read));
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("open");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": dir.drawing()})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let missing = r["missingLinks"].as_array().unwrap();
|
||||
assert_eq!(missing.iter().map(|m| m["name"].as_str()).collect::<Vec<_>>(), [Some("gone.png")], "{r}");
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w.contains("photo.png")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() {
|
||||
let dir = Linked::new("place");
|
||||
let mut s = page();
|
||||
let r = s.execute("file.place", &json!({"path": dir.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]);
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_drawing_keeps_missing_links_anchored_to_its_folder() {
|
||||
let source = Linked::new("place-missing-source");
|
||||
let destination = Linked::new("place-missing-destination");
|
||||
let mut s = page();
|
||||
s.doc_mut().unwrap().path = Some(destination.0.join("art.vectorcraft").to_string_lossy().into_owned());
|
||||
s.execute("file.place", &json!({"path": source.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap();
|
||||
let mut missing = vec![];
|
||||
s.doc().unwrap().doc.visit_images(|_, im| {
|
||||
if let Some(link) = im.link.as_ref().filter(|link| link.name() == "gone.png") {
|
||||
missing.push(std::path::PathBuf::from(&link.path));
|
||||
}
|
||||
});
|
||||
assert_eq!(missing, [source.0.join("gone.png")]);
|
||||
assert!(missing[0].is_absolute());
|
||||
assert!(!missing[0].starts_with(&destination.0));
|
||||
}
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|true (50)|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard, and the artboard's own screen print marks group wherever it lies, while another artboard's group lying on it stays with its own), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
@@ -1273,6 +1273,7 @@ pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Sele
|
||||
for &id in &gone {
|
||||
d.retire_artboard_id(id);
|
||||
}
|
||||
super::addons::release_screen_marks(d, &gone);
|
||||
d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a)));
|
||||
count_artboard_pass();
|
||||
Ok(())
|
||||
@@ -1417,7 +1418,6 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let delta = now.origin() - was.origin();
|
||||
let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO;
|
||||
let transform = fit.or_else(|| moving.then(|| Affine::translate(delta)));
|
||||
let art = if transform.is_some() { d.art_moving_with(index, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] };
|
||||
edits.push(ArtboardEdit {
|
||||
index,
|
||||
now,
|
||||
@@ -1433,9 +1433,29 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
resized,
|
||||
fit,
|
||||
transform,
|
||||
art,
|
||||
art: vec![],
|
||||
});
|
||||
}
|
||||
// The artboards that move take their own screen print marks groups wherever they lie, and not
|
||||
// another artboard's lying on them, as Move Artboard does. An artboard that scales in the same
|
||||
// call leaves a moving artboard's marks lying on it to their own artboard.
|
||||
// One pass for all of them, in the order listed.
|
||||
let movers: Vec<usize> = edits.iter().filter(|e| e.transform.is_some() && e.fit.is_none()).map(|e| e.index).collect();
|
||||
let mut found = super::panelcmds::artboards_art(s, &movers, true, all, true)?.into_iter();
|
||||
let moved: Vec<Option<Vec<NodeId>>> =
|
||||
edits.iter().map(|e| (e.transform.is_some() && e.fit.is_none()).then(|| found.next().map(|(_, a)| a).unwrap_or_default())).collect();
|
||||
// Every group that belongs to a moving artboard, taken by it or left where it is; a group whose
|
||||
// artboard was deleted is ordinary art.
|
||||
let boards: HashSet<u32> = movers.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.id)).collect();
|
||||
let reserved: HashSet<NodeId> = super::addons::screen_marks_owners(d).into_iter().filter(|(_, o)| boards.contains(o)).map(|(id, _)| id).collect();
|
||||
for (e, own) in edits.iter_mut().zip(moved) {
|
||||
let art = match own {
|
||||
Some(art) => art,
|
||||
None if e.fit.is_some() => d.art_moving_with(e.index, all).into_iter().filter(|id| !reserved.contains(id)).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
e.art = art.into_iter().filter(|id| taken.insert(*id)).collect();
|
||||
}
|
||||
// Nothing to change: no undo step.
|
||||
if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) {
|
||||
return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() };
|
||||
|
||||
@@ -2050,6 +2050,36 @@ fn set_found_paths(d: &mut Document, base: LinkBase) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets each relative link path of `d`, a document read from `base`, whose file is not found to
|
||||
/// that path under `base`'s folder, so the link still looks for its file there once the art is
|
||||
/// placed into a document in another folder.
|
||||
pub(crate) fn anchor_missing_relative(d: &mut Document, base: LinkBase) {
|
||||
if base.doc.is_none() {
|
||||
return;
|
||||
}
|
||||
editing_brush_art(d, |d| {
|
||||
let mut anchored: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut look = |l: &LinkInfo| {
|
||||
if Path::new(&l.path).is_relative()
|
||||
&& !anchored.contains_key(&l.path)
|
||||
&& locate(l, base).is_none()
|
||||
&& let Ok(path) = fileio::document_path(&l.path, base.doc)
|
||||
{
|
||||
anchored.insert(l.path.clone(), path);
|
||||
}
|
||||
};
|
||||
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
d.visit_placed(|_, p| look(&p.link));
|
||||
if !anchored.is_empty() {
|
||||
d.update_links(|l| {
|
||||
if let Some(path) = anchored.get(&l.path) {
|
||||
l.path = path.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without
|
||||
/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not
|
||||
/// allow names its file alone, without its relative path or the size and date kept of its file,
|
||||
|
||||
@@ -901,7 +901,7 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
pub(crate) fn default_settings(&self) -> DocSettings {
|
||||
DocSettings { units: self.default_units(), ..DocSettings::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden). With art, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden; edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -306,16 +306,74 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving:
|
||||
})
|
||||
}
|
||||
|
||||
/// `arts` (artboard indices with their art) with each artboard's screen print marks group in its
|
||||
/// own artboard's entry: another artboard's group lying on one of them goes with its own artboard
|
||||
/// when that one is among `arts`, and is left out when it is not. Only the groups on the marks
|
||||
/// layer count; a group whose artboard was deleted stays where it is.
|
||||
/// `held(i, id)` says group `id` stays put for artboard `i`.
|
||||
pub(crate) fn marks_with_owners(
|
||||
d: &vectorcraft_doc::Document,
|
||||
arts: Vec<(usize, Vec<NodeId>)>,
|
||||
held: impl Fn(usize, NodeId) -> bool,
|
||||
) -> Vec<(usize, Vec<NodeId>)> {
|
||||
let owners = super::addons::screen_marks_owners(d);
|
||||
if owners.is_empty() {
|
||||
return arts;
|
||||
}
|
||||
let board = |i: usize| d.artboards.get(i).map(|a| a.id);
|
||||
let owner = |id: NodeId| owners.get(&id).copied().filter(|o| d.artboards.iter().any(|a| a.id == *o));
|
||||
let mut moved: Vec<(u32, NodeId)> = vec![];
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = arts
|
||||
.into_iter()
|
||||
.map(|(i, art)| {
|
||||
let art = art
|
||||
.into_iter()
|
||||
.filter(|id| match owner(*id) {
|
||||
Some(o) if Some(o) != board(i) => {
|
||||
moved.push((o, *id));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
(i, art)
|
||||
})
|
||||
.collect();
|
||||
for (o, id) in moved {
|
||||
if let Some((i, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o))
|
||||
&& !held(*i, id)
|
||||
{
|
||||
art.push(id);
|
||||
}
|
||||
}
|
||||
arts
|
||||
}
|
||||
|
||||
/// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object
|
||||
/// counted once, with the first of them it is on (artboards can overlap).
|
||||
/// counted once, with the first of them it is on (artboards can overlap). With `art`, each
|
||||
/// artboard takes its own eligible screen print marks group, wherever the group lies.
|
||||
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut arts = vec![];
|
||||
for &i in indices {
|
||||
let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let art: Vec<NodeId> = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
Ok(arts)
|
||||
let d = &s.doc()?.doc;
|
||||
// A move or a cut leaves a group lying on an artboard locked other than its own, as it leaves
|
||||
// other art there, unless locked and hidden art goes too.
|
||||
let held = |i: usize, id: NodeId| moving && !all && d.node(id).is_some_and(|n| d.locked_artboards_except(i).holds(n));
|
||||
if art {
|
||||
for (id, o) in super::addons::screen_marks_copied(d, all) {
|
||||
if let Some((i, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o))
|
||||
&& !held(*i, id)
|
||||
&& seen.insert(id)
|
||||
{
|
||||
own.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(marks_with_owners(d, arts, held))
|
||||
}
|
||||
|
||||
/// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste).
|
||||
@@ -399,7 +457,12 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
|
||||
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
|
||||
d.copy_artboard_guides(src.id, id, dv);
|
||||
}
|
||||
let to = d.artboards.get(index).map(|a| a.id);
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| {
|
||||
// A copy of the artboard's screen print marks belongs to the copy.
|
||||
if let Some(to) = to {
|
||||
let _ = super::addons::retag_screen_marks(c, src.id, to);
|
||||
}
|
||||
c.transform(Affine::translate(dv), sc);
|
||||
super::object::keep_pixel_aligned(c, sc);
|
||||
})?;
|
||||
|
||||
+156
-28
@@ -1,6 +1,6 @@
|
||||
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)",
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection); on a path with rounded Live Corners, an anchor added on a side keeps the corners live (the selection follows its corners), and one added on a corner's arc makes the path plain and answers with a warning",
|
||||
has_doc,
|
||||
insert_anchor
|
||||
),
|
||||
@@ -2158,18 +2158,9 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
if d.node(*id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if keep_joined
|
||||
&& !set.is_empty()
|
||||
&& !segments.contains_key(id)
|
||||
&& let Some(path) = d.node(*id).and_then(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect();
|
||||
if keep_joined && !set.is_empty() && !segments.contains_key(id) && d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })) {
|
||||
let anchors: Vec<(usize, usize)> = set.iter().copied().collect();
|
||||
let next = super::draw2::following_anchors(&shape, &anchors);
|
||||
if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? {
|
||||
if let Some(next) = super::draw2::remove_anchors_following(d, selection, &mut emptied, *id, anchors, false)? {
|
||||
survivors.push(*id);
|
||||
following.push((*id, next));
|
||||
}
|
||||
@@ -2212,9 +2203,13 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
for p in compounds {
|
||||
// A compound path left empty by an inner one that went is checked again after it.
|
||||
let mut compounds = compounds;
|
||||
while let Some(p) = compounds.pop_first() {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
let up = d.parent_of(p).filter(|u| matches!(d.node(*u).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
d.remove(p)?;
|
||||
compounds.extend(up);
|
||||
}
|
||||
}
|
||||
super::edit::release_empty_clips(d, clipped);
|
||||
@@ -2466,6 +2461,87 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f
|
||||
/// the same points.
|
||||
/// A selected segment that the new anchor splits stays selected as its two halves, and the new
|
||||
/// anchor joins its ends in the anchors that move with it.
|
||||
/// After anchor `new` of the uncut outline of path `id` was added on its segment `split` as drawn,
|
||||
/// and the path's corners were cut again, select the segments as drawn that run between the same
|
||||
/// anchors of the outline as `segments` (the path's selected segments before), each listed in
|
||||
/// `before` and `after` as [`corner_sources`] gives them, `before` numbered as the outline is after
|
||||
/// the addition. A selected `split` gives both its halves, and the new anchor is selected with
|
||||
/// them, as [`renumber_after_insert`] selects them on a plain path. A segment whose two ends were
|
||||
/// in `held` (the selected anchors that end a selected segment, as drawn before) has the ends of
|
||||
/// its segments as drawn selected, and no other anchor of their corners.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn remap_corner_segments(
|
||||
sel: &mut Selection,
|
||||
id: NodeId,
|
||||
segments: &BTreeSet<SegmentRef>,
|
||||
held: &BTreeSet<AnchorRef>,
|
||||
before: &[Vec<usize>],
|
||||
after: &[Vec<usize>],
|
||||
split: SegmentRef,
|
||||
new: usize,
|
||||
) {
|
||||
let ends = |sources: &[Vec<usize>], (si, g): SegmentRef| {
|
||||
let v = sources.get(si)?;
|
||||
Some((*v.get(g)?, *v.get((g + 1) % v.len())?))
|
||||
};
|
||||
// Each subpath's segments as drawn by the corners at their ends, the first one for each pair.
|
||||
let index: Vec<HashMap<(usize, usize), usize>> = after
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(si, v)| {
|
||||
let mut m = HashMap::new();
|
||||
for g in 0..v.len() {
|
||||
if let Some(pair) = ends(after, (si, g)) {
|
||||
m.entry(pair).or_insert(g);
|
||||
}
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let drawn = |si: usize, pair: (usize, usize)| index.get(si).and_then(|m| m.get(&pair)).map(|&g| (si, g));
|
||||
let mut out = BTreeSet::new();
|
||||
let mut picked = BTreeSet::new();
|
||||
for &r in segments {
|
||||
let Some((a, b)) = ends(before, r) else { continue };
|
||||
let found: Vec<SegmentRef> = if r == split {
|
||||
[drawn(r.0, (a, new)), drawn(r.0, (new, b))].into_iter().flatten().collect()
|
||||
} else {
|
||||
drawn(r.0, (a, b)).into_iter().collect()
|
||||
};
|
||||
let len = before.get(r.0).map_or(0, Vec::len);
|
||||
if len > 0 && held.contains(&r) && held.contains(&(r.0, (r.1 + 1) % len)) {
|
||||
let n = after.get(r.0).map_or(0, Vec::len);
|
||||
picked.extend(found.iter().flat_map(|&(si, g)| [(si, g), (si, (g + 1) % n.max(1))]));
|
||||
}
|
||||
if r == split
|
||||
&& let Some(ai) = after.get(r.0).and_then(|v| v.iter().position(|k| *k == new))
|
||||
{
|
||||
picked.insert((r.0, ai));
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
if !picked.is_empty() {
|
||||
sel.anchors.entry(id).or_default().extend(picked);
|
||||
}
|
||||
if sel.anchors.get(&id).is_some_and(BTreeSet::is_empty) {
|
||||
sel.anchors.remove(&id);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
sel.segments.insert(id, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors as drawn that end the segments in `segments`, on subpaths of the lengths `sources`
|
||||
/// lists ([`corner_sources`]).
|
||||
fn segment_ends(segments: &BTreeSet<SegmentRef>, sources: &[Vec<usize>]) -> BTreeSet<AnchorRef> {
|
||||
let mut out = BTreeSet::new();
|
||||
for &(si, g) in segments {
|
||||
let Some(n) = sources.get(si).map(Vec::len).filter(|n| *n > 0 && g < *n) else { continue };
|
||||
out.extend([(si, g), (si, (g + 1) % n)]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) {
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
// A selected anchor index can name no anchor (`select.anchors` takes any index), so the
|
||||
@@ -2624,17 +2700,17 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
|
||||
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
|
||||
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
|
||||
let idx = s.edit("Add Anchor Point", |d, sel| {
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
let (idx, expanded) = s.edit("Add Anchor Point", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
if select_anchor || !sel.contains(id) {
|
||||
sel.clear();
|
||||
}
|
||||
@@ -2644,9 +2720,53 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.key_anchor = None;
|
||||
}
|
||||
sel.add(id);
|
||||
return Ok(idx);
|
||||
return Ok((idx, false));
|
||||
}
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
let (path, live) = match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Path { path, live, .. }) => (path, live),
|
||||
Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))),
|
||||
None => return Err(EngineError::NoNode(id)),
|
||||
};
|
||||
if seg >= path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
// A plain path has no corners to keep, so it skips the Live Corners work.
|
||||
let (before, cut) = match live.as_deref().and_then(|l| vectorcraft_doc::LiveCorners::new(path, Some(l))) {
|
||||
Some(lc) => (Some(lc.sources().to_vec()), lc.is_cut()),
|
||||
None => (None, false),
|
||||
};
|
||||
let kept = match (&before, d.node_mut(id).map(|n| &mut n.kind)) {
|
||||
(Some(_), Some(NodeKind::Path { path, live, .. })) => vectorcraft_doc::insert_corner_anchor(path, live, si, seg, t),
|
||||
_ => None,
|
||||
};
|
||||
let after = if kept.is_some() { corner_sources(d, id) } else { None };
|
||||
let idx = match (kept, before, after) {
|
||||
// The corners stay live: the selection follows the corners its anchors come from, the
|
||||
// outline's anchors after the new one numbered one higher.
|
||||
(Some(idx), Some(before), Some(after)) => {
|
||||
let new = after.get(si).and_then(|v| v.get(idx)).copied().unwrap_or(usize::MAX);
|
||||
let before: Vec<Vec<usize>> = before.iter().map(|v| v.iter().map(|k| if *k >= new { k + 1 } else { *k }).collect()).collect();
|
||||
let segments = sel.segments.get(&id).cloned().unwrap_or_default();
|
||||
// The ends of selected segments follow the segments, not their whole corners.
|
||||
let ends = segment_ends(&segments, &before);
|
||||
let mut held = BTreeSet::new();
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
held = set.intersection(&ends).copied().collect();
|
||||
set.retain(|r| !ends.contains(r));
|
||||
}
|
||||
remap_corner_anchors(sel, id, &before, &after);
|
||||
remap_corner_segments(sel, id, &segments, &held, &before, &after, (si, seg), new);
|
||||
idx
|
||||
}
|
||||
_ => {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let idx = sp.insert_anchor(seg, t);
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
idx
|
||||
}
|
||||
};
|
||||
let expanded = cut && kept.is_none();
|
||||
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
|
||||
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
|
||||
// for a path that is selected.
|
||||
@@ -2655,11 +2775,19 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.add(id);
|
||||
sel.anchors.entry(id).or_default().insert((si, idx));
|
||||
}
|
||||
Ok(idx)
|
||||
Ok((idx, expanded))
|
||||
})?;
|
||||
Ok(json!({ "anchor": idx }))
|
||||
let mut out = json!({ "anchor": idx });
|
||||
if expanded {
|
||||
out["warning"] = json!(CORNERS_EXPANDED);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The status when adding an anchor point turned a path's Live Corners into plain anchor points.
|
||||
/// Anchors added on a straight or curved side keep them; one added on a corner's curve does not.
|
||||
const CORNERS_EXPANDED: &str = "Live Corners were expanded: the rounded corners are now plain anchor points";
|
||||
|
||||
fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "path.cutAtAnchors";
|
||||
let st = s.doc()?;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! [`fileio::psd_slices`]).
|
||||
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
|
||||
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
|
||||
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! - An EMF, WMF, PICT or CGM picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
//! bounded by its art (`crop: "bounding"`).
|
||||
//! - An EPS file (or a PostScript .ai) becomes one group, clipped to its bounding box or bounded by
|
||||
//! its art: the document an EPS file of ours carries, else what its PostScript draws, else its
|
||||
@@ -377,7 +377,11 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: O
|
||||
));
|
||||
}
|
||||
// Linked images show their files, found from its folder.
|
||||
super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
let links = super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false);
|
||||
if matches!(format.id, "dxf" | "dwg") {
|
||||
l.warnings.extend(fileio::dxfimport::missing_image_notes(&links.missing));
|
||||
super::links::anchor_missing_relative(&mut l.doc, super::links::LinkBase::file(src.path));
|
||||
}
|
||||
(l.doc, l.warnings)
|
||||
};
|
||||
doc.drop_edit_modes();
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.screenMarks",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -80,10 +80,11 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
|
||||
}
|
||||
|
||||
/// The resolution Print as Bitmap renders `doc` at with `set` (ppi): `advanced.bitmapResolution`,
|
||||
/// or the document's raster effects resolution when that is 0.
|
||||
/// or the document's raster effects resolution when that is 0 (72 ppi when the stored value isn't a
|
||||
/// number).
|
||||
fn bitmap_ppi(doc: &Document, set: &PrintSettings) -> f64 {
|
||||
let asked = set.advanced.bitmap_resolution;
|
||||
if asked > 0.0 { asked } else { doc.raster_effects_ppi }
|
||||
if asked > 0.0 { asked } else { doc.raster_ppi() }
|
||||
}
|
||||
|
||||
/// The pixels per document point Print as Bitmap renders `area` at so that it prints at `ppi` on
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked. With moveArt, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
has_doc,
|
||||
artboard_move
|
||||
),
|
||||
@@ -685,13 +685,8 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !copy {
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
}
|
||||
// Each artboard's art, an object counted once (artboards can overlap).
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = vec![];
|
||||
for &i in &indices {
|
||||
let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?;
|
||||
let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
// Each artboard takes its art once and its own eligible screen print marks group.
|
||||
let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?;
|
||||
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
|
||||
let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| {
|
||||
|
||||
@@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 41] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -72,6 +72,7 @@ const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("addon.color.screenMarks", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
("edit.cut", "selectedArtboards"),
|
||||
|
||||
@@ -258,8 +258,9 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with, nor the Artboard tool's selection from the start of the run.
|
||||
// A document whose active artboard the script chose, or whose artboards the script added or
|
||||
// removed, uses its active artboard by id, not the index the run started with, nor the
|
||||
// Artboard tool's selection from the start of the run.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
|
||||
@@ -106,6 +106,7 @@ mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
mod paths;
|
||||
mod perspective;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod raster_capture;
|
||||
@@ -274,7 +275,8 @@ pub(super) struct State {
|
||||
layer_lists: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose its active
|
||||
/// artboard, or the script last added or removed one of its artboards.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
@@ -1749,19 +1751,27 @@ fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
|
||||
/// left out. The settings stay with the run, which hands the script an object of the
|
||||
/// `DocumentPreset` class.
|
||||
fn new_preset(h: &Host) -> Answer {
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
add_preset(
|
||||
h,
|
||||
vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// A new `DocumentPreset` of the run with the settings `fields`, which `new DocumentPreset()` and
|
||||
/// `app.getPresetSettings` both make.
|
||||
fn add_preset(h: &Host, fields: Vec<(String, Data)>) -> Answer {
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
if presets.len() >= MAX_PRESETS {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let fields = vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
];
|
||||
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
|
||||
presets.push(fields);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
@@ -3487,6 +3497,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
for (name, members) in perspective::enums() {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
@@ -3523,6 +3537,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(perspective::application_members(l));
|
||||
application.extend(preferences::app_members());
|
||||
application.extend(matrix::app_members(l));
|
||||
application.extend(clipboard::app_members(l));
|
||||
@@ -3609,6 +3624,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(perspective::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(print::document_members(l));
|
||||
|
||||
@@ -1401,7 +1401,10 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn board_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let (b, i) = this_board(h, a)?;
|
||||
let active = active_board_id(h, b.doc);
|
||||
on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, b.doc.uid, active);
|
||||
follow_active_board(h, b.doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1513,6 +1516,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
if len >= max {
|
||||
return Err(HostError::Range(format!("a document has at most {max} artboards")));
|
||||
}
|
||||
let active = active_board_id(h, doc);
|
||||
let id = super::atomically(h, |h| {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?;
|
||||
@@ -1529,6 +1533,8 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer {
|
||||
st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into()))
|
||||
})
|
||||
})?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(board_ref(h, doc.uid, id))
|
||||
}
|
||||
|
||||
@@ -1550,10 +1556,58 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
let len = with_doc(h, doc, |_, st| st.doc.artboards.len());
|
||||
let i = board_index_arg(arg(a, 1), len, "index")?;
|
||||
let active = active_board_id(h, doc);
|
||||
on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?;
|
||||
keep_active_board(h, doc.uid, active);
|
||||
follow_active_board(h, doc.uid);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The id and index of the artboard that is active in `doc` now, chosen or only the fallback.
|
||||
fn active_board_id(h: &Host, doc: Doc) -> Option<(u32, usize)> {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let i = active_artboard(st);
|
||||
st.doc.artboards.get(i).map(|ab| (ab.id, i))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keeps artboard `id` active in document `uid` by its id when it is still there, as
|
||||
/// `setActiveArtboardIndex` does, so an artboard added or removed before it moves its index
|
||||
/// instead of making another artboard the active one.
|
||||
/// A stored id of an artboard that is gone is replaced as well. In a document made during the run,
|
||||
/// the index the artboard had before the change is recorded for the run's report, as the first
|
||||
/// `setActiveArtboardIndex` records it.
|
||||
fn keep_active_board(h: &Host, uid: u64, active: Option<(u32, usize)>) {
|
||||
let Some((id, index)) = active else { return };
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
let Some(st) = s.document_mut(uid) else { return };
|
||||
if !st.doc.artboards.iter().any(|ab| ab.id == id) {
|
||||
return;
|
||||
}
|
||||
st.active_artboard = Some(id);
|
||||
}
|
||||
if !h.dom.boards_at_start.iter().any(|(u, _)| *u == uid) {
|
||||
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
|
||||
if !made.iter().any(|(u, _)| *u == uid) {
|
||||
made.push((uid, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays
|
||||
/// act on the document's active artboard by id, at the index the run's report gives it, as after
|
||||
/// `setActiveArtboardIndex`, until the document is reverted.
|
||||
fn follow_active_board(h: &Host, uid: u64) {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(u, _)| *u == uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((uid, reverts));
|
||||
}
|
||||
}
|
||||
|
||||
fn boards_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64)))
|
||||
@@ -1572,15 +1626,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
|
||||
}
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = with_doc(h, doc, |_, st| st.reverts);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((doc.uid, reverts));
|
||||
}
|
||||
}
|
||||
follow_active_board(h, doc.uid);
|
||||
// A document made during the run has no index from the start of the run, so the first choice
|
||||
// records one; an artboard inserted before it later still puts it in the report.
|
||||
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
|
||||
|
||||
@@ -719,7 +719,8 @@ thread_local! {
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path,
|
||||
/// image, placed document or visible type that lays out glyphs to clip by.
|
||||
/// image, placed document or visible type that lays out glyphs to clip by, or leave an image first
|
||||
/// in an ordinary group named as a tracing.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -798,13 +799,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let mut masks = Vec::new();
|
||||
for n in nodes.into_iter().rev() {
|
||||
let kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
|
||||
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none()
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& !kids.is_empty()
|
||||
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
|
||||
{
|
||||
// Without `keepEmpty`, clear removes compound paths whose members all go, emptied inner
|
||||
// compound paths included (`emptied_compounds`), but keeps empty groups. A compound
|
||||
// path's own `pathItems.removeAll()` keeps it, empty.
|
||||
if c.is_none() && matches!(n.kind, NodeKind::Compound { .. }) && !kids.is_empty() && kids.iter().all(|k| going.contains(&k.id)) {
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths, the frames of visible images and placed
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The perspective grid of a document and the New Document settings of a startup preset in the
|
||||
//! script object model, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>
|
||||
//! and <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> list them, with the values of
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/>.
|
||||
//!
|
||||
//! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with
|
||||
//! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them
|
||||
//! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows
|
||||
//! the grid and makes one undo step when the grid's geometry changes. As the Document page
|
||||
//! describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and
|
||||
//! `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already
|
||||
//! hidden.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has
|
||||
//! that name (in any case), and when the preset's grid is not of `gridType`; nothing changes then.
|
||||
//! - A one-point grid takes only the left and the floor plane as its active plane, as the archived
|
||||
//! scripting guide says
|
||||
//! (<https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf>).
|
||||
//! `INVALIDGRIDPLANETYPE` makes no plane active.
|
||||
//! - `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed.
|
||||
//! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new
|
||||
//! `DocumentPreset` with the settings a new document from that preset starts with, which
|
||||
//! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than
|
||||
//! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout
|
||||
//! of more than 100 artboards, and the layout of a grid by column that no row count lays out the
|
||||
//! same. Changing the result changes nothing else. Each result counts toward the run's limit
|
||||
//! of `DocumentPreset` objects, as `new DocumentPreset()` does.
|
||||
//! - `startupPresetsList` is an array of the startup preset names, each of which
|
||||
//! `documents.addDocument` and `getPresetSettings` take: `Print` first, then the other New
|
||||
//! Document profiles, then `Basic CMYK` and `Basic RGB`. Each read gives a new
|
||||
//! array; a script that changes that array does not change the list a later read gives.
|
||||
//! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset
|
||||
//! files are not available yet.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
|
||||
|
||||
use super::{
|
||||
Answer, Described, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, returns, startup_preset, text, this_doc, typed, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
|
||||
type Result<T> = std::result::Result<T, HostError>;
|
||||
|
||||
/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each.
|
||||
const GRID_TYPES: &[(&str, Option<u8>)] = &[
|
||||
("OnePointPerspectiveGridType", Some(1)),
|
||||
("TwoPointPerspectiveGridType", Some(2)),
|
||||
("ThreePointPerspectiveGridType", Some(3)),
|
||||
("InvalidPerspectiveGridType", None),
|
||||
];
|
||||
|
||||
/// The `PerspectiveGridPlaneType` values, with the plane of each.
|
||||
const PLANE_TYPES: &[(&str, Plane)] = &[
|
||||
("GRIDLEFTPLANETYPE", Plane::Left),
|
||||
("GRIDRIGHTPLANETYPE", Plane::Right),
|
||||
("GRIDFLOORPLANETYPE", Plane::Ground),
|
||||
("INVALIDGRIDPLANETYPE", Plane::None),
|
||||
];
|
||||
|
||||
/// The enumerations this module adds, as `dom::install` defines them.
|
||||
pub(super) fn enums() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
vec![
|
||||
("PerspectiveGridType", GRID_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
("PerspectiveGridPlaneType", PLANE_TYPES.iter().map(|(n, _)| *n).collect()),
|
||||
]
|
||||
}
|
||||
|
||||
/// The kind a `PerspectiveGridType` value names (`None`: `InvalidPerspectiveGridType`).
|
||||
fn grid_type(d: &Data) -> Result<Option<u8>> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridType.").and_then(|m| GRID_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, k)| *k).ok_or_else(|| HostError::Type("gridType must be a PerspectiveGridType value".into()))
|
||||
}
|
||||
|
||||
/// The plane a `PerspectiveGridPlaneType` value names.
|
||||
fn plane_type(d: &Data) -> Result<Plane> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("PerspectiveGridPlaneType.").and_then(|m| PLANE_TYPES.iter().find(|(n, _)| *n == m)),
|
||||
_ => None,
|
||||
};
|
||||
found.map(|(_, p)| *p).ok_or_else(|| HostError::Type("gridPlane must be a PerspectiveGridPlaneType value".into()))
|
||||
}
|
||||
|
||||
/// The document `this` names and its perspective grid, without the objects attached to it.
|
||||
fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::current(&st.doc))))
|
||||
}
|
||||
|
||||
/// `showPerspectiveGrid()`: shows the document's grid (its default one when none was defined).
|
||||
fn show_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": true})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `hidePerspectiveGrid()`: hides the document's grid. → whether a grid was hidden.
|
||||
fn hide_grid(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if !g.visible {
|
||||
return Ok(Data::Bool(false));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": false})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `getPerspectiveActivePlane()`: the grid's active plane, shown or hidden.
|
||||
fn active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, g) = grid(h, a)?;
|
||||
let name = PLANE_TYPES.iter().find(|(_, p)| *p == g.plane).map_or("INVALIDGRIDPLANETYPE", |(n, _)| *n);
|
||||
Ok(text(format!("PerspectiveGridPlaneType.{name}")))
|
||||
}
|
||||
|
||||
/// `setActivePlane(gridPlane)`: makes `gridPlane` the grid's active plane.
|
||||
fn set_active_plane(h: &Host, a: &[Data]) -> Answer {
|
||||
let plane = plane_type(arg(a, 1))?;
|
||||
let (doc, g) = grid(h, a)?;
|
||||
if g.kind == 1 && plane == Plane::Right {
|
||||
return Err(HostError::Range("a one-point grid has no right plane to make active".into()));
|
||||
}
|
||||
if g.plane != plane {
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.plane.set", &json!({"plane": plane.id()})))?;
|
||||
}
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// `selectPerspectivePreset(gridType, presetName)`: resets the grid to the preset `presetName`,
|
||||
/// which must be a grid of `gridType`.
|
||||
fn select_preset(h: &Host, a: &[Data]) -> Answer {
|
||||
let kind = grid_type(arg(a, 1))?.ok_or_else(|| HostError::Range("InvalidPerspectiveGridType has no presets".into()))?;
|
||||
let Data::String(name) = arg(a, 2) else { return Err(HostError::Type("presetName must be a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the preset's name is too long".into()));
|
||||
}
|
||||
let doc = this_doc(h, a)?;
|
||||
let preset = h.session.borrow().perspective_preset(name);
|
||||
let preset = preset.ok_or_else(|| HostError::Error(format!("no perspective grid preset called {name}")))?;
|
||||
if preset.kind != kind {
|
||||
return Err(HostError::Error(format!("the preset {} is not a grid of that type", preset.name)));
|
||||
}
|
||||
on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.preset", &json!({"name": preset.name})))?;
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The `RulerUnits` value of `u`, for the units `documents.addDocument` takes (`None`: other units,
|
||||
/// which a preset given back to `addDocument` keeps by leaving `units` out).
|
||||
fn units(u: crate::doc::Unit) -> Option<&'static str> {
|
||||
use crate::doc::Unit;
|
||||
Some(match u {
|
||||
Unit::Points => "RulerUnits.Points",
|
||||
Unit::Picas => "RulerUnits.Picas",
|
||||
Unit::Inches => "RulerUnits.Inches",
|
||||
Unit::Millimeters => "RulerUnits.Millimeters",
|
||||
Unit::Centimeters => "RulerUnits.Centimeters",
|
||||
Unit::Pixels => "RulerUnits.Pixels",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `artboardRowsOrCols` as `addDocument` reads it: the rows of a grid filled by column and the
|
||||
/// columns of the other layouts. `None`: a grid by column whose artboards no row count places the
|
||||
/// same.
|
||||
fn rows_or_cols(d: &crate::cmd::newdoc::DocSettings) -> Option<usize> {
|
||||
use crate::cmd::newdoc::ArtboardLayout;
|
||||
let n = d.artboards.max(1) as usize;
|
||||
if d.layout != ArtboardLayout::GridByColumn {
|
||||
return Some(d.grid_columns().max(1));
|
||||
}
|
||||
if d.rows > 0 {
|
||||
return Some((d.rows as usize).min(n));
|
||||
}
|
||||
let rows = n.div_ceil(d.grid_columns().max(1));
|
||||
let by_rows = crate::cmd::newdoc::DocSettings { rows: u32::try_from(rows).ok()?, ..d.clone() };
|
||||
(by_rows.boards() == d.boards()).then_some(rows)
|
||||
}
|
||||
|
||||
/// `app.getPresetSettings(preset)`: a new `DocumentPreset` with the settings a document from the
|
||||
/// startup preset `preset` starts with.
|
||||
fn preset_settings(h: &Host, a: &[Data]) -> Answer {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, PreviewMode};
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("getPresetSettings needs a startup preset's name".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the startup preset's name is too long".into()));
|
||||
}
|
||||
let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?;
|
||||
// The settings `documents.addDocument` starts from: the first built-in preset of the profile's
|
||||
// category, which a saved preset of the same name does not replace, else New Document's
|
||||
// starting settings.
|
||||
let d = {
|
||||
let s = h.session.borrow();
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&s, n)?.into_iter().next());
|
||||
first.unwrap_or_else(|| s.default_settings())
|
||||
};
|
||||
let cmyk = mode.map_or(d.color_mode == crate::doc::ColorMode::Cmyk, |m| m == "cmyk");
|
||||
let layout = match (d.layout, d.right_to_left) {
|
||||
(ArtboardLayout::GridByRow, false) => "GridByRow",
|
||||
(ArtboardLayout::GridByColumn, false) => "GridByCol",
|
||||
(ArtboardLayout::Row, false) => "Row",
|
||||
(ArtboardLayout::Column, _) => "Column",
|
||||
(ArtboardLayout::GridByRow, true) => "RLGridByRow",
|
||||
(ArtboardLayout::GridByColumn, true) => "RLGridByCol",
|
||||
(ArtboardLayout::Row, true) => "RLRow",
|
||||
};
|
||||
let preview = match d.preview_mode {
|
||||
PreviewMode::Default => Some("DefaultPreview"),
|
||||
PreviewMode::Pixel => None,
|
||||
PreviewMode::Overprint => Some("OverprintPreview"),
|
||||
};
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
let mut out = vec![
|
||||
item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))),
|
||||
item("artboardSpacing", num(d.spacing)),
|
||||
item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })),
|
||||
item("height", num(d.height)),
|
||||
item("width", num(d.width)),
|
||||
];
|
||||
if let Some(preview) = preview {
|
||||
out.push(item("previewMode", text(format!("DocumentPreviewMode.{preview}"))));
|
||||
}
|
||||
// The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them
|
||||
// back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row
|
||||
// count lays out the same), so `addDocument` with the same preset keeps the preset's own.
|
||||
if f64::from(d.artboards.max(1)) <= super::MAX_ARTBOARDS {
|
||||
out.push(item("numArtboards", num(f64::from(d.artboards.max(1)))));
|
||||
if let Some(n) = rows_or_cols(&d) {
|
||||
out.push(item("artboardRowsOrCols", num(super::float(n as u64))));
|
||||
}
|
||||
}
|
||||
if let Some(u) = units(d.units) {
|
||||
out.push(item("units", text(u)));
|
||||
}
|
||||
let resolutions = [(72.0, "ScreenResolution"), (150.0, "MediumResolution"), (300.0, "HighResolution")];
|
||||
if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) {
|
||||
out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}"))));
|
||||
}
|
||||
super::add_preset(h, out)
|
||||
}
|
||||
|
||||
/// The startup presets in the order `app.startupPresetsList` gives them: `Print` first, then the
|
||||
/// other New Document profiles, then the presets that give a document of one color mode.
|
||||
const STARTUP_PRESETS: [&str; 9] = ["Print", "Web", "Mobile", "Film & Video", "Art & Illustration", "Branding", "Social", "Basic CMYK", "Basic RGB"];
|
||||
|
||||
/// `app.startupPresetsList`: the names of the startup presets, as a new array.
|
||||
fn startup_presets(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(Data::Array(STARTUP_PRESETS.into_iter().map(text).collect()))
|
||||
}
|
||||
|
||||
/// The members this module adds to `Document`'s.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("showPerspectiveGrid", method(l, show_grid), returns("boolean", &[])),
|
||||
("hidePerspectiveGrid", method(l, hide_grid), returns("boolean", &[])),
|
||||
("getPerspectiveActivePlane", method(l, active_plane), returns("PerspectiveGridPlaneType", &[])),
|
||||
("setActivePlane", method(l, set_active_plane), returns("boolean", &[("gridPlane", "PerspectiveGridPlaneType")])),
|
||||
("selectPerspectivePreset", method(l, select_preset), returns("boolean", &[("gridType", "PerspectiveGridType"), ("presetName", "string")])),
|
||||
]);
|
||||
m.extend(["exportPerspectiveGridPreset", "importPerspectiveGridPreset"].into_iter().map(|n| later(l, "Document", n)));
|
||||
m
|
||||
}
|
||||
|
||||
/// The members this module adds to `Application`'s.
|
||||
pub(super) fn application_members(l: &Link) -> Vec<Described> {
|
||||
let mut m = named(vec![
|
||||
("getPresetSettings", method(l, preset_settings), returns("DocumentPreset", &[("preset", "string")])),
|
||||
("startupPresetsList", get(l, startup_presets), typed("Array")),
|
||||
]);
|
||||
let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"];
|
||||
m.extend(missing.into_iter().map(|n| later(l, "Application", n)));
|
||||
m
|
||||
}
|
||||
@@ -1033,7 +1033,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
|
||||
/// each assigned name against the list it must come from, and puts the checked names into the
|
||||
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
|
||||
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name`.
|
||||
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name` and no profile in the base settings.
|
||||
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
|
||||
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
|
||||
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
|
||||
|
||||
@@ -31,9 +31,10 @@
|
||||
//! when the name ends with `.svgz`.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
|
||||
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DWG
|
||||
//! (`.dwg`) with `AutoCADExportFileFormat.DWG`, the default, and DXF (`.dxf`) with
|
||||
//! `AutoCADExportFileFormat.DXF`. A DWG is written as version 2000 or later: `AutoCADRelease13`
|
||||
//! and `AutoCADRelease14` with DWG throw an error that names `AutoCADRelease15`. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
|
||||
//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is
|
||||
//! one drawing unit. It is at least 0.0001 and at most 1000.
|
||||
@@ -720,11 +721,7 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result:
|
||||
p.insert("outlineText".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"exportFileFormat" => {
|
||||
if pick("AutoCADExportFileFormat")? == "DWG" {
|
||||
return Err(HostError::Error(
|
||||
"AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(),
|
||||
));
|
||||
}
|
||||
p.insert("_dwg".into(), json!(pick("AutoCADExportFileFormat")? == "DWG"));
|
||||
}
|
||||
"exportOption" => {
|
||||
let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" };
|
||||
@@ -1041,9 +1038,17 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
// A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed
|
||||
// colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
// `AutoCADExportFileFormat.DWG` writes the same drawing as a DWG file.
|
||||
let kind = match p.remove("_dwg") {
|
||||
Some(Value::Bool(true)) => ExportKind { format: "dwg", extensions: &["dwg"], options: kind.options },
|
||||
_ => kind,
|
||||
};
|
||||
if kind.format == "dwg" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14")) {
|
||||
return Err(HostError::Error("AutoCADExportFileFormat.DWG needs AutoCADRelease15 or a later version".into()));
|
||||
}
|
||||
// A DXF or DWG version before 2004 holds no true color: with `colors` left out it takes 256
|
||||
// indexed colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if matches!(kind.format, "dxf" | "dwg") && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
match p.get("colors") {
|
||||
None => {
|
||||
p.insert("colors".into(), json!(256));
|
||||
@@ -1063,8 +1068,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
|
||||
}
|
||||
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
// A DXF's or DWG's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
|
||||
if !matches!(kind.format, "svg" | "dxf" | "dwg") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
let format = if svgz { "svgz" } else { kind.format };
|
||||
|
||||
@@ -47,10 +47,12 @@ fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
|
||||
}
|
||||
|
||||
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
|
||||
/// still be in its document.
|
||||
/// still be in its document. A tracing the run traced again is followed to the object that
|
||||
/// replaced it, which keeps its tags, as its `PluginItem` is.
|
||||
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = super::tracing::follow(h, doc.uid, id);
|
||||
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
|
||||
if !alive {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
@@ -111,7 +113,8 @@ fn doc_of_owner(owner: Owner) -> Doc {
|
||||
}
|
||||
|
||||
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
let [high, low] = id_parts(id);
|
||||
// A tracing traced again keeps the id of the first object of its chain, as its `PluginItem` does.
|
||||
let [high, low] = id_parts(super::tracing::origin(h, doc.uid, id));
|
||||
let [tag_high, tag_low] = id_parts(NodeId(tag));
|
||||
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
|
||||
}
|
||||
@@ -119,7 +122,7 @@ fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
|
||||
/// `PageItem.tags`.
|
||||
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
let [high, low] = id_parts(super::tracing::origin(h, item.doc.uid, item.id));
|
||||
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
|
||||
}
|
||||
|
||||
|
||||
@@ -1539,7 +1539,8 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does.
|
||||
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does, and
|
||||
/// so does an image the deletion would leave first in an ordinary group named as a tracing.
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = frames_scope(h, a)?;
|
||||
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -1563,7 +1564,7 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
// A clip group named as a tracing, released with an image left first, would become one.
|
||||
// A group named as a tracing, cleared or released with an image left first, would become one.
|
||||
if tracing {
|
||||
return Err(HostError::Error(super::NOT_A_TRACING.into()));
|
||||
}
|
||||
|
||||
@@ -2835,7 +2835,12 @@ impl Session {
|
||||
changed_names.push(st.title());
|
||||
continue;
|
||||
};
|
||||
let changed = !st.same_content(&b.doc);
|
||||
// The perspective grid's view state changes without an undo step, as it does outside a
|
||||
// run, when no command in the run recorded an undo step of its own on the working copy.
|
||||
// The working copy starts with no undo steps (`World::working`), so any step it holds now
|
||||
// was recorded in the run.
|
||||
let recorded = !st.history.undo.is_empty();
|
||||
let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc));
|
||||
st.history = std::mem::take(&mut b.history);
|
||||
st.recovery.clone_from(&b.recovery);
|
||||
if changed {
|
||||
|
||||
@@ -1004,9 +1004,10 @@ fn take_changed_paints(
|
||||
}
|
||||
|
||||
/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a
|
||||
/// revert), so it runs inside that preview rather than as a step of its own.
|
||||
/// revert), so it runs inside that preview rather than as a step of its own. Place adds art, so
|
||||
/// it runs on the document without the preview, as other edits do.
|
||||
fn reads_preview(id: &str) -> bool {
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode")
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode" && id != "file.place")
|
||||
}
|
||||
|
||||
/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts
|
||||
|
||||
@@ -188,6 +188,7 @@ mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_perspective;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_resources;
|
||||
mod script_dom_tracing;
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::collections::BTreeSet;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind};
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
use vectorcraft_geom::{Affine, ParamCurve, Point};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -1582,3 +1582,174 @@ fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_un
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
|
||||
/// The segment of path `id` as drawn that runs from a cut of corner `a` of its uncut outline to
|
||||
/// a cut of corner `b` (the same corner twice: that corner's curve).
|
||||
fn segment_between(s: &Session, id: NodeId, a: usize, b: usize) -> usize {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
let from = &lc.sources()[0];
|
||||
(0..from.len()).find(|&i| from[i] == a && from[(i + 1) % from.len()] == b).unwrap_or_else(|| panic!("no segment {a} -> {b} in {from:?}"))
|
||||
}
|
||||
|
||||
/// The anchors of path `id` as drawn that come from `corners` of its uncut outline.
|
||||
fn corner_anchors(s: &Session, id: NodeId, corners: &[usize]) -> BTreeSet<AnchorRef> {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&corners.iter().copied().collect())
|
||||
}
|
||||
|
||||
/// Adding an anchor point on a side of a rounded rectangle puts it on that side and keeps every
|
||||
/// corner live at its radius, in one undo step, with the direct-selected anchors still on their
|
||||
/// corner. Delete Anchor Point on it leaves the rectangle's outline with its corners still live.
|
||||
#[test]
|
||||
fn adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = node_path(&s, id).0;
|
||||
let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[2]).into_iter().map(|(si, ai)| [si, ai]).collect();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
let seg = segment_between(&s, id, 0, 1);
|
||||
let want = before.subpaths[0].segment(seg).eval(0.3);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.3})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap();
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert!(matches!(live, Some(LiveShape::Path { .. })), "{live:?}");
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(path.anchor_count(), 9);
|
||||
assert!(path.subpaths[0].anchors[ai].p.distance(want) < 1e-9, "{:?} vs {want:?}", path.subpaths[0].anchors[ai].p);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// The new anchor is the outline's anchor 1, so the corner that was 2 is 3 now.
|
||||
assert_eq!(selected_anchors(&s, id), Some(corner_anchors(&s, id, &[3])));
|
||||
|
||||
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap();
|
||||
assert_eq!(r["removedObject"], false);
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = node_path(&s, id).0;
|
||||
assert_eq!(after.anchor_count(), 8);
|
||||
for (_, _, a) in before.anchors() {
|
||||
assert!(after.anchors().any(|(_, _, b)| b.p.distance(a.p) < 1e-9), "{:?} is still drawn", a.p);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// Selected segments of a rounded rectangle stay selected when an anchor point is added on a
|
||||
/// side: a selected side that is split gives both its halves and the new anchor, and the other
|
||||
/// selected segments stay on the same sides and curves.
|
||||
#[test]
|
||||
fn adding_an_anchor_keeps_the_selected_segments_on_their_sides() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3));
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve], [0, bottom]], "mode": "set"})).unwrap();
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": top, "t": 0.5})).unwrap();
|
||||
let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap();
|
||||
// The new anchor is the outline's anchor 1, so corners 1, 2 and 3 are 2, 3 and 4 now.
|
||||
let want: BTreeSet<_> =
|
||||
[segment_between(&s, id, 0, 1), segment_between(&s, id, 1, 2), segment_between(&s, id, 3, 3), segment_between(&s, id, 3, 4)]
|
||||
.map(|g| (0, g))
|
||||
.into();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.segments.get(&id), Some(&want));
|
||||
assert!(st.selection.anchors.get(&id).is_some_and(|a| a.contains(&(0, ai))), "{:?}", st.selection.anchors);
|
||||
}
|
||||
|
||||
/// The anchors selected as the ends of selected segments stay just those ends when an anchor
|
||||
/// point is added on another side: the far anchors of the corners at a selected side's ends are
|
||||
/// not selected, so an arrow-key nudge does not move them.
|
||||
#[test]
|
||||
fn adding_an_anchor_selects_only_the_ends_of_the_selected_segments() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3));
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve]], "mode": "set"})).unwrap();
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": bottom, "t": 0.5})).unwrap();
|
||||
let n = node_path(&s, id).0.subpaths[0].anchors.len();
|
||||
// The new anchor is the outline's anchor 3, after the corners at the selected segments' ends.
|
||||
let (top, curve) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2));
|
||||
let want: BTreeSet<AnchorRef> = [top, (top + 1) % n, curve, (curve + 1) % n].map(|a| (0, a)).into();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.anchors.get(&id), Some(&want));
|
||||
assert_eq!(st.selection.segments.get(&id), Some(&[(0, top), (0, curve)].into()));
|
||||
}
|
||||
|
||||
/// An anchor point added on a corner's curve turns the corners into plain anchor points, as
|
||||
/// before, and the status bar says so.
|
||||
#[test]
|
||||
fn adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let seg = segment_between(&s, id, 1, 1);
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap();
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("Live Corners")), "{r}");
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!((path.anchor_count(), live), (9, None));
|
||||
}
|
||||
|
||||
/// Delete Anchor Point on either anchor of a cut corner removes that corner from the outline, and
|
||||
/// the other corners stay live at their radii.
|
||||
#[test]
|
||||
fn deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live() {
|
||||
for end in 0..2 {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (_, ai) = corner_anchors(&s, id, &[1]).into_iter().nth(end).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_eq!(lc.base.anchor_count(), 3, "end {end}");
|
||||
assert!(lc.corners.iter().all(|c| c.at.distance(Point::new(110.0, 10.0)) > 1.0), "the top-right corner went");
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 3]), "end {end}");
|
||||
assert_eq!(node_path(&s, id).0.anchor_count(), 6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove Anchor Points on a cut corner of a rounded rectangle keeps the other corners live and
|
||||
/// selects an anchor of the next corner along, so the next Remove Anchor Points goes on there.
|
||||
#[test]
|
||||
fn remove_anchor_points_on_a_cut_corner_selects_the_next_corner() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[1]).into_iter().map(|(si, ai)| [si, ai]).collect();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
s.execute("path.removeAnchors", &json!({})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 3]));
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
// The bottom-right corner, which followed the removed one, is the outline's anchor 1 now.
|
||||
assert!(lc.base.subpaths[0].anchors[1].p.distance(Point::new(110.0, 70.0)) < 1e-9);
|
||||
assert_eq!(selected_anchors(&s, id), lc.drawn_anchor((0, 1)).map(|a| BTreeSet::from([a])));
|
||||
}
|
||||
|
||||
/// Remove Anchor Points with one anchor of every cut corner selected removes every corner, so the
|
||||
/// path goes, as a plain path with all its anchors removed does.
|
||||
#[test]
|
||||
fn removing_an_anchor_of_every_corner_removes_the_path() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
let picked: Vec<[usize; 2]> = (0..4).filter_map(|k| lc.drawn_anchor((0, k))).map(|(si, ai)| [si, ai]).collect();
|
||||
assert_eq!(picked.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1);
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
/// A relative radius keeps the length it is drawn at when an added anchor shortens the side its
|
||||
/// corner's largest radius depends on.
|
||||
#[test]
|
||||
fn an_added_anchor_keeps_a_relative_radius_at_its_length() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"relativeRadii": true}));
|
||||
let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius();
|
||||
run(&mut s, json!({"radius": 0.25 * max}));
|
||||
let drawn = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(0);
|
||||
let seg = segment_between(&s, id, 0, 1);
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(matches!(n.live_shape(), Some(LiveShape::Path { radii_relative: true, .. })), "{:?}", n.live_shape());
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
assert!((lc.drawn_radius(0) - drawn).abs() < 1e-9, "{} vs {drawn}", lc.drawn_radius(0));
|
||||
}
|
||||
@@ -152,6 +152,31 @@ fn print_as_bitmap_prints_all_of_a_long_artboard() {
|
||||
assert!(b.x0 <= 0.0 && b.x1 >= 9000.0, "the image covers the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// A raster effects resolution that isn't a number prints at the resolution the document reads it
|
||||
/// as (72 ppi), not as an empty page.
|
||||
#[test]
|
||||
fn print_as_bitmap_of_a_resolution_that_is_not_a_number_prints_at_72_ppi() {
|
||||
let (s, _) = session();
|
||||
let saved = s.prefs.flattener_presets.clone();
|
||||
let set = settings(json!({"advanced": {"printAsBitmap": true}}));
|
||||
let widths = |ppi: f64| {
|
||||
let mut d = doc(&s).clone();
|
||||
d.raster_effects_ppi = ppi;
|
||||
let bitmap = crate::cmd::printadvanced::prepare("file.print", &d, &set, &saved, false).unwrap().unwrap();
|
||||
let mut widths = vec![];
|
||||
bitmap.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
widths.push(im.width);
|
||||
}
|
||||
});
|
||||
widths
|
||||
};
|
||||
let at_72 = widths(72.0);
|
||||
assert_eq!(at_72.len(), 1, "{at_72:?}");
|
||||
assert_eq!(widths(f64::NAN), at_72);
|
||||
assert!(widths(144.0)[0] > at_72[0], "the resolution decides the image's size");
|
||||
}
|
||||
|
||||
/// The images `file.print` prints with `settings`: their pixel sizes and their places on the page
|
||||
/// in the print-ready PDF (read back), their pixel sizes in the PostScript file (its image
|
||||
/// dictionaries, each size once), and the warnings of both.
|
||||
|
||||
@@ -338,6 +338,45 @@ fn steps_discard_the_chosen_artboard_after_revert() {
|
||||
assert_ne!(now[2], was[2], "playback uses the run's original index after revert");
|
||||
}
|
||||
|
||||
/// An artboard the script removes or inserts moves the active artboard's index; its played steps act
|
||||
/// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does,
|
||||
/// also after an undo puts the artboards back. The artboard that was active stays active, also when
|
||||
/// none was chosen before the run.
|
||||
#[test]
|
||||
fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() {
|
||||
let setup = |active: Option<usize>| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
if let Some(i) = active {
|
||||
make_active(&mut s, i);
|
||||
}
|
||||
(s, id)
|
||||
};
|
||||
let actions = set(&[("Align", vec![json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}})])]);
|
||||
let cases = [
|
||||
(Some(1), "A.remove(0);"),
|
||||
(Some(1), "A[0].remove();"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
(Some(1), "A.insert([2000, 500, 2100, 400], 2);"),
|
||||
(Some(1), "A.remove(0); app.undo();"),
|
||||
(None, "A.insert([2000, 500, 2100, 400], 0);"),
|
||||
];
|
||||
for (active, edit) in cases {
|
||||
let (mut s, id) = setup(active);
|
||||
let was = s.active().unwrap().doc.artboards[active.unwrap_or(0)].rect;
|
||||
let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');");
|
||||
let out = log_with(&mut s, &source, &actions);
|
||||
let index = out[0].as_u64().unwrap() as usize;
|
||||
let board = s.active().unwrap().doc.artboards[index].rect;
|
||||
let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
|
||||
assert_eq!(left, board.x0, "{active:?} {edit}");
|
||||
assert_eq!(board, was, "the artboard active before the edit stays active: {active:?} {edit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
|
||||
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
|
||||
#[test]
|
||||
|
||||
@@ -2804,6 +2804,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
let steps = undo_steps(&s);
|
||||
// The lengths are read inside the run, after the refusal is caught, so a delete that ran before
|
||||
// the refusal shows here even though a failed run would put the tree back.
|
||||
let lengths = "vc.log([d.pageItems.length, d.layers[0].pageItems.length, d.groupItems.length, d.groupItems.length && d.groupItems[0].pageItems.length, \
|
||||
d.compoundPathItems.length]);";
|
||||
let counts = log(&mut s, &format!("var d = app.activeDocument; {lengths}"));
|
||||
for scope in [
|
||||
"app.activeDocument.layers[0].pageItems",
|
||||
"app.activeDocument.layers[0].groupItems",
|
||||
@@ -2815,9 +2820,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
|
||||
"app.activeDocument.groupItems.getByName('locked').pathItems",
|
||||
"app.activeDocument.compoundPathItems[0].pathItems",
|
||||
] {
|
||||
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
|
||||
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var d = app.activeDocument; try {{ {scope}.removeAll(); vc.log('ok'); }} catch (e) {{ vc.log(e.message); }} {lengths}"),
|
||||
);
|
||||
let err = out[0].as_str().unwrap_or_default();
|
||||
assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}");
|
||||
assert_eq!(out[1..], counts[..], "{scope}: nothing is deleted before the refusal");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}");
|
||||
assert_eq!(undo_steps(&s), steps, "{scope}");
|
||||
let doc = &s.active().unwrap().doc;
|
||||
@@ -5190,6 +5199,38 @@ fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() {
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// Without a chosen artboard, an artboard inserted before the default active one moves it to the
|
||||
/// next index, in an open document and in one the run makes, and the report gives that index.
|
||||
#[test]
|
||||
fn inserting_before_the_default_active_artboard_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let first = s.active().unwrap().doc.artboards[0].id;
|
||||
let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}]));
|
||||
assert_eq!(s.active().unwrap().active_artboard, Some(first));
|
||||
let r = run(&mut s, "var d = app.documents.add(); var A = d.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());")
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
let list = r["activeArtboards"].as_array().cloned().unwrap_or_default();
|
||||
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
|
||||
}
|
||||
|
||||
/// After the chosen artboard is removed, the artboard active in its place stays active when one is
|
||||
/// inserted before it.
|
||||
#[test]
|
||||
fn inserting_before_the_fallback_after_the_chosen_artboard_is_removed_keeps_it() {
|
||||
let (mut s, _, _) = doc();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var A = app.activeDocument.artboards; A.add([800, 300, 900, 100]); A.setActiveArtboardIndex(1); A.remove(1);\
|
||||
var was = A[A.getActiveArtboardIndex()].name; A.insert([1000, 300, 1100, 100], 0);\
|
||||
vc.log(A[A.getActiveArtboardIndex()].name == was);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([true]), "{r}");
|
||||
}
|
||||
|
||||
/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard.
|
||||
#[test]
|
||||
fn artboards_insert_returns_nothing() {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! The script object model's perspective grid members and `app.getPresetSettings`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn grid(s: &mut Session) -> Value {
|
||||
s.execute("perspective.grid.get", &json!({})).unwrap()["grid"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_and_hide_change_the_view_without_an_undo_step() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
let out =
|
||||
log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.showPerspectiveGrid()); vc.log(d.showPerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(false), json!(true), json!(true)]);
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.hidePerspectiveGrid());");
|
||||
assert_eq!(out, vec![json!(true), json!(false)]);
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_migrates_legacy_attachments_without_an_undo_step() {
|
||||
use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane};
|
||||
|
||||
for (call, edit) in [("showPerspectiveGrid", false), ("hidePerspectiveGrid", false), ("showPerspectiveGrid", true), ("hidePerspectiveGrid", true)]
|
||||
{
|
||||
let mut s = doc();
|
||||
let made = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let id = NodeId(made["id"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let mut g = PerspectiveGrid::current(d);
|
||||
g.visible = call == "hidePerspectiveGrid";
|
||||
g.attached.insert(id.0.to_string(), Plane::Right);
|
||||
d.unknown.insert(persp::DOC_KEY.into(), serde_json::to_value(&g).unwrap());
|
||||
let before = undo_steps(&s);
|
||||
let draw = if edit { "vc.run('shape.rectangle', {x: 50, y: 50, width: 10, height: 10});" } else { "" };
|
||||
run(&mut s, &format!("app.activeDocument.{call}(); {draw}")).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + usize::from(edit));
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(PerspectiveGrid::current(d).attachment_of(d, id), Some((Plane::Right, 0.0)));
|
||||
assert!(d.node(id).unwrap().extras().perspective.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
run(&mut s, "vc.run('perspective.grid.show', {visible: true}); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
run(&mut s, "app.activeDocument.hidePerspectiveGrid(); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});").unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(grid(&mut s)["visible"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_view_run_after_an_edit_adds_no_undo_step() {
|
||||
let mut s = doc();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let drawn = s.active().unwrap().doc.node_count();
|
||||
run(&mut s, "app.activeDocument.showPerspectiveGrid(); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap();
|
||||
assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.node_count(), drawn - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() {
|
||||
let mut s = doc();
|
||||
let before = undo_steps(&s);
|
||||
s.execute("perspective.grid.set", &json!({"locked": true})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut s = doc();
|
||||
let source = "vc.run('perspective.grid.set', {locked: true}); app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE);";
|
||||
run(&mut s, source).unwrap();
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!((grid(&mut s)["locked"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground")));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!grid(&mut s).get("locked").and_then(Value::as_bool).unwrap_or(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_active_plane_round_trips_and_a_failed_run_puts_it_back() {
|
||||
let mut s = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; vc.log(d.getPerspectiveActivePlane());\
|
||||
vc.log(d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE)); vc.log(d.getPerspectiveActivePlane());\
|
||||
d.setActivePlane(PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
let expected = ["PerspectiveGridPlaneType.GRIDLEFTPLANETYPE", "PerspectiveGridPlaneType.GRIDFLOORPLANETYPE"];
|
||||
assert_eq!(out[..3], [json!(expected[0]), json!(true), json!(expected[1])]);
|
||||
assert_eq!(out[3], json!("PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE"));
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
failure(&mut s, "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE); d.showPerspectiveGrid(); throw 1;");
|
||||
assert_eq!(grid(&mut s)["plane"], "none");
|
||||
assert_eq!(grid(&mut s)["visible"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_plane_or_a_right_plane_on_a_one_point_grid_throws() {
|
||||
let mut s = doc();
|
||||
for bad in ["'left'", "0", "PerspectiveGridType.OnePointPerspectiveGridType", "undefined"] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({bad});"));
|
||||
assert!(e.contains("PerspectiveGridPlaneType"), "{bad}: {e}");
|
||||
}
|
||||
s.execute("perspective.grid.preset", &json!({"kind": 1})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE);");
|
||||
assert!(e.contains("one-point grid"), "{e}");
|
||||
assert_eq!(grid(&mut s)["plane"], "left");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE); vc.log(d.getPerspectiveActivePlane());",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PerspectiveGridPlaneType.GRIDFLOORPLANETYPE")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_perspective_preset_checks_the_type_and_the_name() {
|
||||
let mut s = doc();
|
||||
let one = s.execute("perspective.presets.list", &json!({})).unwrap()["presets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|p| p["kind"] == 1)
|
||||
.map(|p| p["name"].as_str().unwrap().to_string())
|
||||
.unwrap();
|
||||
let before = undo_steps(&s);
|
||||
for (call, message) in [
|
||||
(format!("PerspectiveGridType.TwoPointPerspectiveGridType, '{one}'"), "not a grid of that type"),
|
||||
(format!("PerspectiveGridType.InvalidPerspectiveGridType, '{one}'"), "has no presets"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 'No Such Preset'".to_string(), "no perspective grid preset called"),
|
||||
(format!("'one', '{one}'"), "PerspectiveGridType value"),
|
||||
("PerspectiveGridType.OnePointPerspectiveGridType, 7".to_string(), "presetName must be a string"),
|
||||
(format!("PerspectiveGridType.OnePointPerspectiveGridType, '{}'", "x".repeat(5000)), "too long"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(grid(&mut s)["kind"], 2);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("vc.log(app.activeDocument.selectPerspectivePreset(PerspectiveGridType.OnePointPerspectiveGridType, '{}'));", one.to_uppercase()),
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
let g = grid(&mut s);
|
||||
assert_eq!((g["kind"].clone(), g["visible"].clone()), (json!(1), json!(true)));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_numbers_throw_with_nothing_changed() {
|
||||
let mut s = doc();
|
||||
s.execute("perspective.presets.save", &json!({"name": "Mine"})).unwrap();
|
||||
let before = (undo_steps(&s), grid(&mut s));
|
||||
for name in ["../Mine", "..\\\\Mine", "/Mine", "C:\\\\Mine", "Mine/..", "Mi\\u0000ne", "~/Mine"] {
|
||||
for call in [
|
||||
format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, '{name}');"),
|
||||
format!("app.getPresetSettings('{name}');"),
|
||||
] {
|
||||
let e = failure(&mut s, &call);
|
||||
assert!(e.contains("no perspective grid preset called") || e.contains("no startup preset called"), "{call}: {e}");
|
||||
}
|
||||
}
|
||||
// The script host refuses a number that is not finite before the member runs.
|
||||
for value in ["NaN", "Infinity", "-1e308", "1e308", "2"] {
|
||||
let refused = |e: &str, message: &str| e.contains(message) || e.contains("is not a finite number");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({value}, 'Mine');"));
|
||||
assert!(refused(&e, "PerspectiveGridType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({value});"));
|
||||
assert!(refused(&e, "PerspectiveGridPlaneType value"), "{value}: {e}");
|
||||
let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, {value});"));
|
||||
assert!(refused(&e, "presetName must be a string"), "{value}: {e}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), grid(&mut s)), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_document_throws_on_every_grid_member() {
|
||||
let mut s = doc();
|
||||
run(&mut s, "#targetengine keep\nvar held = app.activeDocument;").unwrap();
|
||||
let e = failure(&mut s, "#targetengine keep\nheld.showPerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "var d = app.activeDocument; vc.run('file.close', {}); d.hidePerspectiveGrid();");
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
let e = failure(&mut s, "Document.prototype.getPerspectiveActivePlane.call({});");
|
||||
assert!(e.contains("not a Document"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_gives_a_copy_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Basic CMYK'); vc.log(p.typename); vc.log(p.colorMode); vc.log(p.width); vc.log(p.height);\
|
||||
vc.log(p.numArtboards); p.width = 100; vc.log(app.getPresetSettings('Basic CMYK').width);\
|
||||
var d = app.documents.addDocument('Basic CMYK', p); vc.log(d.width); vc.log(d.documentColorSpace);\
|
||||
vc.log(app.getPresetSettings(DocumentPresetType.BasicRGB).colorMode);",
|
||||
);
|
||||
let expected = [json!("DocumentPreset"), json!("DocumentColorSpace.CMYK"), json!(612), json!(792), json!(1), json!(612)];
|
||||
assert_eq!(out[..6], expected);
|
||||
assert_eq!(out[6..], [json!(100), json!("DocumentColorSpace.CMYK"), json!("DocumentColorSpace.RGB")]);
|
||||
for (call, message) in [("'No Such Preset'", "no startup preset called"), ("3", "startup preset's name"), ("undefined", "startup preset's name")]
|
||||
{
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings({call});"));
|
||||
assert!(e.contains(message), "{call}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, &format!("app.getPresetSettings('{}');", "x".repeat(5000)));
|
||||
assert!(e.contains("too long"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_of_a_profile_gives_what_add_document_starts_from() {
|
||||
let mut s = Session::new();
|
||||
for preset in ["Video", "Web", "Mobile", "Print", "DocumentPresetType.Video"] {
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.getPresetSettings('{preset}'); var d = app.documents.addDocument('{preset}');\
|
||||
vc.log([p.width, p.height, p.units, p.colorMode]); vc.log([d.width, d.height, d.rulerUnits, d.documentColorSpace]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], out[1], "{preset}");
|
||||
}
|
||||
let out = log(&mut s, "var p = app.getPresetSettings('Video'); vc.log([p.width, p.height]);");
|
||||
assert_ne!(out[0], json!([612, 792]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_preset_settings_given_back_to_add_document_makes_the_same_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "feet"})).unwrap();
|
||||
let layout = json!({"layout": "gridByColumn", "rows": 3, "spacing": 30});
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": 5, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards); vc.log(p.units === undefined);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log(boards(a)); vc.log(boards(b)); vc.log(a.rulerUnits === b.rulerUnits);",
|
||||
);
|
||||
// A saved preset with the built-in preset's name changes neither the settings nor the document.
|
||||
assert_eq!(out[..2], [json!(1), json!(true)]);
|
||||
assert_eq!(out[2], out[3]);
|
||||
assert_eq!(out[2].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(out[4], json!(true));
|
||||
for (artboards, layout) in [
|
||||
(6, json!({"layout": "gridByColumn", "columns": 4})),
|
||||
(150, json!({"layout": "gridByRow", "columns": 12})),
|
||||
(7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": true})),
|
||||
] {
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": artboards, "artboardLayout": layout})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.numArtboards);\
|
||||
function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\
|
||||
vc.log(boards(app.documents.addDocument('Print'))); vc.log(boards(app.documents.addDocument('Print', p)));",
|
||||
);
|
||||
assert_eq!(out[0], json!(1), "{artboards} {layout}");
|
||||
assert_eq!(out[1].as_array().map(Vec::len), Some(1), "{layout}");
|
||||
assert_eq!(out[1], out[2], "{artboards} {layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_preview_preset_settings_can_be_given_back_to_add_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "previewMode": "pixel"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.getPresetSettings('Print'); vc.log(p.previewMode);\
|
||||
var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\
|
||||
vc.log([a.width, a.height, a.documentColorSpace]); vc.log([b.width, b.height, b.documentColorSpace]);",
|
||||
);
|
||||
// The saved preset's Pixel Preview does not replace the built-in preset's preview mode.
|
||||
assert_eq!(out[0], json!("DocumentPreviewMode.DefaultPreview"));
|
||||
assert_eq!(out[1], out[2]);
|
||||
assert_eq!(out[1], json!([612, 792, "DocumentColorSpace.CMYK"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_presets_list_names_presets_add_document_takes() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var l = app.startupPresetsList; vc.log(l); l.push('Mine'); l[0] = 'x'; vc.log(app.startupPresetsList.length === l.length - 1);\
|
||||
vc.log(app.startupPresetsList[0] !== 'x');\
|
||||
for (var i = 0; i < l.length - 1; i++) { var n = app.startupPresetsList[i]; var p = app.getPresetSettings(n);\
|
||||
var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }",
|
||||
);
|
||||
let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
// VectorCraft's own order puts Print first.
|
||||
assert_eq!(names.first(), Some(&"Print"));
|
||||
// Every New Document profile and both Basic presets, each once.
|
||||
let mut sorted = names.clone();
|
||||
sorted.sort_unstable();
|
||||
let mut listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect();
|
||||
listed.sort_unstable();
|
||||
assert_eq!(sorted, listed);
|
||||
assert_eq!(out[1..3], [json!(true), json!(true)]);
|
||||
assert_eq!(out.len(), 3 + names.len());
|
||||
for (name, made) in names.iter().zip(&out[3..]) {
|
||||
assert_eq!(made, &json!([name, true]), "{name}");
|
||||
}
|
||||
assert_eq!(s.documents().len(), names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_not_built_yet_say_so() {
|
||||
let mut s = doc();
|
||||
for (owner, member) in [
|
||||
("app", "saveWorkspace"),
|
||||
("app", "switchWorkspace"),
|
||||
("app", "deleteWorkspace"),
|
||||
("app", "resetWorkspace"),
|
||||
("app", "loadColorSettings"),
|
||||
("app", "showPresets"),
|
||||
("app.activeDocument", "exportPerspectiveGridPreset"),
|
||||
("app.activeDocument", "importPerspectiveGridPreset"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("{owner}.{member}('x');"));
|
||||
assert!(e.contains(&format!("{member} is not available yet")), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1659,6 +1659,102 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrace_keeps_the_tracing_note_and_tags() {
|
||||
let base = folder("retrace-attributes");
|
||||
let (mut s, _) = session(&base, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var tags = p.tags, t = tags.add(); t.name = 'job'; t.value = '42';\
|
||||
p.tracing.tracingOptions.threshold = 90; vc.log(p.note); vc.log(p.tags.length); vc.log(p.tags[0].name + '=' + p.tags[0].value);\
|
||||
vc.log(tags.length); vc.log(t.value); vc.log(t === p.tags[0]); vc.log(tags === p.tags);",
|
||||
);
|
||||
assert_eq!(out, [json!("keep me"), json!(1), json!("job=42"), json!(1), json!("42"), json!(true), json!(true)]);
|
||||
// Image Trace › Make on the tracing keeps them too.
|
||||
let id = traces(&s)[0];
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let attrs = d.node(id).and_then(|n| n.extras().attrs.as_deref().cloned()).unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({"id": id.0})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let group = d.node(id).unwrap();
|
||||
assert!(matches!(group.kind, NodeKind::Group { .. }));
|
||||
let attrs = group.extras().attrs.as_deref().cloned().unwrap_or_default();
|
||||
assert_eq!(attrs.note, "keep me");
|
||||
let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect();
|
||||
assert_eq!(tags, [("job", "42")]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Tracing again moves the tracing's attributes to the new tracing: it copies them once, when it
|
||||
/// reads the tracing out of the document, and not again for the new object.
|
||||
#[test]
|
||||
fn retrace_copies_the_tracing_attributes_once() {
|
||||
let base = folder("retrace-attribute-copies");
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var t = p.tags.add(); t.name = 'job'; t.value = '42';",
|
||||
);
|
||||
let id = traces(&s)[0];
|
||||
let before = vectorcraft_doc::attribute_copies();
|
||||
let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap();
|
||||
assert_eq!(vectorcraft_doc::attribute_copies() - before, 1, "copies of the attributes");
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let note = s.active().unwrap().doc.node(id).and_then(|n| n.extras().attrs.as_deref().map(|a| a.note.clone()));
|
||||
assert_eq!(note.as_deref(), Some("keep me"));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an
|
||||
/// ordinary group named as a tracing, before the document changes.
|
||||
#[test]
|
||||
fn path_and_type_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||||
let setup = |bottom: &str| {
|
||||
format!(
|
||||
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
|
||||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);"
|
||||
)
|
||||
};
|
||||
for (name, bottom, list) in [
|
||||
("remove-all-trace-name-paths", "d.pathItems.rectangle(10, 10, 20, 20)", "pathItems"),
|
||||
// `edit.clear` also deletes the compound path its members leave empty.
|
||||
(
|
||||
"remove-all-trace-name-compound",
|
||||
"(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\
|
||||
vc.run('object.compoundPath.make'); return d.pageItems[0]; })()",
|
||||
"pathItems",
|
||||
),
|
||||
("remove-all-trace-name-type", "d.textFrames.pointText([10, 10])", "textFrames"),
|
||||
] {
|
||||
let base = folder(name);
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(&mut s, &base, &setup(bottom));
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\
|
||||
vc.log(m); vc.log(d.pageItems[0].typename);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}");
|
||||
assert!(traces(&s).is_empty(), "{list}");
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}");
|
||||
assert_eq!(undo_steps(&s), steps, "{list}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_the_same_preset_in_bracket_form_does_not_trace_again() {
|
||||
let base = folder("retrace-bracket-preset");
|
||||
|
||||
@@ -904,10 +904,13 @@ fn dxf_xs(dxf: &str) -> Vec<f64> {
|
||||
xs
|
||||
}
|
||||
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and
|
||||
/// DWG, the help page's default format, throws without writing a file.
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DWG, the help page's default format, or a DXF
|
||||
/// with the `ExportOptionsAutoCAD` options; a DWG of a release before 2000 throws without writing a
|
||||
/// file. craft-dwg writes DWG everywhere but wasm32 and FreeBSD on aarch64.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
fn an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let base = folder("autocad");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
@@ -919,7 +922,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\
|
||||
try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o);\n\
|
||||
o.version = AutoCADCompatibility.AutoCADRelease14;\n\
|
||||
try {{ d.exportFile(new File(dir + '/old'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\
|
||||
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
|
||||
d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\
|
||||
@@ -930,8 +935,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true]));
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]);
|
||||
assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing");
|
||||
let w = std::fs::read(dir.join("w.dwg")).unwrap();
|
||||
assert_eq!(&w[..6], b"AC1024", "the default AutoCADRelease24 is the 2010 format");
|
||||
assert!(!dir.join("w.dxf").exists());
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG needs AutoCADRelease15")), "{}", out[1]);
|
||||
assert!(!dir.join("old.dwg").exists() && !dir.join("old").exists(), "a refused DWG writes nothing");
|
||||
let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap();
|
||||
let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap();
|
||||
assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it");
|
||||
@@ -1421,10 +1429,11 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
"from 0 to 100",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"),
|
||||
(
|
||||
format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"),
|
||||
"DWG is not available",
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; o.version = AutoCADCompatibility.AutoCADRelease13; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"
|
||||
),
|
||||
"DWG needs AutoCADRelease15",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
@@ -1874,7 +1883,7 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
|
||||
/// to the Script Console.
|
||||
#[test]
|
||||
fn a_saves_warnings_go_to_the_console() {
|
||||
let base = folder("warnings");
|
||||
let base = folder("pdf-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! must load as an error or as a document that then renders and exports, without a panic; nor may
|
||||
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
|
||||
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
|
||||
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! opcodes with random contents) opened or placed, nor binary CGM files (damaged files, elements
|
||||
//! with random contents) opened or placed, nor EPS and PostScript files
|
||||
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
|
||||
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
|
||||
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
|
||||
@@ -4158,6 +4159,125 @@ proptest! {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Binary CGM files: opened and placed ----------
|
||||
|
||||
// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature.
|
||||
|
||||
/// One CGM element, in the long form past 30 bytes, padded to an even length.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes());
|
||||
} else {
|
||||
b.extend(((class << 12) | (id << 5) | 31).to_be_bytes());
|
||||
b.extend((data.len() as u16).to_be_bytes());
|
||||
}
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A metafile of one picture holding `body`.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut b = cgm_el(0, 1, b"\x01x");
|
||||
b.extend(cgm_el(1, 1, &be16(&[3])));
|
||||
b.extend(cgm_el(1, 13, b"\x09Helvetica"));
|
||||
b.extend(cgm_el(0, 3, b"\x01p"));
|
||||
b.extend(cgm_el(2, 6, &be16(&[0, 0, 1000, 500])));
|
||||
b.extend(cgm_el(0, 4, &[]));
|
||||
for (class, id, data) in body {
|
||||
b.extend(cgm_el(*class, *id, data));
|
||||
}
|
||||
b.extend(cgm_el(0, 5, &[]));
|
||||
b.extend(cgm_el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_sample() -> Vec<u8> {
|
||||
cgm_of(&[
|
||||
(5, 34, vec![8, 10, 20, 30, 40, 50, 60]),
|
||||
(5, 3, be16(&[3])),
|
||||
(5, 2, be16(&[2])),
|
||||
(4, 1, be16(&[0, 0, 100, 100, 200, 0])),
|
||||
(4, 2, be16(&[0, 10, 50, 10, 60, 10, 90, 10])),
|
||||
(5, 22, be16(&[1])),
|
||||
(5, 30, be16(&[1])),
|
||||
(4, 7, be16(&[300, 0, 400, 0, 350, 80])),
|
||||
(4, 8, be16(&[0, 200, 1, 100, 200, 1, 100, 300, 3])),
|
||||
(4, 11, be16(&[500, 0, 600, 100])),
|
||||
(4, 12, be16(&[700, 100, 50])),
|
||||
(4, 14, be16(&[800, 0, 850, 50, 900, 0, 0])),
|
||||
(4, 16, be16(&[100, 400, 1, 0, 0, 1, 50, 1])),
|
||||
(4, 19, be16(&[300, 400, 350, 400, 300, 420, 1, 0, 0, 1, 0])),
|
||||
(4, 26, be16(&[2, 0, 0, 10, 20, 30, 20, 40, 0])),
|
||||
(0, 8, vec![]),
|
||||
(4, 1, be16(&[500, 300, 600, 300])),
|
||||
(4, 15, be16(&[600, 350, 0, -1, 0, 1, 50])),
|
||||
(3, 10, vec![]),
|
||||
(0, 9, vec![]),
|
||||
(5, 6, be16(&[3])),
|
||||
(4, 3, be16(&[900, 400, 950, 450])),
|
||||
(3, 5, be16(&[0, 0, 500, 250])),
|
||||
(5, 15, be16(&[40])),
|
||||
(4, 4, [be16(&[100, 100, 0]), b"\x03abc".to_vec()].concat()),
|
||||
(4, 6, [be16(&[1]), b"\x02de".to_vec()].concat()),
|
||||
(4, 9, [be16(&[0, 0, 200, 100, 200, 0, 2, 2, 4, 1]), vec![0x12, 0, 0x34, 0]].concat()),
|
||||
])
|
||||
}
|
||||
|
||||
/// The sample the mutations start from opens with art, type and an image.
|
||||
#[cfg(feature = "cgm")]
|
||||
#[test]
|
||||
fn the_cgm_sample_opens() {
|
||||
let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap();
|
||||
assert_eq!(l.format.id, "cgm");
|
||||
let (mut paths, mut images, mut texts) = (0, 0, 0);
|
||||
l.doc.walk(|n| match n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { .. } => paths += 1,
|
||||
vectorcraft_doc::NodeKind::Image(_) => images += 1,
|
||||
vectorcraft_doc::NodeKind::Text(_) => texts += 1,
|
||||
_ => {}
|
||||
});
|
||||
assert!(paths > 10 && images == 1 && texts == 1, "{paths} paths, {images} images, {texts} texts, warnings {:?}", l.warnings);
|
||||
}
|
||||
|
||||
/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the
|
||||
/// low one.
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_ELEMENTS: [u16; 44] = [
|
||||
0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306,
|
||||
0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418,
|
||||
0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801,
|
||||
];
|
||||
|
||||
#[cfg(feature = "cgm")]
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
#[test]
|
||||
fn mutated_cgm_pictures_never_panic(cut in 0usize..4096, edits in prop::collection::vec((0usize..4096, any::<u8>()), 0..16)) {
|
||||
let mut bytes = cgm_sample();
|
||||
let n = bytes.len();
|
||||
for &(at, b) in &edits {
|
||||
bytes[at % n] = b;
|
||||
}
|
||||
bytes.truncate(cut);
|
||||
survive_metafile("mutated CGM", "x.cgm", &bytes)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_cgm_elements_never_panic(els in prop::collection::vec((prop::sample::select(CGM_ELEMENTS.to_vec()), arb_body()), 0..32)) {
|
||||
let body: Vec<(u16, u16, Vec<u8>)> = els.into_iter().map(|(e, d)| (e >> 8, e & 0xFF, d)).collect();
|
||||
survive_metafile("CGM elements", "x.cgm", &cgm_of(&body))?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- HP-GL plot files: opened and placed ----------
|
||||
|
||||
/// A plot file with every kind of instruction the reader plays, printer escapes around it.
|
||||
|
||||
@@ -58,10 +58,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. The perspective
|
||||
/// grid preset files of `Document`, and the workspace methods, `loadColorSettings` and
|
||||
/// `showPresets` of `Application`, throw "not available yet". Reading a preference changes nothing,
|
||||
/// and the matrix functions return new records. `app.copy` and `app.cut` fill VectorCraft's
|
||||
/// clipboard, which the desktop app offers to other apps after the run as Edit › Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "__vcPaletteEvent alert confirm length prompt prototype"),
|
||||
@@ -103,22 +104,22 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||||
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
|
||||
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
|
||||
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
|
||||
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
|
||||
View Views ZOrderMethod",
|
||||
PathPointSelection PathPoints PerspectiveGridPlaneType PerspectiveGridType PlacedItem PlacedItems PluginItem PointType \
|
||||
PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots \
|
||||
StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint \
|
||||
Symbols Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
|
||||
unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut deleteWorkspace \
|
||||
deleteWorkspace= documents doScript executeMenuCommand getIdentityMatrix getIsFileOpen getPresetSettings \
|
||||
getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix loadAction \
|
||||
loadAction= loadColorSettings loadColorSettings= open paste PPDFileList preferences printPresetsList printerList \
|
||||
redo redraw resetWorkspace resetWorkspace= saveWorkspace saveWorkspace= selection selection= selectTool \
|
||||
showColorPicker showPresets showPresets= startupPresetsList switchWorkspace switchWorkspace= textFonts toString \
|
||||
typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
|
||||
),
|
||||
("Preferences.", "prototype"),
|
||||
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
|
||||
@@ -140,10 +141,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
|
||||
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
|
||||
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
|
||||
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace \
|
||||
exportPerspectiveGridPreset exportPerspectiveGridPreset= fullName getPerspectiveActivePlane gradients gradients= \
|
||||
graphicStyles groupItems height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= \
|
||||
layers name pageItems paragraphStyles parent path pathItems patterns patterns= placedItems rasterItems \
|
||||
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selectPerspectivePreset selection selection= \
|
||||
setActivePlane showPerspectiveGrid spots stories swatchGroups swatches symbolItems symbols tags textFrames \
|
||||
toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -300,6 +304,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||||
("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"),
|
||||
("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"),
|
||||
("PointType.", "CORNER SMOOTH"),
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
|
||||
+14
-4
@@ -563,6 +563,7 @@ impl Interp {
|
||||
|
||||
pub(crate) fn sync_host_files(&mut self) -> JsResult<()> {
|
||||
let mut updates = Vec::new();
|
||||
let mut untracked = Vec::new();
|
||||
for id in self.host_file_objects.clone() {
|
||||
self.use_fuel()?;
|
||||
let Some(object) = self.heap.object(id) else { continue };
|
||||
@@ -570,13 +571,22 @@ impl Interp {
|
||||
let class = h.class;
|
||||
for (name, file, previous) in &h.files {
|
||||
let Some(file_id) = file.as_object() else { continue };
|
||||
if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous)
|
||||
&& let Some((get, set)) = self.file_accessors(class, name)
|
||||
{
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
match crate::file_classes::file_path(self, file_id)? {
|
||||
// An object that is no longer a File (its prototype changed) is not tracked
|
||||
// any more, and the host keeps the path it has.
|
||||
None => untracked.push((id, name.clone())),
|
||||
Some(path) if path != *previous => {
|
||||
if let Some((get, set)) = self.file_accessors(class, name) {
|
||||
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, name) in untracked {
|
||||
self.keep_host_file(id, name, Value::Undefined)?;
|
||||
}
|
||||
for (id, name, file, previous, get, set) in updates {
|
||||
self.use_fuel()?;
|
||||
// A property the host changed since the assignment no longer holds this File: it is
|
||||
|
||||
@@ -1682,3 +1682,12 @@ fn a_refused_path_change_is_thrown_once() {
|
||||
assert!(first.contains("refused"), "{first}");
|
||||
assert_eq!(*seen.borrow(), ["/a", "/good"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_whose_prototype_changes_is_no_longer_tracked() {
|
||||
let (mut r, seen) = file_property_realm();
|
||||
r.set_es2015(true);
|
||||
let source = "var f = new File('/a'); it.file = f; Reflect.setPrototypeOf(f, Object.prototype); it.touch(); it.touch(); it.file !== f && it.file instanceof File";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
|
||||
assert_eq!(*seen.borrow(), ["/a"]);
|
||||
}
|
||||
@@ -321,7 +321,8 @@ impl LiveBackend {
|
||||
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
|
||||
}
|
||||
|
||||
/// The folders the open window lets agents use, as the window opens them.
|
||||
/// The folders the open window lets agents use, read from the saved settings: the answer for a
|
||||
/// window that doesn't report the folders it enforces itself.
|
||||
fn window_folders(&self) -> Value {
|
||||
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
|
||||
}
|
||||
@@ -330,7 +331,12 @@ impl LiveBackend {
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
|
||||
// The window answers with the folders it enforces, which are none when a saved folder
|
||||
// can't be used; a window without the method gets the saved settings.
|
||||
Route::Window(w) if method == FOLDERS_METHOD => match w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params) {
|
||||
Err(e) if e.contains(&format!("unknown method `{FOLDERS_METHOD}`")) => Ok(self.window_folders()),
|
||||
answer => answer,
|
||||
},
|
||||
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(h) => h.borrow_mut().call(method, params),
|
||||
}
|
||||
|
||||
@@ -900,7 +900,7 @@ fn errors_are_tool_results_not_crashes() {
|
||||
("type_text", json!({"text": "hi"})),
|
||||
("screenshot", json!({"window": true})),
|
||||
("open_file", json!({"path": "/definitely/not/here.svg"})),
|
||||
("export", json!({"path": "/tmp/out.dwg"})),
|
||||
("export", json!({"path": "/tmp/out.pmd"})),
|
||||
("redo", json!({})),
|
||||
("press_key", json!({"key": "F13"})),
|
||||
];
|
||||
|
||||
@@ -19,8 +19,13 @@ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789a
|
||||
|
||||
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
|
||||
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
|
||||
/// requests it got after authentication.
|
||||
/// requests it got after authentication. It doesn't know `agent.folders`, as a window from before it.
|
||||
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
fake_window_with_folders(token, None)
|
||||
}
|
||||
|
||||
/// [`fake_window`], answering `agent.folders` with `folders` when given.
|
||||
fn fake_window_with_folders(token: &'static str, folders: Option<Value>) -> (u16, Arc<AtomicUsize>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
@@ -29,6 +34,7 @@ fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let count = count.clone();
|
||||
let folders = folders.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut writer = stream.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
@@ -38,7 +44,11 @@ fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
|
||||
let reply = if signed_in {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
|
||||
match (&folders, req["method"] == FOLDERS_METHOD) {
|
||||
(Some(f), true) => json!({"id": req["id"], "ok": true, "result": f}),
|
||||
(None, true) => json!({"id": req["id"], "ok": false, "error": format!("unknown method `{FOLDERS_METHOD}`")}),
|
||||
_ => json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}),
|
||||
}
|
||||
} else {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
signed_in = matches!(step, AuthStep::Authenticated);
|
||||
@@ -102,12 +112,25 @@ fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
|
||||
let r = b.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(r["window"], true, "{r}");
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
// The window's folders are the agent folders as the window opens them: the default one here.
|
||||
// A window without `agent.folders`: the saved agent folders, the default one here.
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
|
||||
assert_eq!(folders["write_folder"], folders["read_folder"]);
|
||||
}
|
||||
|
||||
// `agent_folders` shows the folders the window enforces, not the saved ones: none here, as when a
|
||||
// saved folder can't be used and the window refuses every file.
|
||||
#[test]
|
||||
fn the_window_reports_the_folders_it_enforces() {
|
||||
let dir = TempFolder::new("agents-window-enforced");
|
||||
let (port, served) = fake_window_with_folders(TOKEN, Some(json!({"read_folder": null, "write_folder": null})));
|
||||
publish(&dir, port);
|
||||
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
|
||||
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
|
||||
assert_eq!(folders, json!({"read_folder": null, "write_folder": null}));
|
||||
assert!(served.load(Ordering::SeqCst) >= 1);
|
||||
}
|
||||
|
||||
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with
|
||||
// only the command's folders: the closed-app choice (an error here) is for agents the person let in.
|
||||
#[test]
|
||||
|
||||
@@ -82,7 +82,8 @@ fn export_tool_lists_engine_formats_and_options() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pict"
|
||||
"pict",
|
||||
"dwg"
|
||||
])
|
||||
);
|
||||
for k in ["artboard", "range", "options"] {
|
||||
|
||||
@@ -400,16 +400,16 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"export",
|
||||
"Export",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes, pict QuickDraw pictures as .pct), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes, pict QuickDraw pictures as .pct), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
obj(
|
||||
json!({
|
||||
"format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"},
|
||||
"path": string("Destination file (omit to get dataBase64)"),
|
||||
"scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"),
|
||||
"artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"},
|
||||
"range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"),
|
||||
"range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, DWG, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"),
|
||||
"selection": {"type": "boolean", "description": "Export only the selection, cropped to it"},
|
||||
"outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"},
|
||||
"outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF and DWG take it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"},
|
||||
"options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"},
|
||||
}),
|
||||
&[],
|
||||
|
||||
@@ -1573,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.color.screenMarks|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -1774,7 +1774,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.dxfOptionsDialog",
|
||||
"DXF Options Dialog",
|
||||
"",
|
||||
"{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too",
|
||||
"{path?, format?: dxf (default)|dwg, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too",
|
||||
),
|
||||
(
|
||||
"links.editOriginal",
|
||||
|
||||
@@ -3,11 +3,16 @@ name = "vectorcraft-metafile"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft metafiles: EMF, WMF and QuickDraw PICT export and EMF, EMF+, WMF and PICT import through craft-metafile"
|
||||
description = "VectorCraft metafiles: EMF, WMF and QuickDraw PICT export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# The binary CGM reader (`import_cgm`). Off until the craft-metafile CGM reader (craft-libs#5410)
|
||||
# merges and the workspace pins it; without it, `is_cgm` is false and `import_cgm` is refused.
|
||||
cgm = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT),
|
||||
//! are read by `craft_metafile`, and `picture` turns what they draw into document objects.
|
||||
//! and binary CGM files are read by `craft_metafile`, and `picture` turns what they draw into
|
||||
//! document objects.
|
||||
//!
|
||||
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
|
||||
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
|
||||
@@ -92,3 +93,35 @@ pub(crate) fn import_pict(bytes: &[u8]) -> Result<crate::Picture, String> {
|
||||
})?;
|
||||
Ok(picture::convert(pic))
|
||||
}
|
||||
|
||||
/// The longer side of a CGM picture without a metric scale, points (8 inches).
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_SIDE: f64 = 576.0;
|
||||
|
||||
/// Read the first picture of a binary CGM (ISO/IEC 8632-3) through `craft_metafile`.
|
||||
/// `craft_metafile::parse_cgm` comes with craft-libs#5410, so this waits on the `cgm` feature.
|
||||
#[cfg(feature = "cgm")]
|
||||
pub(crate) fn import_cgm(bytes: &[u8]) -> Result<crate::Picture, String> {
|
||||
let cgm = craft_metafile::parse_cgm(bytes, CGM_SIDE).map_err(|e| e.to_string())?;
|
||||
let n = cgm.notes;
|
||||
let mut p = picture::convert(cgm.picture);
|
||||
let notes = [
|
||||
(n.fills_approximated, "hatch, pattern and interpolated fills were filled with their fill color"),
|
||||
(n.more_pictures, "the file holds more than one picture: only the first was read"),
|
||||
(n.cie_colors, "colors in a CIE color model were read as RGB"),
|
||||
(n.text_path, "text set to run left, up or down was set to run right"),
|
||||
(n.restricted_text, "restricted text was set at its character height without fitting it to its box"),
|
||||
(n.character_spacing, "character spacing was not applied"),
|
||||
(n.text_cut, "text past 16,384 characters in one string was cut"),
|
||||
];
|
||||
p.warnings.extend(notes.iter().filter(|(on, _)| *on).map(|(_, w)| (*w).to_string()));
|
||||
if n.damaged_elements > 0 {
|
||||
let k = n.damaged_elements;
|
||||
p.warnings.push(format!(
|
||||
"{k} drawing element{} cut short or describing no shape {} left out",
|
||||
if k == 1 { "" } else { "s" },
|
||||
if k == 1 { "was" } else { "were" }
|
||||
));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips
|
||||
//! that can't be applied and raster operations other than a plain copy each add a warning.
|
||||
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
|
||||
//! document.
|
||||
//! document, and [`import_cgm`] the first picture of a binary Computer Graphics Metafile (CGM).
|
||||
//!
|
||||
//! [`painted_layers`] gives the same walk's fills and strokes, layer by layer, to writers of other
|
||||
//! formats.
|
||||
@@ -255,5 +255,34 @@ pub fn import_pict(bytes: &[u8]) -> Result<Picture, String> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Do `bytes` start like a binary CGM: BEGIN METAFILE, then METAFILE VERSION? Always false
|
||||
/// without the `cgm` feature (craft-libs#5410).
|
||||
pub fn is_cgm(bytes: &[u8]) -> bool {
|
||||
#[cfg(feature = "cgm")]
|
||||
return craft_metafile::is_cgm(bytes);
|
||||
#[cfg(not(feature = "cgm"))]
|
||||
{
|
||||
let _ = bytes;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the first picture of a binary Computer Graphics Metafile (CGM, ISO/IEC 8632-3) into a
|
||||
/// document whose one artboard is the picture's VDC extent. Without the `cgm` feature
|
||||
/// (craft-libs#5410), every file is refused.
|
||||
pub fn import_cgm(bytes: &[u8]) -> Result<Picture, String> {
|
||||
#[cfg(feature = "cgm")]
|
||||
{
|
||||
let mut p = import::import_cgm(bytes)?;
|
||||
p.document.limit_depth_noting(&mut p.warnings);
|
||||
Ok(p)
|
||||
}
|
||||
#[cfg(not(feature = "cgm"))]
|
||||
{
|
||||
let _ = bytes;
|
||||
Err("CGM files can't be read in this build".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -11,6 +11,9 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(feature = "cgm")]
|
||||
mod cgm;
|
||||
mod import;
|
||||
mod pict;
|
||||
mod pict_export;
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Binary Computer Graphics Metafiles read from hand-built elements: the picture's frame and its
|
||||
//! scale, lines, shapes, arcs, figures, markers, text, cell arrays and clips; elements written in
|
||||
//! partitions; and files that aren't binary CGM, hold no picture, are cut short or hold more than
|
||||
//! one picture.
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::{import_cgm, is_cgm};
|
||||
|
||||
/// Big-endian 16-bit words.
|
||||
fn be(v: &[i16]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// One element in the short form (or the long form past 30 bytes, in one partition), padded to
|
||||
/// an even length.
|
||||
fn el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
b.extend(((class << 12) | (id << 5) | data.len() as u16).to_be_bytes());
|
||||
} else {
|
||||
b.extend(((class << 12) | (id << 5) | 31).to_be_bytes());
|
||||
b.extend((data.len() as u16).to_be_bytes());
|
||||
}
|
||||
b.extend(data);
|
||||
if data.len() % 2 == 1 {
|
||||
b.push(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A string parameter.
|
||||
fn s(text: &str) -> Vec<u8> {
|
||||
[vec![text.len() as u8], text.as_bytes().to_vec()].concat()
|
||||
}
|
||||
|
||||
/// A metafile of one picture: `descriptor` after METAFILE VERSION, `picture` after BEGIN PICTURE
|
||||
/// and `body` after BEGIN PICTURE BODY.
|
||||
fn cgm(descriptor: &[Vec<u8>], picture: &[Vec<u8>], body: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut b = el(0, 1, &s("test"));
|
||||
b.extend(el(1, 1, &be(&[1])));
|
||||
descriptor.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 3, &s("p1")));
|
||||
picture.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 4, &[]));
|
||||
body.iter().for_each(|e| b.extend(e));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
b
|
||||
}
|
||||
|
||||
/// A VDC extent of 1000 × 500 units: abstract, so 576 × 288 pt (0.576 pt a unit).
|
||||
fn extent() -> Vec<u8> {
|
||||
el(2, 6, &be(&[0, 0, 1000, 500]))
|
||||
}
|
||||
|
||||
/// Direct color selection: colors as 8-bit RGB.
|
||||
fn direct() -> Vec<u8> {
|
||||
el(2, 2, &be(&[1]))
|
||||
}
|
||||
|
||||
/// A VDC point (x, y) in points: y runs up from the bottom of the 1000 × 500 extent.
|
||||
fn pt(x: f64, y: f64) -> Point {
|
||||
Point::new(x * 0.576, (500.0 - y) * 0.576)
|
||||
}
|
||||
|
||||
fn all(d: &Document) -> Vec<Node> {
|
||||
let mut v = vec![];
|
||||
for l in &d.layers {
|
||||
for c in l.children().into_iter().flatten() {
|
||||
c.walk(&mut |n| v.push(n.clone()));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn paths(d: &Document) -> Vec<Node> {
|
||||
all(d).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol)
|
||||
}
|
||||
|
||||
fn fill_rgb(n: &Node) -> Option<[u8; 3]> {
|
||||
n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn stroke(n: &Node) -> Option<([u8; 3], f64)> {
|
||||
n.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Stroke(s) => s.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
([r, g, b], s.width)
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn images(d: &Document) -> Vec<(Node, image::RgbaImage)> {
|
||||
all(d)
|
||||
.into_iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
let decoded = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
|
||||
Some((n.clone(), image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_opens_on_its_extent_with_the_first_corner_at_the_bottom_left() {
|
||||
let bytes = cgm(&[], &[extent(), direct()], &[el(5, 22, &be(&[1])), el(5, 23, &[255, 0, 0]), el(4, 11, &be(&[100, 100, 300, 200]))]);
|
||||
assert!(is_cgm(&bytes));
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
assert!(near(p.document.artboards[0].rect, Rect::new(0.0, 0.0, 576.0, 288.0), 1e-9));
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1, "{v:?}");
|
||||
assert_eq!(fill_rgb(&v[0]), Some([255, 0, 0]));
|
||||
assert!(v[0].appearance.stroke().is_none(), "edges are off by default");
|
||||
let b = v[0].geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::from_points(pt(100.0, 100.0), pt(300.0, 200.0)), 1e-4), "{b:?}");
|
||||
|
||||
// An extent whose first corner is its top left turns the picture over: the same rectangle
|
||||
// is then as far from the top as it was from the bottom.
|
||||
let flipped = cgm(&[], &[el(2, 6, &be(&[0, 500, 1000, 0])), direct()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[100, 100, 300, 200]))]);
|
||||
let b = paths(&import_cgm(&flipped).unwrap().document)[0].geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(57.6, 57.6, 172.8, 115.2), 1e-4), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metric_picture_keeps_its_size() {
|
||||
// 0.1 mm a unit: 100 × 50 mm.
|
||||
let metric = el(2, 1, &[be(&[1]), 0.1f32.to_be_bytes().to_vec()].concat());
|
||||
let p = import_cgm(&cgm(&[], &[metric, extent()], &[el(4, 1, &be(&[0, 0, 1000, 500]))])).unwrap();
|
||||
let size = p.document.artboards[0].rect.size();
|
||||
let mm = 72.0 / 25.4;
|
||||
assert!((size.width - 100.0 * mm).abs() < 1e-3 && (size.height - 50.0 * mm).abs() < 1e-3, "{size:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_take_their_width_color_type_caps_and_joins() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
// Widths in VDC units.
|
||||
&[extent(), el(2, 3, &be(&[0])), el(2, 17, &be(&[-1, 200, 1, 3]))],
|
||||
&[
|
||||
// Color 9 from the color table: green.
|
||||
el(5, 34, &[9, 0, 200, 0]),
|
||||
el(5, 4, &[9]),
|
||||
el(5, 3, &be(&[10])),
|
||||
el(5, 2, &be(&[2])),
|
||||
el(5, 37, &be(&[2, 2])),
|
||||
el(5, 38, &be(&[4])),
|
||||
el(4, 1, &be(&[0, 0, 500, 0, 500, 250])),
|
||||
// Default color index 1 (black), a disjoint polyline: two separate lines.
|
||||
el(5, 4, &[1]),
|
||||
el(5, 2, &be(&[1])),
|
||||
el(4, 2, &be(&[0, 400, 100, 400, 200, 400, 300, 400])),
|
||||
// Line type -1 as the picture defines it: 200 units, a quarter on and three off.
|
||||
el(5, 2, &be(&[-1])),
|
||||
el(4, 1, &be(&[0, 450, 1000, 450])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 3, "{v:?}");
|
||||
let dash = v[2].appearance.stroke().unwrap().dash.clone().unwrap();
|
||||
assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 28.8).abs() < 1e-3 && (dash.pattern[1] - 86.4).abs() < 1e-3, "{dash:?}");
|
||||
let (rgb, w) = stroke(&v[0]).unwrap();
|
||||
assert_eq!(rgb, [0, 200, 0]);
|
||||
assert!((w - 5.76).abs() < 1e-4, "{w}");
|
||||
let st = v[0].appearance.stroke().unwrap();
|
||||
assert!(st.dash.as_ref().is_some_and(|d| d.is_dashed()), "line type 2 is dashed");
|
||||
assert_eq!((st.cap, st.join), (vectorcraft_doc::LineCap::Butt, vectorcraft_doc::LineJoin::Bevel));
|
||||
let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 2);
|
||||
assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_ellipses_and_arcs_are_curves_in_their_place() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
// A circle of radius 100 at (500, 250).
|
||||
el(4, 12, &be(&[500, 250, 100])),
|
||||
// An ellipse 200 across and 50 high at (200, 100).
|
||||
el(4, 17, &be(&[200, 100, 300, 100, 200, 125])),
|
||||
// A half circle from (900, 250) through (800, 350) to (700, 250): the top half.
|
||||
el(4, 13, &be(&[900, 250, 800, 350, 700, 250])),
|
||||
// A quarter circle around (100, 400), from east to north, closed as a pie.
|
||||
el(4, 16, &be(&[100, 400, 1, 0, 0, 1, 50, 0])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 4, "{v:?}");
|
||||
// Cubic Béziers stand in for the curves: within 0.03% of the radius.
|
||||
let tol = 0.05;
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(400.0, 150.0), pt(600.0, 350.0)), tol));
|
||||
assert!(near(v[1].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 75.0), pt(300.0, 125.0)), tol));
|
||||
assert!(near(v[2].geometric_bounds().unwrap(), Rect::from_points(pt(700.0, 250.0), pt(900.0, 350.0)), tol));
|
||||
assert!(v[2].appearance.fill().is_none(), "an open arc is stroked");
|
||||
assert!(near(v[3].geometric_bounds().unwrap(), Rect::from_points(pt(100.0, 400.0), pt(150.0, 450.0)), tol));
|
||||
assert!(fill_rgb(&v[3]).is_some(), "a closed arc is filled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_outline_shapes_and_polygon_sets_skip_their_hidden_edges() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent(), direct()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
el(5, 30, &be(&[1])),
|
||||
el(5, 29, &[0, 0, 255]),
|
||||
// Two squares; the first one's left edge (from its last point) is hidden.
|
||||
el(4, 8, &be(&[0, 0, 1, 100, 0, 1, 100, 100, 1, 0, 100, 2, 200, 0, 1, 300, 0, 1, 300, 100, 1, 200, 100, 3])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 2, "a fill and its edges: {v:?}");
|
||||
let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 2, "both squares fill");
|
||||
assert_eq!(stroke(&v[1]).unwrap().0, [0, 0, 255]);
|
||||
let NodeKind::Path { path, .. } = &v[1].kind else { panic!("a path") };
|
||||
// The first square's three visible edges are one open line, and the second square is one
|
||||
// closed outline.
|
||||
assert_eq!(path.subpaths.len(), 2, "one outline for each square");
|
||||
assert_eq!(path.subpaths.iter().filter(|s| s.closed).count(), 1, "{:?}", path.subpaths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_figure_fills_its_lines_as_one_shape() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 22, &be(&[1])),
|
||||
el(0, 8, &[]),
|
||||
el(4, 1, &be(&[0, 0, 100, 0])),
|
||||
el(4, 15, &be(&[100, 50, 0, -1, 0, 1, 50])),
|
||||
el(4, 1, &be(&[100, 100, 0, 100])),
|
||||
el(0, 9, &[]),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1, "{v:?}");
|
||||
assert!(fill_rgb(&v[0]).is_some() && v[0].appearance.stroke().is_none());
|
||||
let NodeKind::Path { path, .. } = &v[0].kind else { panic!("a path") };
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(150.0, 100.0)), 0.05));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_comes_in_as_point_type_at_its_character_height() {
|
||||
let bytes = cgm(
|
||||
&[el(1, 13, &[s("Times-Roman"), s("Helvetica-BoldOblique")].concat())],
|
||||
&[extent()],
|
||||
&[
|
||||
el(5, 10, &be(&[2])),
|
||||
el(5, 15, &be(&[70])),
|
||||
// Not final: the rest of the string follows in APPEND TEXT.
|
||||
el(4, 4, &[be(&[100, 200, 0]), s("Hel")].concat()),
|
||||
el(4, 6, &[be(&[1]), s("lo")].concat()),
|
||||
// Restricted text: its box is not applied, and a warning says so.
|
||||
el(4, 5, &[be(&[300, 70, 100, 50, 1]), s("Box")].concat()),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert_eq!(p.warnings, ["restricted text was set at its character height without fitting it to its box"]);
|
||||
let texts: Vec<_> = all(&p.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).collect();
|
||||
assert_eq!(texts.len(), 2);
|
||||
let NodeKind::Text(t) = &texts[0].kind else { panic!("text") };
|
||||
assert_eq!(t.plain_text(), "Hello");
|
||||
let st = &t.runs[0].style;
|
||||
assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Helvetica", "Bold Italic"));
|
||||
// The character height (70 units, 40.32 pt) is the cap height: 0.7 of the size.
|
||||
assert!((st.size - 57.6).abs() < 1e-3, "{}", st.size);
|
||||
assert!((t.xf.translation().to_point() - pt(100.0, 200.0)).hypot() < 1e-3, "{:?}", t.xf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_reader_left_out_or_set_differently_is_warned_about() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[
|
||||
// Character spacing 0.5, then a rectangle with one corner and a circle without its radius.
|
||||
el(5, 13, &[0, 0, 0x80, 0]),
|
||||
el(4, 4, &[be(&[0, 0, 1]), s("spaced")].concat()),
|
||||
el(4, 11, &be(&[0, 0])),
|
||||
el(4, 12, &be(&[10, 10])),
|
||||
el(4, 11, &be(&[0, 0, 10, 10])),
|
||||
],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.iter().any(|w| w == "character spacing was not applied"), "{:?}", p.warnings);
|
||||
assert!(p.warnings.iter().any(|w| w == "2 drawing elements cut short or describing no shape were left out"), "{:?}", p.warnings);
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cell_arrays_become_images_packed_or_run_length() {
|
||||
// 2 × 2 cells over (0, 0) to (200, 100), first row along the bottom: red, green, then blue,
|
||||
// white.
|
||||
let corners = be(&[0, 0, 200, 100, 200, 0]);
|
||||
let packed = [corners.clone(), be(&[2, 2, 8, 1]), vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 255, 255]].concat();
|
||||
// Runs: a count (16 bits) and a color.
|
||||
let run = |color: [u8; 3]| [be(&[1]), color.to_vec()].concat();
|
||||
let runs = [corners.clone(), be(&[2, 2, 8, 0]), run([255, 0, 0]), run([0, 255, 0]), run([0, 0, 255]), run([255, 255, 255])].concat();
|
||||
// 4-bit indexed cells: each row of two cells takes one byte and is padded to a word.
|
||||
let indexed = [corners, be(&[2, 2, 4, 1]), vec![0x23, 0, 0x41, 0]].concat();
|
||||
for data in [packed, runs] {
|
||||
let p = import_cgm(&cgm(&[], &[extent(), direct()], &[el(4, 9, &data)])).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let imgs = images(&p.document);
|
||||
assert_eq!(imgs.len(), 1);
|
||||
let (n, px) = &imgs[0];
|
||||
assert_eq!(px.dimensions(), (2, 2));
|
||||
assert_eq!(px.get_pixel(0, 0).0, [255, 0, 0, 255]);
|
||||
assert_eq!(px.get_pixel(1, 0).0, [0, 255, 0, 255]);
|
||||
assert_eq!(px.get_pixel(0, 1).0, [0, 0, 255, 255]);
|
||||
// The first row is at the bottom of the picture: drawn upward from P.
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::from_points(pt(0.0, 0.0), pt(200.0, 100.0)), 1e-3), "{b:?}");
|
||||
}
|
||||
// Indexed cells through the default color table.
|
||||
let p = import_cgm(&cgm(&[], &[extent()], &[el(4, 9, &indexed)])).unwrap();
|
||||
let px = &images(&p.document)[0].1;
|
||||
let row = |y| [px.get_pixel(0, y).0, px.get_pixel(1, y).0];
|
||||
assert_eq!(row(0), [[255, 0, 0, 255], [0, 255, 0, 255]]);
|
||||
assert_eq!(row(1), [[0, 0, 255, 255], [0, 0, 0, 255]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_are_drawn_at_their_points() {
|
||||
let bytes = cgm(&[], &[extent()], &[el(5, 6, &be(&[4])), el(4, 3, &be(&[100, 100, 900, 400]))]);
|
||||
let v = paths(&import_cgm(&bytes).unwrap().document);
|
||||
assert_eq!(v.len(), 2);
|
||||
// A nominal marker is 1/100 of the longer side across: 5.76 pt.
|
||||
let b = v[1].geometric_bounds().unwrap();
|
||||
assert!((b.center() - pt(900.0, 400.0)).hypot() < 1e-3 && (b.width() - 5.76).abs() < 1e-2, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clip_rectangle_clips_what_follows() {
|
||||
let bytes = cgm(
|
||||
&[],
|
||||
&[extent()],
|
||||
&[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(3, 5, &be(&[0, 0, 500, 250])), el(4, 11, &be(&[0, 0, 1000, 500]))],
|
||||
);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
let layer = p.document.layers[0].children().unwrap();
|
||||
assert!(matches!(layer[0].kind, NodeKind::Path { .. }), "the picture's own extent clips nothing");
|
||||
let NodeKind::Group { children, clip: true } = &layer[1].kind else { panic!("a clipping group: {:?}", layer[1].kind) };
|
||||
assert!(near(children[0].geometric_bounds().unwrap(), Rect::from_points(pt(0.0, 0.0), pt(500.0, 250.0)), 1e-3));
|
||||
// With the clip indicator off, nothing is clipped.
|
||||
let off = [el(3, 5, &be(&[0, 0, 500, 250])), el(3, 6, &be(&[0])), el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 1000, 500]))];
|
||||
let off = cgm(&[], &[extent()], &off);
|
||||
let p = import_cgm(&off).unwrap();
|
||||
assert!(matches!(p.document.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precisions_real_coordinates_partitions_and_default_replacements() {
|
||||
// Real VDC (fixed point 16.16), a line width set in the metafile's defaults, and a polyline
|
||||
// in two partitions.
|
||||
let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes().to_vec();
|
||||
let mdr = el(1, 12, &[el(2, 3, &be(&[0])), el(5, 3, &fixed(100.0))].concat());
|
||||
let real_extent = el(2, 6, &[fixed(0.0), fixed(0.0), fixed(1000.0), fixed(500.0)].concat());
|
||||
let points: Vec<u8> = [0.0, 0.0, 500.0, 0.0, 500.0, 250.0, 1000.0, 500.0].iter().flat_map(|v| fixed(*v)).collect();
|
||||
let mut body = vec![];
|
||||
body.extend(((4u16 << 12) | (1 << 5) | 31).to_be_bytes());
|
||||
body.extend((0x8000u16 | 16).to_be_bytes());
|
||||
body.extend(&points[..16]);
|
||||
body.extend(16u16.to_be_bytes());
|
||||
body.extend(&points[16..]);
|
||||
let bytes = cgm(&[el(1, 3, &be(&[1])), mdr], &[real_extent], &[body]);
|
||||
let p = import_cgm(&bytes).unwrap();
|
||||
assert!(p.warnings.is_empty(), "{:?}", p.warnings);
|
||||
let v = paths(&p.document);
|
||||
assert_eq!(v.len(), 1);
|
||||
assert!(near(v[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 576.0, 288.0), 1e-3));
|
||||
assert!((stroke(&v[0]).unwrap().1 - 57.6).abs() < 1e-3, "{:?}", stroke(&v[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_that_are_not_binary_cgm_are_refused() {
|
||||
assert_eq!(import_cgm(b"").unwrap_err(), "not a CGM file");
|
||||
assert_eq!(import_cgm(&[0; 64]).unwrap_err(), "not a CGM file");
|
||||
assert!(!is_cgm(&[0; 64]));
|
||||
let clear = import_cgm(b"BEGMF 'drawing';\nmfversion 1;\n").unwrap_err();
|
||||
assert!(clear.contains("only binary CGM files"), "{clear}");
|
||||
// A metafile without a picture.
|
||||
let mut b = el(0, 1, &s("empty"));
|
||||
b.extend(el(1, 1, &be(&[1])));
|
||||
b.extend(el(0, 2, &[]));
|
||||
assert!(is_cgm(&b));
|
||||
assert_eq!(import_cgm(&b).unwrap_err(), "the CGM file holds no picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_cut_short_keeps_what_came_before() {
|
||||
let full = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100])), el(4, 11, &be(&[200, 0, 300, 100]))]);
|
||||
// Cut inside the second rectangle.
|
||||
let cut = &full[..full.len() - 10];
|
||||
let p = import_cgm(cut).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("cut short")), "{:?}", p.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_first_picture_is_read() {
|
||||
let mut b = cgm(&[], &[extent()], &[el(5, 22, &be(&[1])), el(4, 11, &be(&[0, 0, 100, 100]))]);
|
||||
// Drop END METAFILE and add a second picture.
|
||||
b.truncate(b.len() - 2);
|
||||
b.extend(el(0, 3, &s("p2")));
|
||||
b.extend(el(0, 4, &[]));
|
||||
b.extend(el(4, 11, &be(&[0, 0, 500, 500])));
|
||||
b.extend(el(0, 5, &[]));
|
||||
b.extend(el(0, 2, &[]));
|
||||
let p = import_cgm(&b).unwrap();
|
||||
assert_eq!(paths(&p.document).len(), 1);
|
||||
assert!(p.warnings.iter().any(|w| w.contains("only the first")), "{:?}", p.warnings);
|
||||
}
|
||||
@@ -108,6 +108,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
egui_extras = { workspace = true }
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true, features = ["swatch-scans"] }
|
||||
vectorcraft-tools = { workspace = true, features = ["testing"] }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
//! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's
|
||||
//! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live
|
||||
//! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and
|
||||
//! Randomize Fill Colors ([`random_fill`]) and opens the panel.
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]), Create
|
||||
//! Screen Print Marks ([`screen_marks`]) and Randomize Fill Colors ([`random_fill`]) and opens the
|
||||
//! panel.
|
||||
|
||||
pub mod legend;
|
||||
pub mod nearest;
|
||||
pub mod random_fill;
|
||||
pub mod screen_marks;
|
||||
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders};
|
||||
use craft::menu::Node;
|
||||
@@ -113,6 +115,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cmd(print_fixes()),
|
||||
c("Find Nearest Swatch…", nearest::COMMAND),
|
||||
c("Create Swatch Legend…", legend::COMMAND),
|
||||
c("Create Screen Print Marks…", screen_marks::COMMAND),
|
||||
Sep,
|
||||
// Each selected object's stroke takes its own fill, or the other way (#5530).
|
||||
cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Create Screen Print Marks in the interface (Object › Plug-ins › Color Effects › Create Screen
|
||||
//! Print Marks…): a dialog for where the registration targets go, their size, stroke weight, inset
|
||||
//! and ink, the spot ink and file lines with their type size and place, and whether every artboard
|
||||
//! gets marks. It previews on the canvas and runs `addon.color.screenMarks` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
use crate::canvas::rulers::{general_lengths, stroke_lengths, type_lengths};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
/// The target positions: (the command's name, the dialog's label), in the command's order.
|
||||
pub const POSITIONS: [(&str, &str); 8] = [
|
||||
("topLeft", "Top Left"),
|
||||
("top", "Top Center"),
|
||||
("topRight", "Top Right"),
|
||||
("left", "Left Center"),
|
||||
("right", "Right Center"),
|
||||
("bottomLeft", "Bottom Left"),
|
||||
("bottom", "Bottom Center"),
|
||||
("bottomRight", "Bottom Right"),
|
||||
];
|
||||
/// The positions ticked when the dialog opens: the command's default.
|
||||
const TICKED: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The positions ticked in `fields`, in the command's order.
|
||||
fn ticked(fields: &DialogFields) -> Vec<&'static str> {
|
||||
POSITIONS.iter().filter(|(key, _)| fields.bool(key).unwrap_or(false)).map(|(key, _)| *key).collect()
|
||||
}
|
||||
|
||||
/// Whether `fields` ask for anything to be drawn: a target, the file line, or the spot ink line of a document
|
||||
/// that has spot inks (`spots`).
|
||||
fn draws(fields: &DialogFields, spots: bool) -> bool {
|
||||
!ticked(fields).is_empty() || (spots && fields.bool("inks").unwrap_or(false)) || fields.bool("info").unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The command's params from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
json!({
|
||||
"positions": ticked(fields),
|
||||
"size": fields.number("size").unwrap_or(36.0),
|
||||
"weight": fields.number("weight").unwrap_or(1.0),
|
||||
"inset": fields.number("inset").unwrap_or(18.0),
|
||||
"ink": fields.text("ink").unwrap_or(REGISTRATION),
|
||||
"inks": fields.bool("inks").unwrap_or(false),
|
||||
"info": fields.bool("info").unwrap_or(false),
|
||||
"textSize": fields.number("textSize").unwrap_or(9.0),
|
||||
"textPlace": fields.text("textPlace").unwrap_or("bottom"),
|
||||
"textAlign": fields.text("textAlign").unwrap_or("left"),
|
||||
"allArtboards": fields.bool("allArtboards").unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens Create Screen Print Marks' dialog on the command's defaults. The ink list is [Registration] and the
|
||||
/// document's spot swatches, read once, when it opens.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let mut inks = vec![REGISTRATION.to_string()];
|
||||
if let Some(st) = app.session.active() {
|
||||
inks.extend(
|
||||
st.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()),
|
||||
);
|
||||
}
|
||||
let mut fields = DialogFields::from_pairs([
|
||||
("size", FieldValue::Number(36.0)),
|
||||
("weight", FieldValue::Number(1.0)),
|
||||
("inset", FieldValue::Number(18.0)),
|
||||
("ink", FieldValue::Text(REGISTRATION.into())),
|
||||
("inks", FieldValue::Bool(false)),
|
||||
("info", FieldValue::Bool(false)),
|
||||
("textSize", FieldValue::Number(9.0)),
|
||||
("textPlace", FieldValue::Text("bottom".into())),
|
||||
("textAlign", FieldValue::Text("left".into())),
|
||||
("allArtboards", FieldValue::Bool(false)),
|
||||
]);
|
||||
for (key, _) in POSITIONS {
|
||||
fields.set(key, FieldValue::Bool(TICKED.contains(&key)));
|
||||
}
|
||||
let (lengths, strokes, types) = (general_lengths(app), stroke_lengths(app), type_lengths(app));
|
||||
dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let ink_choices = inks.iter().map(|name| (name.clone(), name.clone().into())).collect();
|
||||
let places = vec![("bottom".to_string(), tl!("Bottom").into()), ("top".to_string(), tl!("Top").into())];
|
||||
let aligns = vec![("left".to_string(), tl!("Left").into()), ("right".to_string(), tl!("Right").into())];
|
||||
let mut rows = vec![Param::section(tl!("Targets:"))];
|
||||
rows.extend(POSITIONS.iter().map(|&(key, label)| Param::new(key, tl!(label), ParamKind::bool(TICKED.contains(&key)))));
|
||||
rows.extend([
|
||||
Param::number("size", tl!("Size:"), 36.0, 1.0, 2).length(lengths).bounds(Some(4.0), Some(1000.0)),
|
||||
Param::number("weight", tl!("Weight:"), 1.0, 0.1, 2).length(strokes).bounds(Some(0.1), Some(20.0)),
|
||||
Param::number("inset", tl!("Inset:"), 18.0, 1.0, 2).length(lengths).bounds(Some(-1000.0), Some(1000.0)),
|
||||
Param::new("ink", tl!("Ink:"), ParamKind::choice(ink_choices, Some(REGISTRATION.into()))),
|
||||
Param::section(tl!("Text:")),
|
||||
Param::new("inks", tl!("Spot Ink Names"), ParamKind::bool(false)),
|
||||
Param::new("info", tl!("File Name and Date"), ParamKind::bool(false)),
|
||||
Param::number("textSize", tl!("Type Size:"), 9.0, 1.0, 1).length(types).bounds(Some(4.0), Some(72.0)),
|
||||
Param::new("textPlace", tl!("Place:"), ParamKind::choice(places, Some("bottom".into()))),
|
||||
Param::new("textAlign", tl!("Align:"), ParamKind::choice(aligns, Some("left".into()))),
|
||||
Param::new("allArtboards", tl!("All Artboards"), ParamKind::bool(false)),
|
||||
]);
|
||||
let ok = draws(fields, inks.len() > 1);
|
||||
ParamDialog::new(COMMAND, tl!("Create Screen Print Marks"), rows)
|
||||
.ok_enabled(ok)
|
||||
.ok_reason(tl!("Tick a target or a line of text.").into())
|
||||
.values(Bind::bound(fields))
|
||||
.previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,145 @@
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::tests as host;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
/// The marks group of the active document's marks layer: its targets' rings' widths and its type lines.
|
||||
fn marks(app: &VectorcraftApp) -> Option<(Vec<f64>, Vec<String>)> {
|
||||
let doc = &app.session.active()?.doc;
|
||||
let layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Screen Print Marks"))?;
|
||||
let group: &Node = layer.children()?.first()?;
|
||||
let kids = group.children()?;
|
||||
let rings = kids
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap()[0].geometric_bounds().unwrap().width())
|
||||
.collect();
|
||||
let lines = kids
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.plain_text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Some((rings, lines))
|
||||
}
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
app.run("swatch.new", json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Keyboard and checkbox edits reach the preview; Cancel restores the drawing, while OK with Preview off applies the
|
||||
/// same values in one undo step.
|
||||
#[test]
|
||||
fn keyboard_and_checkbox_edits_reach_the_preview_ok_and_cancel() {
|
||||
for commit in [false, true] {
|
||||
let app = app();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 1000.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on");
|
||||
assert!(panel.app().session.in_interaction(), "the opening marks are previewed");
|
||||
assert_eq!(marks(&panel.app()).map(|(rings, _)| rings.len()), Some(4), "four targets on opening");
|
||||
if commit {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
}
|
||||
panel.click_role("Left Center", Role::CHECK_BOX);
|
||||
panel.click_role("Right Center", Role::CHECK_BOX);
|
||||
panel.click_role("Spot Ink Names", Role::CHECK_BOX);
|
||||
panel.click_role("Size", Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text("40 pt");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
let edited = |app: &VectorcraftApp| {
|
||||
let (rings, lines) = marks(app).expect("the marks layer");
|
||||
assert_eq!(rings.len(), 2, "the unticked sides draw no target");
|
||||
assert!(rings.iter().all(|w| (w - 20.0).abs() < 1e-6), "the typed size reaches the targets: {rings:?}");
|
||||
assert_eq!(lines, ["Plate Red"], "the spot ink line");
|
||||
};
|
||||
if commit {
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
} else {
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
|
||||
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// With no target ticked and no line, OK is off; a spot ink picked in the dialog strokes the targets.
|
||||
#[test]
|
||||
fn ok_needs_something_to_draw_and_the_ink_list_offers_the_spot_swatches() {
|
||||
let mut app = crate::testing::windowed(app());
|
||||
host::open_item(&mut app, "Color Effects", "Create Screen Print Marks…");
|
||||
let id = host::dialog_id(&app);
|
||||
for key in ["top", "bottom", "left", "right"] {
|
||||
host::set(&app, id, key, json!(false));
|
||||
}
|
||||
host::frame(&mut app);
|
||||
assert!(!host::confirm(&app, id), "nothing to draw: OK is off");
|
||||
host::set(&app, id, "topLeft", json!(true));
|
||||
host::set(&app, id, "ink", json!("Plate Red"));
|
||||
host::frame(&mut app);
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert!(layer.locked, "the marks layer is locked at the bottom");
|
||||
let target = &layer.children().unwrap()[0].children().unwrap()[0];
|
||||
let ring = &target.children().unwrap()[0];
|
||||
let linked = match ring.appearance.stroke_paint() {
|
||||
vectorcraft_color::Paint::Solid { swatch, .. } => swatch,
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(linked.as_deref(), Some("Plate Red"));
|
||||
}
|
||||
|
||||
/// The ticked positions go in the command's order; every other value goes as the dialog holds it.
|
||||
#[test]
|
||||
fn params_lists_the_ticked_positions_in_order() {
|
||||
let fields = DialogFields::from_pairs([
|
||||
("bottomRight", FieldValue::Bool(true)),
|
||||
("topLeft", FieldValue::Bool(true)),
|
||||
("top", FieldValue::Bool(false)),
|
||||
("textPlace", FieldValue::Text("top".into())),
|
||||
("info", FieldValue::Bool(true)),
|
||||
]);
|
||||
let p = super::params(&fields);
|
||||
assert_eq!(p["positions"], json!(["topLeft", "bottomRight"]));
|
||||
assert_eq!(p["textPlace"], json!("top"));
|
||||
assert_eq!(p["info"], json!(true));
|
||||
assert_eq!(p["ink"], json!("[Registration]"));
|
||||
assert!(p.get("time").is_none(), "the date is the time of the run");
|
||||
}
|
||||
|
||||
/// Spot Ink Names alone draws something only in a document with spot inks.
|
||||
#[test]
|
||||
fn the_spot_ink_line_alone_needs_spot_inks() {
|
||||
let fields = DialogFields::from_pairs([("inks", FieldValue::Bool(true))]);
|
||||
assert!(!super::draws(&fields, false));
|
||||
assert!(super::draws(&fields, true));
|
||||
}
|
||||
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user