Merge main into feat/character-anti-aliasing-method

This commit is contained in:
dotCooCoo committed 2026-10-30 19:23:59 -07:00
commit 21d00bf04c
189 files changed
+13534 -577

No files matched your search

Generated
+34 -34
View File
@@ -217,7 +217,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -303,7 +303,7 @@ dependencies = [
"futures-lite",
"parking",
"polling",
"rustix 1.1.5",
"rustix 1.1.6",
"slab",
"windows-sys 0.61.2",
]
@@ -334,7 +334,7 @@ dependencies = [
"cfg-if",
"event-listener",
"futures-lite",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -360,7 +360,7 @@ dependencies = [
"cfg-if",
"futures-core",
"futures-io",
"rustix 1.1.5",
"rustix 1.1.6",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
@@ -665,7 +665,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e"
dependencies = [
"bitflags 2.13.2",
"polling",
"rustix 1.1.5",
"rustix 1.1.6",
"tracing",
]
@@ -688,7 +688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa"
dependencies = [
"calloop 0.14.5",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-client",
]
@@ -763,9 +763,9 @@ dependencies = [
[[package]]
name = "clipboard-win"
version = "5.4.1"
version = "5.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
dependencies = [
"error-code",
]
@@ -1563,7 +1563,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1888,7 +1888,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
"windows-link",
]
@@ -3618,7 +3618,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3900,7 +3900,7 @@ dependencies = [
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
@@ -4140,7 +4140,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4489,15 +4489,15 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.5"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4556,7 +4556,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5097,9 +5097,9 @@ dependencies = [
[[package]]
name = "smallvec"
version = "1.16.3"
version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
dependencies = [
"serde",
]
@@ -5142,7 +5142,7 @@ dependencies = [
"libc",
"log",
"memmap2",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"wayland-backend",
"wayland-client",
@@ -5415,10 +5415,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.59.0",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
[[package]]
@@ -6199,7 +6199,7 @@ dependencies = [
"log",
"proptest",
"roxmltree 0.21.2",
"rustix 1.1.5",
"rustix 1.1.6",
"ruzstd",
"serde",
"serde_json",
@@ -6256,7 +6256,7 @@ version = "0.18.0"
dependencies = [
"flate2",
"proptest",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -6517,7 +6517,7 @@ dependencies = [
"egui_kittest",
"image",
"log",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_json",
"toml",
@@ -6810,7 +6810,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
"downcast-rs",
"rustix 1.1.5",
"rustix 1.1.6",
"scoped-tls",
"smallvec",
"wayland-sys",
@@ -6823,7 +6823,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
dependencies = [
"bitflags 2.13.2",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-scanner",
]
@@ -6845,7 +6845,7 @@ version = "0.31.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-client",
"xcursor",
]
@@ -7183,7 +7183,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7520,7 +7520,7 @@ dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
@@ -7579,7 +7579,7 @@ dependencies = [
"libc",
"libloading",
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
"x11rb-protocol",
]
@@ -7621,7 +7621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -7725,7 +7725,7 @@ dependencies = [
"hex",
"libc",
"ordered-stream",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_repr",
"tracing",
+2 -2
View File
@@ -116,7 +116,7 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> {
let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() };
let err = |e: vectorcraft_engine::EngineError| e.to_string();
let mut drag = |down: Point| -> Result<f64, String> {
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), pressure: 1.0 };
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, pressure: 1.0 };
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?;
s.select_tool("directSelection", view).map_err(err)?;
let undo = s.doc().map_err(err)?.history.undo.len();
@@ -215,7 +215,7 @@ fn deep(n: usize) -> Result<(), String> {
let first = s.doc().map_err(err)?.selection.objects.first().copied();
let at = first.and_then(|id| s.doc().ok()?.doc.node(id)?.geometric_bounds()).map(|b| b.center());
if let Some(down) = at {
let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), pressure: 1.0 };
let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), backquote: false, pressure: 1.0 };
s.select_tool("selection", view).map_err(err)?;
s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?;
let mut dx = 0.0;
+1
View File
@@ -339,6 +339,7 @@ mod portable {
}
/// What a write of a picture says where the clipboard carries text only.
#[cfg(target_os = "linux")]
const TEXT_ONLY: &str = "this clipboard carries text only";
impl Backend {
+3
View File
@@ -6,7 +6,10 @@
//! with one to four inks.
//! - [`halftone`]: Color Effects' live Vector Halftone, and the screens Object › Vector Halftone
//! builds its dots with.
//! - [`path`]: Path Precision Tools' live Path Effects, geometry effects built on the add-on's path
//! kernels.
pub mod color;
pub mod duotone;
pub mod halftone;
pub mod path;
+243
View File
@@ -0,0 +1,243 @@
//! Path Effects (Path Precision Tools): live geometry effects that rewrite an object's path with the
//! add-on's path kernels (Effect › Path Effects). Each is evaluated with the other geometry effects
//! ([`crate::apply_geometry`]), so it draws, measures, exports and expands as they do; the geometry
//! is written only by Expand Appearance.
//!
//! Parameters come from documents and scripts, so each is clamped to its documented range, and a
//! path with a coordinate past [`MAX_COORDINATE`] or not finite is left as it is.
use serde_json::{Value, json};
use vectorcraft_doc::Dash;
use vectorcraft_geom::{PathData, Point, SubPath};
use vectorcraft_pathops::addons::pathtools::{self as tools, AnchorSpacing, CloseMode, ExtendMode, SMOOTH_RATIO, SegmentKind};
use vectorcraft_pathops::addons::{PT_PER_TOLERANCE, retract_tiny_handles, simplify_keep_shape};
use crate::catalog::{EffectInfo, Lengths};
use crate::stroke;
use crate::util::{flag, num, text};
/// What every Path Effect's id starts with.
pub const PREFIX: &str = "addon.path.";
pub const DASHES: &str = "addon.path.dashes";
pub const ADD_ANCHORS: &str = "addon.path.addAnchors";
pub const EXTEND: &str = "addon.path.extend";
pub const CLOSE: &str = "addon.path.close";
pub const SMOOTH: &str = "addon.path.smooth";
pub const RETRACT: &str = "addon.path.retract";
pub const REVERSE: &str = "addon.path.reverse";
pub const SIMPLIFY: &str = "addon.path.simplify";
pub const SPLIT: &str = "addon.path.split";
const MENU: &[&str] = &["Effect", "Path Effects"];
/// The dash and gap parameters of [`DASHES`], pair by pair.
const DASH_PAIRS: [(&str, &str); 5] = [("dash1", "gap1"), ("dash2", "gap2"), ("dash3", "gap3"), ("dash4", "gap4"), ("dash5", "gap5")];
/// Longest dash or gap, and the farthest offset (pt).
const MAX_DASH: f64 = 10_000.0;
/// Longest stretch [`EXTEND`] adds or takes off an end, in points and in percent of the path.
const MAX_EXTEND: f64 = 100_000.0;
const MAX_EXTEND_PERCENT: f64 = 1000.0;
/// Most anchors [`ADD_ANCHORS`] adds to one segment.
const MAX_PER_SEGMENT: f64 = 1000.0;
/// Closest and farthest apart [`ADD_ANCHORS`]' anchors are (pt).
const DISTANCE_RANGE: (f64, f64) = (0.01, 100_000.0);
/// The range of [`SMOOTH`]'s ratio.
const RATIO_RANGE: (f64, f64) = (0.01, 0.5);
/// Longest handle length [`RETRACT`] takes (pt).
const MAX_HANDLE: f64 = 100_000.0;
/// Highest tolerance of [`SIMPLIFY`].
const MAX_TOLERANCE: f64 = 200.0;
// shortcut: simplifying measures every anchor on every draw, so a larger path draws as it is; lift
// this if the kernel gets an incremental pass.
/// Most anchors [`SIMPLIFY`] takes in one path.
const MAX_SIMPLIFY_ANCHORS: usize = 50_000;
/// A path with a coordinate past this, or one that isn't finite, is left as it is: lengths measured
/// on it would overflow.
const MAX_COORDINATE: f64 = 1e12;
/// The effects' catalogue entries.
pub(crate) fn catalog() -> Vec<EffectInfo> {
let entry = |id, label, params, defaults, always| EffectInfo {
id,
label,
menu: MENU,
params,
defaults,
raster: false,
lengths: Lengths { always, absolute: &[] },
};
vec![
entry(
DASHES,
"Dashes to Geometry…",
"{dash1: pt 0..10000 (12), gap1: pt 0..10000 (6), dash2: pt 0..10000 (0), gap2: pt 0..10000 (0), dash3: pt 0..10000 (0), gap3: pt 0..10000 (0), dash4: pt 0..10000 (0), gap4: pt 0..10000 (0), dash5: pt 0..10000 (0), gap5: pt 0..10000 (0), offset: pt -10000..10000 (0; how far into the pattern the path starts; not with alignCorners), alignCorners: bool (false; every run between corners and path ends holds whole periods, stretched or squeezed to fit, with a dash centred on each corner and end)} cuts the path into its dashes, open subpaths along it that the stroke paints as it paints any path. A dash of 0 is a point its stroke's round or projecting cap paints; a pair of two zeros is left out, and the pattern repeats. A pattern of nothing, or of more than 200000 dashes, leaves the path as it is; a dash longer than a closed subpath keeps it closed",
json!({"dash1": 12.0, "gap1": 6.0, "dash2": 0.0, "gap2": 0.0, "dash3": 0.0, "gap3": 0.0, "dash4": 0.0, "gap4": 0.0, "dash5": 0.0, "gap5": 0.0, "offset": 0.0, "alignCorners": false}),
&["dash1", "gap1", "dash2", "gap2", "dash3", "gap3", "dash4", "gap4", "dash5", "gap5", "offset"],
),
entry(
ADD_ANCHORS,
"Add Anchors…",
"{target: \"all\"|\"curved\"|\"straight\" (all; the segments that get anchors), spacing: \"count\"|\"distance\" (count), count: 1..1000 (1; anchors on each segment, evenly spaced by length), distance: pt 0.01..100000 (20; an anchor every so far along each segment from its start), maxCount: 1..1000 (100; most anchors added to one segment)} adds anchors without changing the shape; past 2 million anchors in all the path stays as it is",
json!({"target": "all", "spacing": "count", "count": 1, "distance": 20.0, "maxCount": 100}),
&["distance"],
),
entry(
EXTEND,
"Extend Path…",
"{startLength: pt -100000..100000 (10), startPercent: % of the path's length -1000..1000 (0), startShape: \"straight\"|\"arc\" (straight), endLength: pt -100000..100000 (10), endPercent: % of the path's length -1000..1000 (0), endShape: \"straight\"|\"arc\" (straight)} lengthens each end of an open subpath by its length and percent together, or shortens it back along itself when they come to less than 0. Straight runs on along the end's direction; arc follows the circle of the end's curvature, at most half way round. Closed subpaths stay as they are, and so does an end that would be shortened to nothing",
json!({"startLength": 10.0, "startPercent": 0.0, "startShape": "straight", "endLength": 10.0, "endPercent": 0.0, "endShape": "straight"}),
&["startLength", "endLength"],
),
entry(
CLOSE,
"Close Path…",
"{mode: \"straight\"|\"smooth\" (straight; smooth: the closing segment leaves both ends smoothly)} closes every open subpath of two anchors or more",
json!({"mode": "straight"}),
&[],
),
entry(
SMOOTH,
"Smooth Anchors…",
"{ratio: 0.01..0.5 (0.3905; a handle's length as a share of the distance to the nearer neighbour; 0.3905 makes a square's corners a circle)} makes every anchor smooth: a lone handle is mirrored, two are brought into line keeping their lengths, and an anchor without handles gets them at right angles to the bisector of its neighbours",
json!({"ratio": SMOOTH_RATIO}),
&[],
),
entry(
RETRACT,
"Retract Handles…",
"{handles: \"all\"|\"shorter\" (all; shorter: only those shorter than length), length: pt 0..100000 (5)} takes the handles back to their anchors; an anchor that loses one becomes a corner",
json!({"handles": "all", "length": 5.0}),
&["length"],
),
entry(
REVERSE,
"Reverse Direction",
"{} runs every subpath the other way: the shape stays, and arrowheads, dashes and the effects after it swap ends",
json!({}),
&[],
),
entry(
SIMPLIFY,
"Simplify Anchors…",
"{tolerance: 0..200 (10; higher removes more anchors and lets the outline move further, up to tolerance × 0.02 pt), protectCorners: bool (true; anchors where the path turns by more than 30° stay)} removes the anchors a path can do without, refitting the handles beside each; open ends stay; a path of more than 50000 anchors stays as it is",
json!({"tolerance": 10.0, "protectCorners": true}),
&[],
),
entry(
SPLIT,
"Split at Anchors…",
"{anchors: \"corner\"|\"smooth\"|\"both\" (both; smooth: where the handles stand in line, corner: the others)} cuts subpaths into open pieces at those anchors; the shape stays, and an open path's ends aren't cuts",
json!({"anchors": "both"}),
&[],
),
]
}
/// Path Effect `id` with parameters `p` on `path`, which keeps to `max` anchors where anchors are
/// added one by one. `path` as it is when `id` is no such effect or the path can't be measured.
pub(crate) fn apply(id: &str, p: &Value, path: &PathData, max: usize) -> PathData {
if !measurable(path) {
return path.clone();
}
let edit = |change: &dyn Fn(&mut SubPath)| {
let mut out = path.clone();
out.subpaths.iter_mut().for_each(change);
out
};
match id {
DASHES => dashes(path, p),
ADD_ANCHORS => add_anchors(path, p, max).unwrap_or_else(|| path.clone()),
EXTEND => PathData::new(path.subpaths.iter().map(|sp| extend(sp, p)).collect()),
CLOSE => {
let mode = if text(p, "mode", "straight") == "smooth" { CloseMode::Smooth } else { CloseMode::Straight };
edit(&|sp| {
tools::close(sp, mode, SMOOTH_RATIO);
})
}
SMOOTH => {
let ratio = num(p, "ratio", SMOOTH_RATIO).clamp(RATIO_RANGE.0, RATIO_RANGE.1);
edit(&|sp| tools::smooth_anchors(sp, ratio))
}
RETRACT if text(p, "handles", "all") == "shorter" => {
let length = num(p, "length", 5.0).clamp(0.0, MAX_HANDLE);
edit(&|sp| {
retract_tiny_handles(sp, length);
})
}
RETRACT => edit(&|sp| sp.anchors.iter_mut().for_each(|a| a.retract())),
REVERSE => edit(&SubPath::reverse),
SIMPLIFY if path.anchor_count() <= MAX_SIMPLIFY_ANCHORS => {
let tolerance = num(p, "tolerance", 10.0).clamp(0.0, MAX_TOLERANCE) * PT_PER_TOLERANCE;
simplify_keep_shape(path, tolerance, flag(p, "protectCorners", true))
}
SPLIT => {
let at = text(p, "anchors", "both");
let (corners, smooth) = (at != "smooth", at != "corner");
PathData::new(path.subpaths.iter().flat_map(|sp| tools::split_at_anchors(sp, corners, smooth)).collect())
}
_ => path.clone(),
}
}
/// Is every coordinate of `path` within [`MAX_COORDINATE`]?
fn measurable(path: &PathData) -> bool {
let near = |q: Point| q.x.abs() <= MAX_COORDINATE && q.y.abs() <= MAX_COORDINATE;
path.anchors().all(|(_, _, a)| near(a.p) && near(a.h_in) && near(a.h_out))
}
/// [`DASHES`]: the dashes of `path` as open subpaths, those of no length as subpaths that stay on
/// their point; `path` as it is when the pattern draws no dashes.
fn dashes(path: &PathData, p: &Value) -> PathData {
let length = |key| num(p, key, 0.0).clamp(0.0, MAX_DASH);
let pairs = DASH_PAIRS.iter().map(|(dash, gap)| (length(dash), length(gap)));
let pattern = pairs.filter(|(d, g)| *d > 0.0 || *g > 0.0).flat_map(|(d, g)| [d, g]).collect();
let dash = Dash { pattern, offset: num(p, "offset", 0.0).clamp(-MAX_DASH, MAX_DASH), align_corners: flag(p, "alignCorners", false) };
let Some(dashed) = stroke::dash(&path.to_bezpath(), &dash) else { return path.clone() };
let mut out = PathData::from_bezpath(&dashed.path);
out.subpaths.extend(dashed.dots.iter().map(|d| SubPath::polyline(&[d.at, d.at], false)));
out
}
/// [`ADD_ANCHORS`] within `max` anchors in all; `None` past them.
fn add_anchors(path: &PathData, p: &Value, max: usize) -> Option<PathData> {
let which = match text(p, "target", "all") {
"curved" => SegmentKind::Curved,
"straight" => SegmentKind::Straight,
_ => SegmentKind::All,
};
let spacing = match text(p, "spacing", "count") {
"distance" => AnchorSpacing::Distance(num(p, "distance", 20.0).clamp(DISTANCE_RANGE.0, DISTANCE_RANGE.1)),
_ => AnchorSpacing::Count(num(p, "count", 1.0).clamp(1.0, MAX_PER_SEGMENT) as usize),
};
let cap = num(p, "maxCount", 100.0).clamp(1.0, MAX_PER_SEGMENT) as usize;
let mut room = max.saturating_sub(path.anchor_count());
let mut out = Vec::with_capacity(path.subpaths.len());
for sp in &path.subpaths {
let added = tools::add_anchors(sp, which, spacing, cap, room)?;
room = room.saturating_sub(added.anchors.len().saturating_sub(sp.anchors.len()));
out.push(added);
}
Some(PathData::new(out))
}
/// [`EXTEND`] on one subpath, the start then the end; what can't be done stays as it is.
fn extend(sp: &SubPath, p: &Value) -> SubPath {
let total = sp.anchor_arc_positions().last().copied().unwrap_or(0.0);
let by = |length, percent| {
num(p, length, 0.0).clamp(-MAX_EXTEND, MAX_EXTEND) + num(p, percent, 0.0).clamp(-MAX_EXTEND_PERCENT, MAX_EXTEND_PERCENT) / 100.0 * total
};
let shape = |key| if text(p, key, "straight") == "arc" { ExtendMode::Arc } else { ExtendMode::Straight };
let ends = [(true, by("startLength", "startPercent"), shape("startShape")), (false, by("endLength", "endPercent"), shape("endShape"))];
let mut out = sp.clone();
for (at_start, by, shape) in ends {
if by != 0.0
&& let Some(changed) = tools::extend_open(&out, at_start, by, shape)
{
out = changed;
}
}
out
}
#[cfg(test)]
mod tests;
+278
View File
@@ -0,0 +1,278 @@
use serde_json::{Value, json};
use vectorcraft_doc::Effect;
use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath};
use super::*;
use crate::{apply_geometry, effect_info, is_geometry, is_length, is_raster, length_range};
fn pt(x: f64, y: f64) -> Point {
Point::new(x, y)
}
fn line(pts: &[(f64, f64)], closed: bool) -> PathData {
PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| pt(x, y)).collect::<Vec<_>>(), closed))
}
fn square() -> PathData {
line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true)
}
/// A curve: a smooth anchor between two ends.
fn curve() -> PathData {
let mid = Anchor::smooth(pt(50.0, -30.0), pt(70.0, -30.0));
PathData::single(SubPath::new(
vec![
Anchor { h_out: pt(10.0, -20.0), ..Anchor::corner(pt(0.0, 0.0)) },
mid,
Anchor { h_in: pt(90.0, -20.0), ..Anchor::corner(pt(100.0, 0.0)) },
],
false,
))
}
fn run(id: &str, params: Value, path: &PathData) -> PathData {
let e = Effect { id: id.into(), params, visible: true };
apply_geometry(&[e], path, path.bounds().unwrap_or(Rect::ZERO))
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-3
}
const ALL: [&str; 9] = [DASHES, ADD_ANCHORS, EXTEND, CLOSE, SMOOTH, RETRACT, REVERSE, SIMPLIFY, SPLIT];
#[test]
fn the_effects_are_geometry_effects_of_the_path_effects_menu() {
for id in ALL {
let info = effect_info(id).unwrap();
assert!(is_geometry(id) && !is_raster(id), "{id}");
assert_eq!(info.menu, ["Effect", "Path Effects"], "{id}");
assert!(id.starts_with(PREFIX));
}
assert!(is_length(DASHES, "gap5", false) && is_length(EXTEND, "endLength", false) && !is_length(EXTEND, "endPercent", false));
assert_eq!(length_range(DASHES, "offset"), Some(-10_000.0..=10_000.0));
}
#[test]
fn dashes_become_open_subpaths_along_the_path() {
let out = run(DASHES, json!({"dash1": 10, "gap1": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false));
assert_eq!(out.subpaths.len(), 7, "periods of 15 on 100");
assert!(out.subpaths.iter().all(|s| !s.closed));
assert!(near(out.subpaths[1].anchors[0].p.x, 15.0) && near(out.subpaths[1].anchors[1].p.x, 25.0));
// Two pairs, and a pair of zeros between them left out.
let out = run(DASHES, json!({"dash1": 10, "gap1": 5, "dash3": 20, "gap3": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false));
assert!(near(out.subpaths[1].anchors[0].p.x, 15.0) && near(out.subpaths[1].anchors[1].p.x, 35.0));
assert!(near(out.subpaths[2].anchors[0].p.x, 40.0));
// The offset starts part way into the pattern.
let out = run(DASHES, json!({"dash1": 10, "gap1": 5, "offset": 5}), &line(&[(0.0, 0.0), (100.0, 0.0)], false));
assert!(near(out.subpaths[0].anchors[1].p.x, 5.0));
}
#[test]
fn aligned_dashes_centre_on_corners_and_ends() {
let open = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false);
let out = run(DASHES, json!({"dash1": 10, "gap1": 10, "alignCorners": true}), &open);
let on = |p: Point| out.subpaths.iter().any(|s| (0..s.segment_count()).any(|i| s.anchors[i].p == p || s.anchors[i + 1].p == p));
assert!(on(pt(0.0, 0.0)) && on(pt(100.0, 100.0)), "a dash on each end");
let corner = out.subpaths.iter().find(|s| s.anchors.iter().any(|a| a.p == pt(100.0, 0.0))).expect("a dash over the corner");
assert!(near(corner.anchors[0].p.distance(pt(100.0, 0.0)), corner.anchors[2].p.distance(pt(100.0, 0.0))), "centred: {corner:?}");
}
#[test]
fn zero_dashes_are_points_and_patterns_of_nothing_leave_the_path() {
let path = line(&[(0.0, 0.0), (100.0, 0.0)], false);
let dots = run(DASHES, json!({"dash1": 0, "gap1": 25}), &path);
assert_eq!(dots.subpaths.len(), 5);
assert!(dots.subpaths.iter().all(|s| s.anchors.len() == 2 && s.anchors[0].p == s.anchors[1].p));
for params in [
json!({"dash1": 0, "gap1": 0}),
json!({"dash1": -5, "gap1": -5}),
json!({"dash1": 0.0001, "gap1": 0.0001}),
json!({"dash1": "x", "gap1": null}),
] {
assert_eq!(run(DASHES, params.clone(), &path), path, "{params}");
}
}
#[test]
fn add_anchors_spaces_them_and_keeps_to_the_caps() {
let square = square();
assert_eq!(run(ADD_ANCHORS, json!({}), &square).anchor_count(), 8, "one on each segment");
assert_eq!(run(ADD_ANCHORS, json!({"count": 3}), &square).anchor_count(), 16);
assert_eq!(run(ADD_ANCHORS, json!({"count": 3, "maxCount": 2}), &square).anchor_count(), 12);
let out = run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 30}), &square);
assert_eq!(out.anchor_count(), 16, "at 30, 60 and 90 on each side");
assert!(near(out.subpaths[0].anchors[2].p.x, 60.0));
assert_eq!(run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 25}), &square).anchor_count(), 16, "none on the segment's end");
assert_eq!(run(ADD_ANCHORS, json!({"spacing": "distance", "distance": 1e-9, "maxCount": 2}), &square).anchor_count(), 12);
// Only the segments asked for.
let mixed = PathData::new(vec![curve().subpaths[0].clone(), square.subpaths[0].clone()]);
assert_eq!(run(ADD_ANCHORS, json!({"target": "curved"}), &mixed).anchor_count(), 7 + 2);
assert_eq!(run(ADD_ANCHORS, json!({"target": "straight"}), &mixed).anchor_count(), 7 + 4);
// The shape stays.
let out = run(ADD_ANCHORS, json!({"count": 4}), &curve());
assert_eq!(out.anchor_count(), 3 + 8);
assert!(near(out.length(), curve().length()));
assert_eq!(out.bounds().map(|b| (b.y0 * 100.0).round()), curve().bounds().map(|b| (b.y0 * 100.0).round()));
}
#[test]
fn add_anchors_past_the_budget_leaves_the_path() {
let path = square();
let most = json!({"count": 1000, "maxCount": 1000});
assert_eq!(super::apply(ADD_ANCHORS, &most, &path, 4003), path);
assert_eq!(super::apply(ADD_ANCHORS, &most, &path, 4004).anchor_count(), 4004);
// Many segments, each with the most anchors: refused before they are built.
let long = line(&(0..4000).map(|i| (i as f64, 0.0)).collect::<Vec<_>>(), false);
assert_eq!(run(ADD_ANCHORS, json!({"count": 1000, "maxCount": 1000}), &long).anchor_count(), 4000, "4 million would pass the budget");
}
#[test]
fn extend_lengthens_and_shortens_each_end() {
let path = line(&[(0.0, 0.0), (100.0, 0.0)], false);
let out = run(EXTEND, json!({"startLength": 20, "endLength": 10}), &path);
let xs: Vec<f64> = out.subpaths[0].anchors.iter().map(|a| a.p.x).collect();
assert_eq!(xs, [-20.0, 0.0, 100.0, 110.0]);
// Percent of the path's length, adding to the length; negative shortens.
let out = run(EXTEND, json!({"startLength": 0, "endLength": 5, "endPercent": 10}), &path);
assert!(out.subpaths[0].anchors.last().is_some_and(|a| near(a.p.x, 115.0)));
let out = run(EXTEND, json!({"startLength": -10, "endLength": 0, "endPercent": -50}), &path);
let xs: Vec<f64> = out.subpaths[0].anchors.iter().map(|a| a.p.x).collect();
assert!(near(xs[0], 10.0) && near(xs[1], 50.0), "{xs:?}");
// An arc carries on round the end's curve.
let arc = run(EXTEND, json!({"startLength": 0, "endLength": 40, "endShape": "arc"}), &curve());
let straight = run(EXTEND, json!({"startLength": 0, "endLength": 40}), &curve());
assert!(arc.anchor_count() >= straight.anchor_count());
assert!((arc.length() - straight.length()).abs() < 0.1);
assert_ne!(arc.subpaths[0].anchors.last().map(|a| a.p), straight.subpaths[0].anchors.last().map(|a| a.p));
}
#[test]
fn extend_leaves_what_it_cannot_change() {
let closed = square();
assert_eq!(run(EXTEND, json!({"endLength": 50}), &closed), closed);
let path = line(&[(0.0, 0.0), (100.0, 0.0)], false);
assert_eq!(run(EXTEND, json!({"startLength": 0, "endLength": -500}), &path), path, "nothing would be left");
assert_eq!(run(EXTEND, json!({"startLength": 0, "endLength": 0, "endPercent": -100}), &path), path);
let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], false));
assert_eq!(run(EXTEND, json!({}), &one), one);
}
#[test]
fn close_joins_open_subpaths_straight_or_smooth() {
let open = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false);
let out = run(CLOSE, json!({}), &open);
assert!(out.subpaths[0].closed && out.subpaths[0].segment_is_line(2));
let out = run(CLOSE, json!({"mode": "smooth"}), &open);
assert!(out.subpaths[0].closed && !out.subpaths[0].segment_is_line(2));
assert_eq!(run(CLOSE, json!({}), &square()), square());
let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], false));
assert_eq!(run(CLOSE, json!({}), &one), one);
}
#[test]
fn smooth_makes_a_square_round_and_clamps_its_ratio() {
let out = run(SMOOTH, json!({}), &square());
assert!(out.subpaths[0].anchors.iter().all(|a| near(a.h_out.distance(a.p), 39.05) && a.has_in()));
let at = |ratio: f64| run(SMOOTH, json!({ "ratio": ratio }), &square()).subpaths[0].anchors[0];
assert!(near(at(9.0).h_out.distance(pt(0.0, 0.0)), 50.0));
assert!(near(at(-9.0).h_out.distance(pt(0.0, 0.0)), 1.0));
}
#[test]
fn retract_takes_all_handles_or_the_short_ones() {
let out = run(RETRACT, json!({}), &curve());
assert!(out.subpaths[0].anchors.iter().all(|a| !a.has_in() && !a.has_out()));
// The ends' handles are about 22 pt long and the middle anchor's 20.
let out = run(RETRACT, json!({"handles": "shorter", "length": 21}), &curve());
let a = &out.subpaths[0].anchors;
assert!(!a[1].has_in() && !a[1].has_out() && a[0].has_out() && a[2].has_in());
assert_eq!(run(RETRACT, json!({"handles": "shorter", "length": 1}), &curve()), curve());
}
#[test]
fn reverse_runs_the_other_way_and_twice_is_as_it_was() {
let out = run(REVERSE, json!({}), &curve());
assert_eq!(out.subpaths[0].anchors[0].p, pt(100.0, 0.0));
assert_eq!(run(REVERSE, json!({}), &out), curve());
}
#[test]
fn simplify_takes_anchors_within_the_tolerance_and_stops_at_its_cap() {
let pts: Vec<(f64, f64)> = (0..=40).map(|i| (i as f64, (i as f64 / 40.0 * std::f64::consts::PI).sin() * 3.0)).collect();
let path = line(&pts, false);
let out = run(SIMPLIFY, json!({"tolerance": 200}), &path);
assert!(out.anchor_count() < 20, "{}", out.anchor_count());
assert_eq!(run(SIMPLIFY, json!({"tolerance": 0}), &path), path);
// Corners stay unless told otherwise.
let corner = line(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)], false);
assert_eq!(run(SIMPLIFY, json!({"tolerance": 200}), &corner), corner);
assert_eq!(run(SIMPLIFY, json!({"tolerance": 200, "protectCorners": false}), &corner).anchor_count(), 2);
let long = line(&(0..=MAX_SIMPLIFY_ANCHORS).map(|i| (i as f64, 0.0)).collect::<Vec<_>>(), false);
assert_eq!(run(SIMPLIFY, json!({}), &long).anchor_count(), long.anchor_count());
}
#[test]
fn split_cuts_at_the_anchors_asked_for() {
let mixed = PathData::single(SubPath::new(
vec![
Anchor::corner(pt(0.0, 0.0)),
Anchor::smooth(pt(50.0, 0.0), pt(60.0, 0.0)),
Anchor::corner(pt(100.0, 0.0)),
Anchor::corner(pt(100.0, 50.0)),
],
false,
));
assert_eq!(run(SPLIT, json!({}), &mixed).subpaths.len(), 3);
assert_eq!(run(SPLIT, json!({"anchors": "smooth"}), &mixed).subpaths.len(), 2);
assert_eq!(run(SPLIT, json!({"anchors": "corner"}), &mixed).subpaths.len(), 2);
let out = run(SPLIT, json!({}), &square());
assert_eq!(out.subpaths.len(), 4);
assert!(out.subpaths.iter().all(|s| !s.closed && s.anchors.len() == 2));
assert!(near(out.length(), 400.0));
assert_eq!(run(SPLIT, json!({"anchors": "smooth"}), &square()), square(), "no smooth anchors");
}
/// Whatever a file holds: every effect takes wrong types, huge numbers and paths of nothing, of one
/// anchor or past measuring, and keeps to the budget.
#[test]
fn junk_params_and_paths_are_harmless() {
let junk = [
json!({}),
json!(null),
json!([1, 2]),
json!("x"),
json!({"dash1": 1e308, "gap1": 1e308, "dash2": -1e308, "gap2": "x", "offset": 1e308, "alignCorners": "yes"}),
json!({"dash1": 1e-300, "gap1": 1e-300, "offset": -1e308, "alignCorners": true}),
json!({"target": 3, "spacing": ["distance"], "count": 1e308, "distance": 1e-308, "maxCount": -1e308}),
json!({"spacing": "distance", "distance": -1e308, "maxCount": 1e308}),
json!({"startLength": 1e308, "startPercent": 1e308, "startShape": 7, "endLength": -1e308, "endPercent": -1e308, "endShape": "arc"}),
json!({"mode": {}, "ratio": 1e308, "handles": "shorter", "length": 1e308, "tolerance": 1e308, "protectCorners": "no", "anchors": 9}),
json!({"ratio": -1e308, "length": -1e308, "tolerance": -1e308, "anchors": "none"}),
];
let far = line(&[(1e308, -1e308), (-1e308, 1e308), (1e300, 0.0)], false);
let nan = line(&[(f64::NAN, 0.0), (f64::INFINITY, 1.0)], false);
let tiny = line(&[(0.0, 0.0), (1e-300, 0.0), (1e-300, 1e-300)], true);
let same = line(&[(5.0, 5.0), (5.0, 5.0), (5.0, 5.0)], true);
let empty = PathData::single(SubPath::default());
let one = PathData::single(SubPath::polyline(&[pt(1.0, 1.0)], true));
let paths = [square(), curve(), far.clone(), nan.clone(), tiny, same, empty, one, PathData::default()];
for id in ALL {
for params in &junk {
for path in &paths {
let out = super::apply(id, &crate::merged_params(id, params), path, 100_000);
assert!(out.anchor_count() <= 100_000.max(path.anchor_count()) + 8 * path.subpaths.len(), "{id} {params}");
}
}
// Compared as text: NaN never equals itself.
assert_eq!(format!("{:?}", super::apply(id, &json!({}), &nan, 100)), format!("{nan:?}"), "{id}");
assert_eq!(super::apply(id, &json!({}), &far, 100), far, "{id}");
}
}
/// The dash generator's limit holds: a pattern too fine for the path leaves it solid.
#[test]
fn too_many_dashes_leave_the_path() {
let long = line(&[(0.0, 0.0), (1e9, 0.0)], false);
assert_eq!(run(DASHES, json!({"dash1": 1, "gap1": 1}), &long), long);
}
+1
View File
@@ -793,6 +793,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
}
v.extend(crate::addons::color::catalog());
v.extend(crate::addons::halftone::catalog());
v.extend(crate::addons::path::catalog());
v.push(g(TRAP, "Trap…", PATHFINDER, trap::EFFECT_PARAMS_DOC, trap::effect_defaults()));
v.push(g(
CROP_MARKS,
+1
View File
@@ -265,6 +265,7 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
"convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => stylize::convert_to_shape(id, b, p),
"stylize.roundCorners" => stylize::round_corners(path, num(p, "radius", 10.0)),
"stylize.scribble" => stylize::scribble(path, b, p),
_ if id.starts_with(crate::addons::path::PREFIX) => crate::addons::path::apply(id, p, path, max),
_ => match id.strip_prefix("warp.").and_then(WarpStyle::from_id) {
Some(style) => warp::warp(path, b, style, p, max),
None => path.clone(),
+9 -6
View File
@@ -1,10 +1,12 @@
//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path
//! Pieces. Its panel and its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's.
//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork
//! Cleanup, are the UI's.
mod checks;
#[cfg(test)]
mod tests;
mod text;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
@@ -16,9 +18,8 @@ use super::super::edit::selected_roots;
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, switch_or, text_param};
use crate::{EngineError, Result, Session};
/// Simplify Anchors' tolerance by default, and the drift (pt) each step of it allows.
/// Simplify Anchors' tolerance by default.
const TOLERANCE: f64 = 20.0;
pub(super) const PT_PER_TOLERANCE: f64 = 0.02;
/// Rejoin Path Pieces' gap by default, and the widest (pt).
const GAP: f64 = 0.1;
const MAX_GAP: f64 = 6.0;
@@ -30,7 +31,7 @@ const FIX_ROUNDS: usize = 3;
const MAX_LISTED: usize = 1000;
pub fn specs() -> Vec<CommandSpec> {
vec![
let mut v = vec![
cmd!(
"addon.cleanup.simplify",
"Simplify Anchors (Keep Shape)…",
@@ -85,7 +86,9 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
rejoin
),
]
];
v.extend(text::specs());
v
}
/// The paths (not guides) under `roots`, compound path members included.
@@ -119,7 +122,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
let changed: Vec<(NodeId, PathData)> = paths
.iter()
.filter_map(|(id, path)| {
let np = po::simplify_keep_shape(path, tolerance * PT_PER_TOLERANCE, protect);
let np = po::simplify_keep_shape(path, tolerance * po::PT_PER_TOLERANCE, protect);
(np != **path).then_some((*id, np))
})
.collect();
@@ -0,0 +1,865 @@
//! Artwork Cleanup's text tools: Break Text into Lines / Paragraphs / Words / Glyphs, Combine Point
//! Text, Split Text at Cursor, Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset
//! Text Transform and Replace Missing Fonts. Each is one undo step. Pieces keep their characters'
//! styles and stay where the layout drew them: each is moved so the glyph of its first character
//! lands where it was.
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, ParaStyle, RubySpan, TextKind, TextObject};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::textedit::editing_range;
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{EngineError, Result, Session};
/// Most text objects one command takes.
const MAX_TEXTS: usize = 10_000;
/// Most pieces Break Text and Split Text at Cursor make at once.
const MAX_PIECES: usize = 20_000;
/// Most breaks Remove Line / Paragraph Breaks removes at once.
const MAX_BREAKS: usize = 200_000;
/// Most pieces Combine Point Text tries to join, counted over every try: past it, what it joined
/// so far is the result.
const MAX_JOIN_TRIES: usize = 200_000;
/// How far (pt) a glyph Combine Point Text sets may land from where it was.
const TOLERANCE: f64 = 0.01;
/// Combine Point Text: pieces whose baselines are within this many ems of each other share a line
/// (the difference becomes baseline shift); a gap wider than `MAX_GAP` ems, or an overlap of more
/// than `MAX_OVERLAP`, starts another object.
const SAME_LINE: f64 = 0.4;
const MAX_GAP: f64 = 10.0;
const MAX_OVERLAP: f64 = 1.0;
/// Tracking Combine Point Text may give a character (thousandths of an em).
const TRACKING: std::ops::RangeInclusive<f64> = -1000.0..=10000.0;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.cleanup.breakText",
"Break Text",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}",
has_selection,
break_text
),
cmd!(
"addon.cleanup.combineText",
"Combine Point Text",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}",
has_selection,
combine_text
),
cmd!(
"addon.cleanup.removeBreaks",
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}",
has_selection,
remove_breaks
),
cmd!(
"addon.cleanup.splitText",
"Split Text at Cursor",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{} while a Type tool edits horizontal point or area type: the text before the selected characters, they and the text after become point type objects of their own (at a cursor: before and after it), each where its characters were, as one undo step; spaces at the ends of each piece go, and editing ends with the pieces selected → {ids}",
editing_text,
split_text
),
cmd!(
"addon.cleanup.alignInPlace",
"Set Alignment, Keep Position",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}",
has_selection,
align_in_place
),
cmd!(
"addon.cleanup.resetTextTransform",
"Reset Text Transform",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}",
has_selection,
reset_transform
),
cmd!(
"addon.cleanup.replaceFonts",
"Replace Missing Fonts…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
has_doc,
replace_fonts
),
]
}
/// Enabled while a Type tool edits text.
fn editing_text(s: &Session) -> std::result::Result<(), String> {
match s.tool_options().get("editing") {
Some(v) if !v.is_null() => Ok(()),
_ => Err("Click in type with a Type tool to split it".into()),
}
}
/// The type objects under `roots` (inside groups and layers, not live art) that can be edited.
fn texts_under(d: &Document, roots: &[NodeId]) -> Result<Vec<NodeId>> {
fn visit(n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Text(_) => out.push(n.id),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)),
_ => {}
}
}
let mut out = vec![];
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
let editable = d.editable();
out.retain(|id| editable(*id));
out.dedup();
if out.len() > MAX_TEXTS {
return Err(EngineError::Other("Too many type objects to change at once".into()));
}
Ok(out)
}
fn text_of(d: &Document, id: NodeId) -> Option<&TextObject> {
match &d.node(id)?.kind {
NodeKind::Text(t) => Some(t),
_ => None,
}
}
fn layout(t: &TextObject) -> TextLayout {
vectorcraft_text::layout(FontDb::global(), t)
}
/// Where the layout draws the character at `byte` (the one it starts in): its glyph's pen position.
fn glyph_at(lay: &TextLayout, byte: usize) -> Option<Point> {
let start = lay.glyphs.iter().filter(|g| g.len > 0 && g.byte <= byte).map(|g| g.byte).max()?;
lay.glyphs.iter().find(|g| g.len > 0 && g.byte == start).map(|g| g.origin)
}
/// The pen position of the glyph that starts at `byte`, if one does.
fn glyph_starting(lay: &TextLayout, byte: usize) -> Option<Point> {
lay.glyphs.iter().find(|g| g.len > 0 && g.byte == byte).map(|g| g.origin)
}
/// The first glyph of line `l`, in text order.
fn line_start(lay: &TextLayout, l: usize) -> Option<Point> {
let line = lay.lines.get(l)?;
let g = lay.glyphs.get(line.glyph_start..line.glyph_end)?.iter().filter(|g| g.len > 0).min_by_key(|g| g.byte)?;
Some(g.origin)
}
/// `a..b` of `text` without the white space at its ends; None when nothing else is left.
fn trimmed(text: &str, a: usize, b: usize) -> Option<(usize, usize)> {
let s = text.get(a..b)?;
let start = a + (s.len() - s.trim_start().len());
let end = a + s.trim_end().len();
(start < end).then_some((start, end))
}
/// Paragraph alignment as point type keeps it: justified lines align to their side.
fn point_justify(j: Justify) -> Justify {
match j {
Justify::JustifyLeft | Justify::JustifyAll => Justify::Left,
Justify::JustifyCenter => Justify::Center,
Justify::JustifyRight => Justify::Right,
j => j,
}
}
#[derive(Clone, Copy, PartialEq)]
enum By {
Lines,
Paragraphs,
Words,
Glyphs,
}
/// A type object being cut into point type pieces: its text as drawn (Shrink Text to Fit's sizes
/// taken in) and its layout.
struct Source {
t: TextObject,
lay: TextLayout,
text: String,
}
impl Source {
/// Horizontal point or area type that isn't threaded and whose text all fits; None otherwise.
fn of(d: &Document, id: NodeId) -> Option<Self> {
let t = text_of(d, id)?;
if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || d.text_threads.iter().any(|th| th.contains(&id)) {
return None;
}
let lay = layout(t);
// Text left out of a frame would be lost with it.
if lay.overflow {
return None;
}
let t = if (lay.fit_scale - 1.0).abs() > 1e-9 { vectorcraft_text::scaled(t, lay.fit_scale) } else { t.clone() };
Some(Self { text: t.plain_text(), t, lay })
}
/// The byte ranges of the pieces `by` cuts the text into.
fn ranges(&self, by: By) -> Vec<(usize, usize)> {
let text = &self.text;
match by {
By::Paragraphs => {
let mut out = vec![];
let mut a = 0;
for (i, _) in text.match_indices('\n') {
out.push((a, i));
a = i + 1;
}
out.push((a, text.len()));
out
}
By::Lines => self.lay.lines.iter().map(|l| (l.start, l.end)).collect(),
By::Words => {
let mut out = vec![];
for l in &self.lay.lines {
let Some(s) = text.get(l.start..l.end) else { continue };
let mut word: Option<usize> = None;
for (i, c) in s.char_indices() {
match (c.is_whitespace(), word) {
(true, Some(w)) => {
out.push((l.start + w, l.start + i));
word = None;
}
(false, None) => word = Some(i),
_ => {}
}
}
if let Some(w) = word {
out.push((l.start + w, l.end));
}
}
out
}
By::Glyphs => {
// One piece per cluster (a ligature's characters stay together).
let mut clusters = std::collections::BTreeMap::new();
for g in self.lay.glyphs.iter().filter(|g| g.len > 0) {
let end = clusters.entry(g.byte).or_insert(g.byte + g.len);
*end = (*end).max(g.byte + g.len);
}
clusters.into_iter().collect()
}
}
}
/// Point type holding bytes `a..b` (white space at its ends left out) where they were drawn.
/// Lines the layout wrapped end in a forced line break; `lists` keeps bulleted paragraphs'
/// bullets where the piece starts its paragraph.
fn piece(&self, (a, b): (usize, usize), lists: bool) -> Option<TextObject> {
let (a, b) = trimmed(&self.text, a, b)?;
let mut p = TextObject::point(Point::ZERO, "", CharStyle::default());
p.runs = edit::slice_runs(&self.t.runs, a, b);
p.xf = self.t.xf;
p.optical_margin = self.t.optical_margin;
p.system_layout = self.t.system_layout;
p.fractional_widths = self.t.fractional_widths;
p.ruby =
self.t.ruby.iter().filter(|r| a <= r.start && r.end <= b).map(|r| RubySpan { start: r.start - a, end: r.end - a, ..r.clone() }).collect();
// The paragraphs it holds, with their styles; the first keeps its bullet only from its start.
let starts_para = self.text.get(..a).is_some_and(|s| s.rsplit('\n').next().is_some_and(|line| line.trim().is_empty()));
let styles = self.t.paragraph_styles();
let mut paras: Vec<ParaStyle> = styles.get(self.t.paragraphs_in(a, b))?.to_vec();
for (i, para) in paras.iter_mut().enumerate() {
para.justify = point_justify(para.justify);
if !(lists && (i > 0 || starts_para) && para.list.as_ref().is_some_and(|l| l.number.is_none())) {
para.list = None;
}
}
p.set_paragraph_styles(paras);
// Lines the layout wrapped end in a forced line break, in place of the spaces they ended in.
let mut wraps = vec![];
for next in self.lay.lines.iter().skip(1).filter(|l| a < l.start && l.start < b) {
let content = self.text.get(..next.start)?.trim_end_matches([' ', '\t']);
// A line that ends in a break of its own keeps it.
if !content.ends_with(['\n', '\u{2028}']) {
wraps.push((content.len().max(a) - a, next.start - a));
}
}
for &(s, e) in wraps.iter().rev() {
edit::replace_range(&mut p.runs, s, e, "\u{2028}");
p.ruby_after_replace(s, e, '\u{2028}'.len_utf8());
}
self.place(&mut p, a)?;
Some(p)
}
/// Move `p` (cut from byte `a`) so the glyph of its first character lands where it was drawn.
/// A piece of several lines that starts inside a left-aligned line takes a first-line indent,
/// so its later lines stay where they were too.
fn place(&self, p: &mut TextObject, a: usize) -> Option<()> {
let lay = layout(p);
let mut shift: Vec2 = glyph_at(&self.lay, a)? - glyph_at(&lay, 0)?;
let first = self.lay.lines.iter().rposition(|l| l.start <= a);
if let (Some(now), Some(was)) = (line_start(&lay, 1), first.and_then(|l| line_start(&self.lay, l + 1))) {
let off = was.x - (now.x + shift.x);
let left = match p.para.justify {
Justify::Left => true,
Justify::Auto => lay.lines.first().is_some_and(|l| !l.rtl),
_ => false,
};
if left && off.abs() > 1e-6 {
p.edit_paras(Some(0..1), |para| para.first_line_indent -= off);
shift.x += off;
}
}
p.xf = self.t.xf * Affine::translate(shift);
Some(())
}
}
/// Put each object of `items` (id, the node, its pieces) out of the document, its pieces in its
/// place, as one undo step labelled `label`, the pieces selected → their ids.
fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, Vec<TextObject>)>) -> Result<Vec<u64>> {
s.edit(label, |d, sel| {
let (mut made, mut places) = (vec![], vec![]);
for (id, mut node, pieces) in items {
// A light template: the pieces take its paint and attributes, not its text.
node.kind = NodeKind::Text(Box::new(TextObject::point(Point::ZERO, "", CharStyle::default())));
let nodes: Vec<Node> = pieces
.into_iter()
.map(|mut t| {
refresh_bounds(&mut t);
let mut n = d.reid(&node);
n.kind = NodeKind::Text(Box::new(t));
n
})
.collect();
made.extend(nodes.iter().map(|n| n.id));
places.push((id, nodes));
}
d.insert_beside(places, true)?;
sel.set(made.iter().copied());
Ok(made.iter().map(|i| i.0).collect())
})
}
fn ids_json(ids: &[NodeId]) -> Vec<u64> {
ids.iter().map(|i| i.0).collect()
}
fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.breakText";
let by = match text_param(p, "by", C)?.unwrap_or("lines") {
"lines" => By::Lines,
"paragraphs" => By::Paragraphs,
"words" => By::Words,
"glyphs" => By::Glyphs,
other => return Err(bad(C, format!("`by` must be lines, paragraphs, words or glyphs, not {other:?}"))),
};
let d = &s.doc()?.doc;
let (mut items, mut skipped, mut count) = (vec![], vec![], 0);
for id in texts_under(d, &checked_ids_or_selection(s, p, C)?)? {
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id)) else {
skipped.push(id);
continue;
};
let ranges = src.ranges(by);
count += ranges.len();
if count > MAX_PIECES {
return Err(EngineError::Other("Too many pieces to make at once".into()));
}
let pieces: Vec<TextObject> = ranges.into_iter().filter_map(|r| src.piece(r, by == By::Paragraphs)).collect();
if pieces.is_empty() {
skipped.push(id);
} else {
items.push((id, node.clone(), pieces));
}
}
if items.is_empty() {
return Err(EngineError::Other("Select horizontal point or area type whose text fits".into()));
}
let ids = replace_with_pieces(s, "Break Text", items)?;
Ok(json!({ "ids": ids, "skipped": ids_json(&skipped) }))
}
fn split_text(s: &mut Session, _: &Value) -> Result<Value> {
let Some((id, a, b)) = editing_range(s)? else {
return Err(EngineError::Other("Click in type with a Type tool to split it".into()));
};
let d = &s.doc()?.doc;
let (Some(src), Some(node)) = (Source::of(d, id), d.node(id).filter(|_| d.is_editable(id))) else {
return Err(EngineError::Other("Select horizontal point or area type whose text fits".into()));
};
let text = &src.text;
let (a, b) = (edit::floor_char(text, a.min(b)), edit::floor_char(text, a.max(b)));
let cuts: Vec<(usize, usize)> = if a == b { vec![(0, a), (a, text.len())] } else { vec![(0, a), (a, b), (b, text.len())] };
let pieces: Vec<TextObject> = cuts.into_iter().filter_map(|r| src.piece(r, true)).collect();
if pieces.len() < 2 {
return Err(EngineError::Other("Nothing to split at the cursor".into()));
}
let node = node.clone();
let ids = replace_with_pieces(s, "Split Text at Cursor", vec![(id, node, pieces)])?;
// The text edited is gone: the pieces stay selected.
s.set_tool_option("stopEditing", &Value::Bool(true));
Ok(json!({ "ids": ids }))
}
/// One piece of point type Combine Point Text takes: its text with its object's scale taken into
/// its characters, and where it starts and ends along its line in the frame of its turn and shear.
struct Piece {
id: NodeId,
t: TextObject,
/// The object's turn and shear (`xf` without its move).
turn: [f64; 4],
/// Where its first character's glyph starts on its baseline, in that frame.
at: Point,
/// Where its last glyph ends along the line, in that frame.
end: f64,
/// Its first character's size.
size: f64,
/// Each character's pen position from the first's (byte, x), as it lays out alone.
pens: Vec<(usize, f64)>,
}
impl Piece {
fn of(d: &Document, id: NodeId) -> Option<(Self, &Node)> {
let node = d.node(id)?;
let NodeKind::Text(t) = &node.kind else { return None };
let text = t.plain_text();
if t.vertical || !matches!(t.kind, TextKind::Point) || text.trim().is_empty() || text.contains(['\n', '\u{2028}']) {
return None;
}
let mut t = (**t).clone();
t.scale_text_attributes();
t.style_scale()?;
let lay = layout(&t);
let line = lay.lines.first().filter(|l| !l.rtl && lay.lines.len() == 1)?;
let first = glyph_at(&lay, 0)?;
// The first glyph of each cluster (a mark drawn over it shares its byte).
let mut seen = std::collections::HashSet::new();
let pens = lay.glyphs.iter().filter(|g| g.len > 0 && seen.insert(g.byte)).map(|g| (g.byte, g.origin.x - first.x)).collect();
let end = lay.glyphs.iter().map(|g| g.origin.x + g.advance).fold(first.x, f64::max) - first.x;
let [a, b, c, dd, _, _] = t.xf.as_coeffs();
let turn = Affine::new([a, b, c, dd, 0.0, 0.0]);
let at = turn.inverse() * (t.xf * Point::new(first.x, line.baseline));
let size = t.runs.first()?.style.size;
if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) {
return None;
}
Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node))
}
/// Whether `o` is turned and sheared alike.
fn turned_like(&self, o: &Piece) -> bool {
self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0))
}
}
/// Whether two objects look alike apart from their text (paint, opacity, blending, effects).
fn same_look(a: &Node, b: &Node) -> bool {
a.appearance == b.appearance
&& a.opacity == b.opacity
&& a.blend == b.blend
&& a.isolate == b.isolate
&& a.knockout == b.knockout
&& a.extras == b.extras
}
/// How wide a space of `style` is.
fn space_width(style: &CharStyle) -> f64 {
let probe = TextObject::point(Point::ZERO, " ", CharStyle { tracking: 0.0, ..style.clone() });
layout(&probe).glyphs.first().map_or(style.size * 0.25, |g| g.advance)
}
/// `chain` (pieces left to right on one line) as one point type object whose glyphs land where
/// theirs were, or the index of the first piece that can't join the ones before it so.
fn merge(chain: &[&Piece]) -> std::result::Result<TextObject, usize> {
let Some(first) = chain.first() else { return Err(0) };
let mut runs = vec![];
// Each piece's first byte, and the byte range of the character before it (whose tracking sets
// the gap).
let (mut starts, mut before) = (vec![], vec![]);
let mut text = String::new();
for (k, p) in chain.iter().enumerate() {
if let Some(prev) = k.checked_sub(1).and_then(|i| chain.get(i)) {
let starts_blank = p.t.plain_text().starts_with(char::is_whitespace);
let last = prev.t.runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default();
if !text.ends_with(char::is_whitespace) && !starts_blank && p.at.x - prev.end >= 0.5 * space_width(&last) {
runs.push(vectorcraft_doc::TextRun::new(" ", last));
text.push(' ');
}
let c = text.chars().next_back().map_or(1, char::len_utf8);
before.push((text.len() - c, text.len()));
}
starts.push(text.len());
// Baselines a little apart: the difference is baseline shift (up is positive).
let shift = first.at.y - p.at.y;
for r in &p.t.runs {
let mut r = r.clone();
r.style.baseline_shift += shift;
text.push_str(&r.text);
runs.push(r);
}
}
let mut m = first.t.clone();
m.set_all_paras(ParaStyle { justify: Justify::Left, ..first.t.para.clone() });
let [a, b, c, d] = first.turn;
let base = Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate(first.at.to_vec2());
m.xf = base;
m.runs = runs;
m.ruby.clear();
// Tracking after the character before each piece, until each lands where it was.
let targets: Vec<f64> = chain.iter().map(|p| p.at.x - first.at.x).collect();
let mut lay = layout(&m);
for _ in 0..4 {
// A piece whose first character joins the one before it (a ligature) can't keep its place.
let xs: Vec<f64> = match starts.iter().enumerate().map(|(k, b)| glyph_starting(&lay, *b).map(|g| g.x).ok_or(k)).collect() {
Ok(xs) => xs,
Err(k) => return Err(k.max(1)),
};
let x0 = xs.first().copied().unwrap_or(0.0);
let off: Vec<f64> = targets.iter().zip(&xs).map(|(t, x)| t - (x - x0)).collect();
if off.iter().all(|o| o.abs() <= TOLERANCE * 0.5) {
break;
}
// Moving piece k moves those after it as far.
for (k, w) in off.windows(2).enumerate() {
let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue };
if delta.abs() > 1e-9 {
edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0);
if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) {
return Err(k + 1);
}
}
}
lay = layout(&m);
}
// Every glyph where it was, within the tolerance; else the run ends before the piece that moved.
let x0 = glyph_starting(&lay, 0).map_or(0.0, |g| g.x);
for (k, p) in chain.iter().enumerate() {
let (Some(&start), Some(&target)) = (starts.get(k), targets.get(k)) else { return Err(k.max(1)) };
let moved = p.pens.iter().any(|(byte, x)| glyph_starting(&lay, start + byte).is_none_or(|g| (g.x - x0 - target - x).abs() > TOLERANCE));
if moved {
return Err(k.max(1));
}
}
m.xf = base * Affine::translate((-x0, 0.0));
Ok(m)
}
fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.combineText";
let d = &s.doc()?.doc;
let mut pieces: Vec<(Piece, &Node)> =
texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect();
// Lines: pieces turned alike and looking alike, by baseline, then left to right.
pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x)));
let mut lines: Vec<Vec<(&Piece, &Node)>> = vec![];
for (piece, node) in &pieces {
let fits = |l: &Vec<(&Piece, &Node)>| {
l.first()
.is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))
};
match lines.iter_mut().find(|l| fits(l)) {
Some(l) => l.push((piece, node)),
None => lines.push(vec![(piece, node)]),
}
}
// Runs along each line: a wide gap or an overlap starts another.
let mut chains: Vec<Vec<&Piece>> = vec![];
for mut l in lines {
l.sort_by(|x, y| x.0.at.x.total_cmp(&y.0.at.x));
let mut chain: Vec<&Piece> = vec![];
for (piece, _) in l {
if let Some(prev) = chain.last() {
let gap = piece.at.x - prev.end;
if gap > MAX_GAP * prev.size || gap < -MAX_OVERLAP * prev.size {
chains.push(std::mem::take(&mut chain));
}
}
chain.push(piece);
}
chains.push(chain);
}
// Each run as one object, or as several where a piece can't keep its place joined.
let mut made: Vec<(NodeId, TextObject, Vec<NodeId>)> = vec![];
let mut tries = 0;
'chains: for chain in chains {
let mut rest: &[&Piece] = &chain;
while rest.len() > 1 {
let mut upto = rest.len();
while let Some(part) = rest.get(..upto) {
tries += part.len();
if tries > MAX_JOIN_TRIES {
break 'chains;
}
match merge(part) {
Ok(m) => {
let gone = part.iter().skip(1).map(|p| p.id).collect();
if let Some(first) = part.first() {
made.push((first.id, m, gone));
}
break;
}
// A run of one stays as it is.
Err(k) if k <= 1 => {
upto = 1;
break;
}
Err(k) => upto = k,
}
}
rest = rest.get(upto.max(1)..).unwrap_or_default();
}
}
if made.is_empty() {
return Err(EngineError::Other("Select two or more one-line point type objects on one baseline to combine".into()));
}
let combined: usize = made.iter().map(|m| m.2.len()).sum();
let ids: Vec<u64> = made.iter().map(|m| m.0.0).collect();
s.edit("Combine Point Text", |d, sel| {
let mut gone = vec![];
for (id, mut t, others) in made {
refresh_bounds(&mut t);
if let Some(n) = d.node_mut(id) {
n.kind = NodeKind::Text(Box::new(t));
}
gone.extend(others);
}
d.remove_many(&gone)?;
sel.set(ids.iter().map(|i| NodeId(*i)));
Ok(())
})?;
Ok(json!({ "ids": ids, "combined": combined }))
}
/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many
/// went.
fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
let text = t.plain_text();
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
let Some(range) = text.get(a..b) else { return 0 };
let mut prev = text.get(..a).and_then(|s| s.chars().next_back());
let mut cuts = vec![];
for (i, c) in range.char_indices() {
let at = a + i;
if c != brk {
prev = Some(c);
continue;
}
// The next character left: past the breaks that go too.
let after = at + c.len_utf8();
let next = text.get(after..).and_then(|rest| rest.char_indices().find(|(j, n)| *n != brk || after + j >= b).map(|(_, n)| n));
let space = prev.is_some_and(|p| !p.is_whitespace()) && next.is_some_and(|n| !n.is_whitespace());
if space {
prev = Some(' ');
}
cuts.push((at, space));
}
for &(at, space) in cuts.iter().rev() {
let insert = if space { " " } else { "" };
let end = at + brk.len_utf8();
t.splice_paras(at, end, insert);
edit::replace_range(&mut t.runs, at, end, insert);
t.ruby_after_replace(at, end, insert.len());
}
cuts.len()
}
fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.removeBreaks";
let (brk, label, none) = match text_param(p, "kind", C)? {
Some("line") => ('\u{2028}', "Remove Line Breaks", "No line breaks to remove"),
Some("paragraph") => ('\n', "Remove Paragraph Breaks", "No paragraph breaks to remove"),
Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))),
None => return Err(bad(C, "missing `kind`")),
};
// The characters a Type tool has selected, else all the text of the selected type.
let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
let d = &s.doc()?.doc;
let targets: Vec<(NodeId, usize, usize)> = match editing {
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(),
None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(),
};
let count: usize = targets
.iter()
.filter_map(|(id, a, b)| {
let text = text_of(d, *id)?.plain_text();
let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b));
Some(text.get(a..b)?.matches(brk).count())
})
.sum();
if count == 0 {
return Err(EngineError::Other(none.into()));
}
if count > MAX_BREAKS {
return Err(EngineError::Other("Too many breaks to remove at once".into()));
}
let (removed, ids) = s.edit(label, |d, _| {
let (mut removed, mut ids) = (0, vec![]);
for (id, a, b) in targets {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
let n = strip_breaks(t, a, b, brk);
if n > 0 {
refresh_bounds(t);
removed += n;
ids.push(id.0);
}
}
Ok((removed, ids))
})?;
Ok(json!({ "ids": ids, "removed": removed }))
}
/// Horizontal point type among the objects `p` names.
fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids: Vec<NodeId> = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)?
.into_iter()
.filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point)))
.collect();
if ids.is_empty() {
return Err(EngineError::Other("Select point type".into()));
}
Ok(ids)
}
/// Replace the type objects of `changed` as one undo step labelled `label` → their ids.
fn set_texts(s: &mut Session, label: &str, changed: Vec<(NodeId, TextObject)>, reset_angle: bool) -> Result<Value> {
let ids: Vec<u64> = changed.iter().map(|c| c.0.0).collect();
s.edit(label, |d, _| {
for (id, mut t) in changed {
refresh_bounds(&mut t);
if let Some(n) = d.node_mut(id) {
n.kind = NodeKind::Text(Box::new(t));
if reset_angle {
n.bbox_angle = 0.0;
}
}
}
Ok(())
})?;
Ok(json!({ "ids": ids }))
}
fn align_in_place(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.alignInPlace";
let justify = match text_param(p, "align", C)? {
Some("left") => Justify::Left,
Some("center") => Justify::Center,
Some("right") => Justify::Right,
Some(other) => return Err(bad(C, format!("`align` must be \"left\", \"center\" or \"right\", not {other:?}"))),
None => return Err(bad(C, "missing `align`")),
};
let ids = point_texts(s, p, C)?;
let d = &s.doc()?.doc;
let mut changed = vec![];
for id in ids {
let Some(t) = text_of(d, id).filter(|t| !t.vertical && t.para_styles().any(|para| para.justify != justify)) else { continue };
let was = layout(t);
// The longest line stays where it is.
let Some((i, line)) = was.lines.iter().enumerate().max_by(|a, b| (a.1.x1 - a.1.x0).total_cmp(&(b.1.x1 - b.1.x0))) else { continue };
let mut n = t.clone();
n.edit_paras(None, |para| para.justify = justify);
let Some(now) = layout(&n).lines.get(i).map(|l| l.x0) else { continue };
n.xf *= Affine::translate((line.x0 - now, 0.0));
changed.push((id, n));
}
if changed.is_empty() {
return Err(EngineError::Other("The point type is aligned that way already".into()));
}
set_texts(s, "Set Alignment, Keep Position", changed, false)
}
fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.resetTextTransform";
let scale = switch_or(p, "scale", false, C)?;
let ids = point_texts(s, p, C)?;
let d = &s.doc()?.doc;
let mut changed = vec![];
for id in ids {
let Some(t) = text_of(d, id) else { continue };
let [a, b, c, dd, _, _] = t.xf.as_coeffs();
// The object's own axes: its width along its baseline, and its height square to it.
let (sx, det) = (a.hypot(b), a * dd - b * c);
if !(sx > 1e-12 && sx.is_finite() && det.is_finite() && det.abs() > 1e-12) {
continue;
}
let sy = det.abs() / sx;
let unscaled = |t: &TextObject| t.runs.iter().all(|r| r.style.h_scale == 100.0);
let upright = b.abs() <= 1e-9 * sx && c.abs() <= 1e-9 * sy && a > 0.0 && dd > 0.0;
if upright && (!scale || ((sx - sy).abs() <= 1e-9 * sy && unscaled(t))) {
continue;
}
let mut n = t.clone();
let w = if scale {
n.runs.iter_mut().for_each(|r| r.style.h_scale = 100.0);
sy
} else {
sx
};
// The centre of the text stays where it is.
let centre = t.xf * layout(t).bounds.center();
let turn = Affine::scale_non_uniform(w, sy);
let now = turn * layout(&n).bounds.center();
n.xf = Affine::translate(centre - now) * turn;
changed.push((id, n));
}
if changed.is_empty() {
return Err(EngineError::Other("The point type has no transform to reset".into()));
}
set_texts(s, "Reset Text Transform", changed, true)
}
fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.replaceFonts";
let default = CharStyle::default().font_family;
let wanted = text_param(p, "font", C)?.filter(|f| !f.trim().is_empty()).unwrap_or(&default);
let db = FontDb::global();
// Any name of the family is stored as its own name.
let family = match db.resolve(wanted, "Regular") {
Some((f, m)) if m != FontMatch::Missing => f.family.clone(),
_ => return Err(bad(C, "the replacement font is not available")),
};
let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing);
let d = &s.doc()?.doc;
let mut ids = vec![];
for l in &d.layers {
l.walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& t.runs.iter().any(|r| missing(&r.style))
{
ids.push(n.id);
}
});
}
if ids.is_empty() {
return Err(EngineError::Other("No fonts are missing".into()));
}
let runs = s.edit("Replace Missing Fonts", |d, _| {
let mut runs = 0;
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
for r in t.runs.iter_mut().filter(|r| missing(&r.style)) {
// The style the font has closest to the one the character had.
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
r.style.font_family = family.clone();
r.style.font_version = None;
r.style.font_axes.clear();
runs += 1;
}
edit::normalize(&mut t.runs);
refresh_bounds(t);
}
Ok(runs)
})?;
Ok(json!({ "runs": runs, "font": family }))
}
@@ -0,0 +1,307 @@
//! Artwork Cleanup's text tools: pieces stay where their glyphs were drawn and keep their styles,
//! each command is one undo step and refuses cleanly when there is nothing to do.
use serde_json::{Value, json};
use vectorcraft_doc::{Justify, NodeId, NodeKind, TextKind, TextObject};
use vectorcraft_geom::Point;
use crate::{EngineError, Session};
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn text(s: &mut Session, p: Value) -> NodeId {
NodeId(s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap())
}
fn obj(s: &Session, id: NodeId) -> TextObject {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
/// Each drawn character of `ids` (spaces left out) with where its glyph starts on the page, in
/// the order of the objects and their text.
fn glyphs(s: &Session, ids: &[NodeId]) -> Vec<(char, Point)> {
let mut out = vec![];
for id in ids {
let t = obj(s, *id);
let text = t.plain_text();
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let mut gs: Vec<_> = lay.glyphs.iter().filter(|g| g.len > 0).collect();
gs.sort_by_key(|g| g.byte);
gs.dedup_by_key(|g| g.byte);
for g in gs {
let c = text[g.byte..].chars().next().unwrap();
if !c.is_whitespace() {
out.push((c, t.xf * g.origin));
}
}
}
out
}
fn assert_same_places(was: &[(char, Point)], now: &[(char, Point)]) {
assert_eq!(was.iter().map(|g| g.0).collect::<String>(), now.iter().map(|g| g.0).collect::<String>());
for (a, b) in was.iter().zip(now) {
assert!((a.1 - b.1).hypot() < 0.02, "{:?} moved to {:?}", a, b);
}
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn doc_json(s: &Session) -> String {
serde_json::to_string(&s.doc().unwrap().doc.layers).unwrap()
}
fn other(r: Result<Value, EngineError>) -> String {
match r {
Err(EngineError::Other(m)) => m,
r => panic!("expected a refusal, got {r:?}"),
}
}
#[test]
fn break_into_words_keeps_places_styles_and_is_one_step() {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 100, "text": "Hello big World", "size": 24}));
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 9, "size": 36, "tracking": 50})).unwrap();
let rotated = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned words", "size": 18, "rotation": 30}));
let was = glyphs(&s, &[id, rotated]);
let before = doc_json(&s);
let steps = undo_steps(&s);
select(&mut s, &[id, rotated]);
let r = s.execute("addon.cleanup.breakText", &json!({"by": "words"})).unwrap();
let pieces = ids(&r);
assert_eq!(pieces.len(), 5);
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(s.doc().unwrap().selection.objects.len(), 5, "the pieces are selected");
let texts: Vec<String> = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect();
assert_eq!(texts, ["Hello", "big", "World", "Turned", "words"]);
assert_same_places(&was, &glyphs(&s, &pieces));
let big = obj(&s, pieces[1]);
assert!(matches!(big.kind, TextKind::Point));
assert_eq!((big.runs[0].style.size, big.runs[0].style.tracking), (36.0, 50.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc_json(&s), before);
}
#[test]
fn break_area_type_into_lines_paragraphs_and_glyphs() {
for (by, count) in [("lines", None), ("paragraphs", Some(2)), ("glyphs", None)] {
let mut s = session();
let id = text(
&mut s,
json!({"x": 40, "y": 40, "text": "A paragraph long enough to wrap in its frame\nSecond one", "size": 14, "area": {"width": 140, "height": 200}}),
);
let t = obj(&s, id);
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
assert!(lay.lines.len() >= 3, "the first paragraph wraps");
let was = glyphs(&s, &[id]);
select(&mut s, &[id]);
let r = s.execute("addon.cleanup.breakText", &json!({"by": by})).unwrap();
let pieces = ids(&r);
let want = count.unwrap_or(if by == "lines" { lay.lines.len() } else { was.len() });
assert_eq!(pieces.len(), want, "{by}");
assert_same_places(&was, &glyphs(&s, &pieces));
if by == "paragraphs" {
// The wrapped lines end in line breaks.
assert!(obj(&s, pieces[0]).plain_text().contains('\u{2028}'));
}
}
}
#[test]
fn break_text_refuses_what_it_cannot_break() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
assert!(other(s.execute("addon.cleanup.breakText", &json!({}))).contains("point or area type"));
let r = s.execute("addon.cleanup.breakText", &json!({"by": "sentences"}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
}
#[test]
fn combine_puts_glyph_pieces_back_together_where_they_were() {
let mut s = session();
let id = text(&mut s, json!({"x": 50, "y": 120, "text": "Water Lily", "size": 30}));
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 10, "fill": "#ff0000"})).unwrap();
let was = glyphs(&s, &[id]);
select(&mut s, &[id]);
let pieces = ids(&s.execute("addon.cleanup.breakText", &json!({"by": "glyphs"})).unwrap());
assert_eq!(pieces.len(), 9);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap();
assert_eq!(undo_steps(&s), steps + 1);
let made = ids(&r);
assert_eq!((made.len(), r["combined"].as_u64()), (1, Some(8)));
let t = obj(&s, made[0]);
assert_eq!(t.plain_text(), "Water Lily", "a space goes back between the words");
assert_same_places(&was, &glyphs(&s, &made));
let red = t.runs.iter().find(|r| r.text.contains('L')).unwrap();
assert_ne!(red.style.fill, t.runs[0].style.fill, "styles stay");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(pieces[1]).is_some(), "undo brings the pieces back");
}
#[test]
fn combine_joins_only_pieces_on_one_line_turned_alike() {
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
let c = text(&mut s, json!({"x": 50, "y": 200, "text": "Below", "size": 20}));
let d = text(&mut s, json!({"x": 300, "y": 100, "text": "Turned", "size": 20, "rotation": 45}));
let was = glyphs(&s, &[a, b]);
select(&mut s, &[a, b, c, d]);
let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap();
assert_eq!(ids(&r), [a]);
assert_eq!(obj(&s, a).plain_text(), "Left Right");
assert_same_places(&was, &glyphs(&s, &[a]));
let doc = &s.doc().unwrap().doc;
assert!(doc.node(b).is_none() && doc.node(c).is_some() && doc.node(d).is_some());
select(&mut s, &[c, d]);
assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine"));
}
#[test]
fn remove_line_and_paragraph_breaks() {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 60, "text": "one\u{2028}two \u{2028}three\nfour\n\nfive", "size": 12}));
select(&mut s, &[id]);
let before = doc_json(&s);
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"})).unwrap();
assert_eq!(r["removed"], 2);
assert_eq!(obj(&s, id).plain_text(), "one two three\nfour\n\nfive");
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(r["removed"], 3);
let t = obj(&s, id);
assert_eq!((t.plain_text().as_str(), t.paragraph_count()), ("one two three four five", 1));
assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"}))), "No line breaks to remove");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc_json(&s), before);
assert!(matches!(s.execute("addon.cleanup.removeBreaks", &json!({})), Err(EngineError::BadParams { .. })));
}
/// The Type tool editing `id` with bytes `anchor..caret` selected.
fn edit_text(s: &mut Session, id: NodeId, anchor: usize, caret: usize) {
s.select_tool("type", Default::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": id.0, "anchor": anchor, "caret": caret}));
}
#[test]
fn remove_breaks_in_the_characters_a_type_tool_selected() {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12}));
select(&mut s, &[id]);
edit_text(&mut s, id, 0, 2);
s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(obj(&s, id).plain_text(), "a b\nc");
}
#[test]
fn split_at_the_cursor_and_around_a_selection() {
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
let mut s = session();
let id = text(&mut s, json!({"x": 40, "y": 60, "text": "Split here please", "size": 20, "justify": "center"}));
let was = glyphs(&s, &[id]);
select(&mut s, &[id]);
let r = s.execute("addon.cleanup.splitText", &json!({}));
assert!(matches!(&r, Err(EngineError::Disabled(_, why)) if why.contains("Type tool")), "{r:?}");
edit_text(&mut s, id, anchor, caret);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.splitText", &json!({})).unwrap();
assert_eq!(undo_steps(&s), steps + 1);
let pieces = ids(&r);
let texts: Vec<String> = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect();
assert_eq!(texts, want);
assert_same_places(&was, &glyphs(&s, &pieces));
assert!(s.tool_options()["editing"].is_null(), "editing ends");
}
}
#[test]
fn split_keeps_the_later_lines_of_a_wrapped_piece() {
let mut s = session();
let id = text(
&mut s,
json!({"x": 40, "y": 40, "text": "First words then a long run of text that wraps in the frame", "size": 14, "area": {"width": 160, "height": 200}}),
);
let was = glyphs(&s, &[id]);
select(&mut s, &[id]);
edit_text(&mut s, id, 6, 6);
let pieces = ids(&s.execute("addon.cleanup.splitText", &json!({})).unwrap());
assert_eq!(pieces.len(), 2);
assert_same_places(&was, &glyphs(&s, &pieces));
}
#[test]
fn set_alignment_keeps_the_text_in_place() {
let mut s = session();
let id = text(&mut s, json!({"x": 100, "y": 60, "text": "Stay put", "size": 20}));
let multi = text(&mut s, json!({"x": 100, "y": 160, "text": "Short\u{2028}The longest line", "size": 20}));
let was = glyphs(&s, &[id]);
let longest: Vec<_> = glyphs(&s, &[multi]).into_iter().skip(5).collect();
select(&mut s, &[id, multi]);
for align in ["center", "right", "left"] {
s.execute("addon.cleanup.alignInPlace", &json!({"align": align})).unwrap();
assert_same_places(&was, &glyphs(&s, &[id]));
assert_same_places(&longest, &glyphs(&s, &[multi]).into_iter().skip(5).collect::<Vec<_>>());
}
assert_eq!(obj(&s, id).para.justify, Justify::Left);
assert!(other(s.execute("addon.cleanup.alignInPlace", &json!({"align": "left"}))).contains("already"));
assert!(matches!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "up"})), Err(EngineError::BadParams { .. })));
}
#[test]
fn reset_text_transform_takes_off_rotation_and_with_scale_the_horizontal_scale() {
let mut s = session();
let id = text(&mut s, json!({"x": 100, "y": 100, "text": "Tilted", "size": 20, "rotation": 30}));
s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 150})).unwrap();
let centre = |s: &Session| {
let t = obj(s, id);
t.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.center()
};
let was = centre(&s);
let size = obj(&s, id).effective_char_style(&obj(&s, id).runs[0].style).unwrap().size;
select(&mut s, &[id]);
s.execute("addon.cleanup.resetTextTransform", &json!({})).unwrap();
let t = obj(&s, id);
let [_, b, c, _, _, _] = t.xf.as_coeffs();
assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "{:?}", t.xf);
assert!((centre(&s) - was).hypot() < 1e-6);
assert!((t.effective_char_style(&t.runs[0].style).unwrap().size - size).abs() < 1e-6, "the size stays");
assert!(t.runs[0].style.h_scale > 100.0, "the horizontal scale stays");
assert!(other(s.execute("addon.cleanup.resetTextTransform", &json!({}))).contains("no transform"));
s.execute("addon.cleanup.resetTextTransform", &json!({"scale": true})).unwrap();
assert_eq!(obj(&s, id).runs[0].style.h_scale, 100.0);
}
#[test]
fn replace_missing_fonts_with_the_default_or_a_chosen_font() {
let mut s = session();
let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family", "style": "Bold"}));
let kept = text(&mut s, json!({"x": 40, "y": 120, "text": "Fine", "size": 20}));
let fine = obj(&s, kept);
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("Source Sans 3")));
let t = obj(&s, gone);
assert_eq!((t.runs[0].style.font_family.as_str(), t.runs[0].style.font_style.as_str()), ("Source Sans 3", "Bold"));
assert_eq!(obj(&s, kept), fine);
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
let r = s.execute("addon.cleanup.replaceFonts", &json!({"font": "No Such Font Family"}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
}
+68 -25
View File
@@ -1,10 +1,16 @@
//! Path Precision Tools (`addon.pathtools.*`), a built-in add-on: the Anchor Eraser Brush's stroke,
//! the Extend Path tool's extension, the Measure & Inspect tool's readouts, the Anchor Inspector's
//! anchor edits, Split / Add Points at Crossings and the Parametric Shape Tool's shapes ([`shape`]).
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), and the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
mod corners;
#[cfg(test)]
mod effect_tests;
mod shape;
mod shared_edge;
#[cfg(test)]
mod tests;
@@ -20,7 +26,6 @@ use super::super::pathops::Beside;
use super::super::{
CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, finite_numbers, has_doc, has_selection, number_or, switch_or, text_param,
};
use super::cleanup::PT_PER_TOLERANCE;
use crate::{EngineError, Result, Session};
/// The Anchor Eraser Brush's tolerance by default (the scale Simplify Anchors (Keep Shape) uses).
@@ -54,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Extend Path",
[],
None,
"{id, subpath?: index (0), end: \"start\"|\"end\", length?: pt (negative shortens; never all of it), to?: [x, y] (instead of length: the length that brings the end nearest this point), mode?: \"straight\"|\"bezier\" (stretch the last segment's curve, no anchor added)|\"arc\" (along the circle the end curves on, at most half way round) (\"straight\")} lengthen an open path at an end the way it runs there, or shorten it back along itself, as one undo step → {id, length (pt)}",
"{id, subpath?: index (0), end: \"start\"|\"end\", length?: pt (negative shortens; never all of it), to?: [x, y] (instead of length: the length that brings the end nearest this point), mode?: \"straight\"|\"bezier\" (stretch the last segment's curve, no anchor added)|\"arc\" (along the circle the end curves on, at most half way round) (\"straight\")} lengthen an open path at an end the way it runs there, or shorten it back along itself, as one undo step; with Keep Shared Points Together on, anchors coincident with an end that moves go with it → {id, length (pt)}",
has_doc,
extend
),
@@ -72,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Anchor",
[],
None,
"{x?, y?: pt (on the page), inLength?, outLength?: pt (0 retracts), inAngle?, outAngle?: degrees counter-clockwise} move the selected anchors (with their handles) and set their handles, as one undo step: direct-selected anchors, or every anchor of a path selected whole; a smooth anchor's other handle turns with the one set → {anchors}",
"{x?, y?: pt (on the page), inLength?, outLength?: pt (0 retracts), inAngle?, outAngle?: degrees counter-clockwise} move the selected anchors (with their handles) and set their handles, as one undo step: direct-selected anchors, or every anchor of a path selected whole; a smooth anchor's other handle turns with the one set; with Keep Shared Points Together on, anchors coincident with one that moves go with it → {anchors}",
has_selection,
set_anchor
),
@@ -139,8 +144,19 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
crossings
),
cmd!(
"addon.pathtools.slideAnchor",
"Slide Anchor Along Path",
[],
None,
"{id, subpath?: index (0), anchor: index, t: -0.98..0.98 (where to: positive, a curve parameter on the segment after the anchor; negative, back from the end of the one before)} move an anchor along its path, the segments beside it refitted so the outline stays, as one undo step; ends of open paths don't slide; with Keep Shared Points Together on, anchors coincident with it go with it → {id, strayed (pt)}",
has_doc,
slide_anchor
),
];
v.extend(shape::specs());
v.extend(corners::specs());
v.extend(shared_edge::specs());
v
}
@@ -244,7 +260,7 @@ fn erase(s: &mut Session, p: &Value) -> Result<Value> {
let ids = paths_under(d, &roots);
let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect();
check_size(paths.iter().map(|(_, p)| *p), C)?;
let tol = if ignore { f64::INFINITY } else { tolerance * PT_PER_TOLERANCE };
let tol = if ignore { f64::INFINITY } else { tolerance * po::PT_PER_TOLERANCE };
let mut removed = 0;
let mut changed = vec![];
for (id, path) in paths {
@@ -288,8 +304,8 @@ fn edit_whole(s: &mut Session, label: &str, changed: Vec<(NodeId, PathData)>) ->
// ---------- Extend Path ----------
/// The open subpath an `extend` request names: (path id, subpath index, its data).
fn open_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> {
/// The subpath a request names: (path id, subpath index, its data).
fn named_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> {
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?;
let si = usize_opt(p, "subpath", cmd)?.unwrap_or(0);
let d = &s.doc()?.doc;
@@ -298,15 +314,36 @@ fn open_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, Sub
}
let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?;
let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?;
if sp.closed || sp.anchors.len() < 2 {
return Err(bad(cmd, "the subpath has no ends to extend (it is closed or a single point)"));
}
Ok((id, si, sp.clone()))
}
/// Put `new` in place of the subpath `old` (from [`named_subpath`]) as one step labelled `label`
/// (none when it is the same), with what Keep Shared Points Together moves too; the path's direct
/// selection goes.
fn set_subpath(s: &mut Session, label: &str, (id, si, old): (NodeId, usize, SubPath), new: SubPath) -> Result<()> {
if new == old {
return Ok(());
}
let mut np = s.doc()?.doc.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?;
if let Some(slot) = np.subpaths.get_mut(si) {
*slot = new;
}
let shared = shared_edge::shared_points(s, [(id, &np)])?;
s.edit(label, |d, sel| {
sel.anchors.remove(&id);
sel.segments.remove(&id);
set_path(d, id, np);
shared_edge::move_shared(d, shared);
Ok(())
})
}
fn extend(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.extend";
let (id, si, sp) = open_subpath(s, p, C)?;
let (id, si, sp) = named_subpath(s, p, C)?;
if sp.closed || sp.anchors.len() < 2 {
return Err(bad(C, "the subpath has no ends to extend (it is closed or a single point)"));
}
let at_start = match text_param(p, "end", C)? {
Some("start") => true,
Some("end") => false,
@@ -328,22 +365,26 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`length` must be a number of at most 1000000 pt either way"));
}
let new = pt::extend_open(&sp, at_start, length, mode).ok_or_else(|| bad(C, "the path is too short to shorten that much"))?;
if new != sp {
s.edit("Extend Path", |d, sel| {
let n = d.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?;
let mut np = n;
if let Some(slot) = np.subpaths.get_mut(si) {
*slot = new;
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
set_path(d, id, np);
Ok(())
})?;
}
set_subpath(s, "Extend Path", (id, si, sp), new)?;
Ok(json!({ "id": id.0, "length": length }))
}
// ---------- Slide Anchor Along Path ----------
fn slide_anchor(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.slideAnchor";
let (id, si, sp) = named_subpath(s, p, C)?;
let anchor = usize_opt(p, "anchor", C)?.ok_or_else(|| bad(C, "give `anchor`, the index of the anchor to slide"))?;
let t = number_or(p, "t", f64::NAN, C)?;
if t.is_nan() || t.abs() > pt::MAX_SLIDE {
return Err(bad(C, "`t` must be a number from -0.98 to 0.98"));
}
let (new, strayed) =
pt::slide_anchor(&sp, anchor, t).ok_or_else(|| bad(C, "that anchor can't slide: an end of an open path has nowhere to go"))?;
set_subpath(s, "Slide Anchor Along Path", (id, si, sp), new)?;
Ok(json!({ "id": id.0, "strayed": strayed }))
}
// ---------- Measure & Inspect ----------
fn polar(h: Option<(f64, f64)>) -> Value {
@@ -355,7 +396,7 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
let (x, y) = (number_or(p, "x", f64::NAN, C)?, number_or(p, "y", f64::NAN, C)?);
let tolerance = number_or(p, "tolerance", 3.0, C)?;
if !(x.is_finite() && y.is_finite()) || !(tolerance >= 0.0 && tolerance.is_finite()) {
if !(x.is_finite() && y.is_finite() && tolerance >= 0.0 && tolerance.is_finite()) {
return Err(bad(C, "give `x` and `y` (and a `tolerance` of 0 or more)"));
}
let path = s.doc()?.doc.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?;
@@ -423,10 +464,12 @@ fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath
}
}
if !changed.is_empty() {
let shared = shared_edge::shared_points(s, changed.iter().map(|(id, np)| (*id, np)))?;
s.edit(label, |d, _| {
for (id, np) in changed {
set_path(d, id, np);
}
shared_edge::move_shared(d, shared);
Ok(())
})?;
}
@@ -0,0 +1,144 @@
//! The Corner Tool's commands: the app's Live Corners ([`LiveCorners`]) cut, resized and removed on
//! chosen anchors, each edit one undo step.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::{LiveCorners, NodeId, NodeKind};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_tools::addons::corner_tool::MAX_RADIUS;
use super::super::super::object::recut;
use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, number_or};
use super::{check_size, paths_under};
use crate::{Result, Session};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.pathtools.cornerSet",
"Set Corners",
[],
None,
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}",
has_doc,
corner_set
),
cmd!(
"addon.pathtools.cornerRemove",
"Remove Corners",
[],
None,
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors)} make those live corners sharp again, as one undo step → {ids, corners (how many)}",
has_doc,
corner_remove
),
]
}
/// The `anchors` of `p`.
fn anchors_param(p: &Value, cmd: &str) -> Result<Option<BTreeSet<usize>>> {
let Some(v) = p.get("anchors").filter(|v| !v.is_null()) else { return Ok(None) };
let list = v.as_array().ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {v}")))?;
list.iter()
.map(|k| {
k.as_u64()
.and_then(|k| usize::try_from(k).ok())
.ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {k}")))
})
.collect::<Result<_>>()
.map(Some)
}
/// The corners a request names: each path with the corners (anchor indices of its uncut outline).
fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
let shared = anchors_param(p, cmd)?;
// Each path with its own `anchors`, or sharing the request's.
let mut own: Vec<Option<BTreeSet<usize>>> = vec![];
let ids: Vec<NodeId> = match p.get("items").filter(|v| !v.is_null()) {
None => paths_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, cmd)?),
Some(Value::Array(items)) => {
let mut ids = vec![];
for it in items {
ids.push(checked_id(s, it.get("id").unwrap_or(&Value::Null), cmd)?);
own.push(anchors_param(it, cmd)?);
}
ids
}
Some(v) => return Err(bad(cmd, format!("`items` must be a list of {{id, anchors?}}, not {v}"))),
};
let st = s.doc()?;
let d = &st.doc;
check_size(ids.iter().filter_map(|id| d.node(*id)?.path_data()), cmd)?;
let editable = d.editable();
let mut out = vec![];
for (i, id) in ids.iter().enumerate() {
let Some(lc) = d.node(*id).filter(|_| editable(*id)).and_then(LiveCorners::of) else { continue };
let corners = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) {
Some(given) => {
let n = lc.base.anchor_count();
if let Some(past) = given.iter().find(|k| **k >= n) {
return Err(bad(cmd, format!("object {id} has {n} anchors, so no anchor {past}")));
}
given.iter().copied().filter(|k| lc.corner(*k).is_some()).collect()
}
None => st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)),
};
if !corners.is_empty() {
out.push((*id, corners));
}
}
if out.is_empty() {
return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner"));
}
Ok(out)
}
/// Cut `radius` and `kind` on `corners` as one step (none when they have them already).
fn edit_corners(s: &mut Session, label: &str, corners: Vec<(NodeId, BTreeSet<usize>)>, radius: f64, kind: Option<CornerKind>) -> Result<Value> {
let d = &s.doc()?.doc;
let same = corners.iter().all(|(id, picked)| {
d.node(*id)
.and_then(LiveCorners::of)
.is_some_and(|c| picked.iter().all(|k| (c.drawn_radius(*k) - radius).abs() < 1e-9 && kind.is_none_or(|kd| c.kind(*k) == kd)))
});
let out = json!({
"ids": corners.iter().map(|(id, _)| id.0).collect::<Vec<_>>(),
"corners": corners.iter().map(|(_, c)| c.len()).sum::<usize>(),
});
if !same {
s.edit(label, |d, sel| {
for (id, picked) in corners {
let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
// A cut changes the anchors, which is all a segment selection goes by.
sel.segments.remove(&id);
recut(path, live, sel.anchors.get_mut(&id), &picked, Some(radius), kind);
}
Ok(())
})?;
}
Ok(out)
}
fn corner_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.cornerSet";
let radius = number_or(p, "radius", f64::NAN, C)?;
if !(0.0..=MAX_RADIUS).contains(&radius) {
return Err(bad(C, "`radius` must be from 0 to 1000000 pt"));
}
let kind = p
.get("kind")
.filter(|v| !v.is_null())
.map(|v| {
serde_json::from_value::<CornerKind>(v.clone())
.map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}")))
})
.transpose()?;
let corners = named_corners(s, p, C)?;
edit_corners(s, "Set Corners", corners, radius, kind)
}
fn corner_remove(s: &mut Session, p: &Value) -> Result<Value> {
let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?;
edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round))
}
@@ -0,0 +1,186 @@
//! Path Effects (`addon.path.*`) through the session: live on the canvas, the document's path left
//! alone, and Expand Appearance and a save keeping what they draw.
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Effect, Node, NodeId};
use vectorcraft_geom::{BezPath, Rect};
use vectorcraft_render::Renderer;
use vectorcraft_render::effects::{GeomContext, apply_geometry_bez, effect_catalog, new_effect, preview, scale_effect};
use crate::Session;
/// A black 4 pt stroke along `anchors`, unfilled.
fn stroked(anchors: Value, closed: bool) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.set([id])).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
(s, id)
}
fn wave() -> (Session, NodeId) {
let anchors = json!([
{"x": 20, "y": 100},
{"x": 60, "y": 60, "in": [40, 60], "out": [80, 60]},
{"x": 100, "y": 100},
{"x": 140, "y": 140},
{"x": 180, "y": 100}
]);
stroked(anchors, false)
}
/// Every Path Effect, with parameters that change the wave.
fn effects() -> Vec<(&'static str, Value)> {
vec![
("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "dash2": 3, "gap2": 6})),
("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "alignCorners": true})),
("addon.path.addAnchors", json!({"count": 3})),
("addon.path.addAnchors", json!({"spacing": "distance", "distance": 15, "target": "curved"})),
("addon.path.extend", json!({"startLength": 10, "endPercent": 10, "endShape": "arc"})),
("addon.path.extend", json!({"startLength": -10, "endLength": -20})),
("addon.path.close", json!({})),
("addon.path.close", json!({"mode": "smooth"})),
("addon.path.smooth", json!({"ratio": 0.3})),
("addon.path.retract", json!({})),
("addon.path.reverse", json!({})),
("addon.path.simplify", json!({"tolerance": 200, "protectCorners": false})),
("addon.path.split", json!({"anchors": "both"})),
]
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn picture_of(d: &Document) -> Vec<u8> {
let r = Renderer::new().render_region(d, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true);
(0..200).flat_map(|y| (0..200).map(move |x| (x, y))).flat_map(|(x, y)| r.pixel(x, y)).collect()
}
fn picture(s: &Session) -> Vec<u8> {
picture_of(&s.doc().unwrap().doc)
}
/// The outline of `n`: its path, or those of the compound path it became.
fn outline(n: &Node) -> BezPath {
let mut out = n.path_data().map(|p| p.to_bezpath()).unwrap_or_default();
n.children().into_iter().flatten().for_each(|c| out.extend(outline(c)));
out
}
/// How many bytes of two pictures differ by more than antialiasing noise.
fn differing(a: &[u8], b: &[u8]) -> usize {
a.iter().zip(b).filter(|(x, y)| x.abs_diff(**y) > 8).count()
}
#[test]
fn a_path_effect_draws_live_and_leaves_the_document_path() {
let (mut s, id) = stroked(json!([{"x": 10, "y": 50}, {"x": 190, "y": 50}]), false);
let solid = picture(&s);
let path = node(&s, id).path_data().cloned();
s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 20, "gap1": 20}})).unwrap();
assert_eq!(node(&s, id).path_data().cloned(), path, "only the effect holds the geometry");
let dashed = picture(&s);
let at = |pic: &[u8], x: usize| pic[(50 * 200 + x) * 4];
assert!(at(&solid, 45) < 40 && at(&dashed, 45) > 200, "a gap: {}", at(&dashed, 45));
assert!(at(&dashed, 15) < 40, "a dash");
// Hiding it draws the path again.
s.execute("effect.setParams", &json!({"index": 0, "visible": false})).unwrap();
assert_eq!(picture(&s), solid);
}
#[test]
fn a_path_effect_moves_the_bounds_the_object_is_measured_by() {
let (mut s, id) = stroked(json!([{"x": 50, "y": 50}, {"x": 150, "y": 50}]), false);
s.execute("effect.apply", &json!({"effect": "addon.path.extend", "params": {"startLength": 0, "endLength": 30}})).unwrap();
let drawn = preview::bounds_of(&s.doc().unwrap().doc, &[id], true).unwrap();
assert!((drawn.x1 - 180.0).abs() < 3.0, "{drawn:?}");
let pic = picture(&s);
assert!(pic[(50 * 200 + 170) * 4] < 40, "and draws there");
}
#[test]
fn expand_appearance_writes_the_outline_the_effect_draws() {
for (effect, params) in effects() {
let (mut s, id) = wave();
s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
let n = node(&s, id);
let before = n.path_data().cloned().unwrap();
let live = apply_geometry_bez(&n.appearance.effects, &before.to_bezpath(), before.bounds().unwrap(), &GeomContext::of(&n));
let pic = picture(&s);
s.execute("effect.expandAppearance", &json!({})).unwrap();
let expanded = node(&s, id);
assert!(expanded.appearance.effects.is_empty(), "{effect} {params}");
let (out, want) = (outline(&expanded), live);
assert_eq!(out.elements().len(), want.elements().len(), "{effect} {params}");
for (a, b) in out.elements().iter().zip(want.elements()) {
assert!(a.is_finite() && format!("{a:.4?}") == format!("{b:.4?}"), "{effect} {params}: {a:?} {b:?}");
}
assert_eq!(differing(&pic, &picture(&s)), 0, "{effect} {params}");
}
}
#[test]
fn path_effects_round_trip_through_a_save_and_scale_their_distances() {
for (effect, params) in effects() {
let (mut s, id) = wave();
s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(restored.node(id).unwrap().appearance.effects, node(&s, id).appearance.effects, "{effect} {params}");
assert_eq!(picture_of(&restored), picture(&s), "{effect} {params}");
}
let mut e = new_effect("addon.path.dashes", &json!({"dash1": 10})).unwrap();
scale_effect(&mut e, 2.0);
assert_eq!((e.params["dash1"].as_f64(), e.params["gap1"].as_f64()), (Some(20.0), Some(12.0)));
}
#[test]
fn undo_takes_a_path_effect_off_in_one_step() {
let (mut s, id) = wave();
s.execute("effect.apply", &json!({"effect": "addon.path.reverse"})).unwrap();
assert_eq!(node(&s, id).appearance.effects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, id).appearance.effects.is_empty());
}
/// A file's effects skip the checks `effect.apply` makes: whatever they hold, the object draws and
/// expands.
#[test]
fn path_effects_with_junk_params_from_a_file_draw_and_expand() {
let junk = [
json!(null),
json!("x"),
json!({"dash1": 1e308, "gap1": -1e308, "offset": "x", "alignCorners": 3}),
json!({"count": 1e308, "maxCount": 1e308, "distance": -1e308, "spacing": "distance", "target": []}),
json!({"startLength": 1e308, "endPercent": -1e308, "endShape": {}, "mode": 1, "ratio": "x", "handles": "shorter", "length": 1e308}),
json!({"tolerance": 1e308, "protectCorners": "no", "anchors": null, "startPercent": 1e308, "startShape": "arc"}),
];
let ids = effect_catalog().into_iter().map(|e| e.id).filter(|id| id.starts_with("addon.path."));
let stack: Vec<Effect> =
ids.flat_map(|id| junk.iter().map(move |params| Effect { id: id.into(), params: params.clone(), visible: true })).collect();
let (mut s, id) = wave();
s.edit("Junk", |d, _| {
if let Some(n) = d.node_mut(id) {
n.appearance.effects = stack;
}
Ok(())
})
.unwrap();
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
picture_of(&vectorcraft_format::load(&saved).unwrap());
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert!(node(&s, id).appearance.effects.is_empty());
}
#[test]
fn exports_write_the_dashes_as_paths() {
let (mut s, _) = wave();
s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 10, "gap1": 10}})).unwrap();
let v = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
let moves = svg.iter().filter(|c| **c == b'M').count();
assert!(moves > 5, "the exported art holds the dashes: {moves}");
}
@@ -0,0 +1,164 @@
//! The Shared Edge Merge Tool's command and Keep Shared Points Together: with that option on, the
//! add-on's own commands that move an anchor (Slide Anchor Along Path, Extend Path, Set Anchor) take
//! the anchors coincident with it along.
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, Vec2};
use vectorcraft_pathops::addons::pathtools as pt;
use vectorcraft_tools::addons::shared_edge::{DIAMETER, DIAMETER_RANGE, ID};
use super::super::super::{CommandSpec, always, bad, checked_id, cmd, finite_numbers, has_doc, number_or, switch_or, text_param};
use super::{edit_whole, set_path};
use crate::{Result, Session};
#[cfg(test)]
mod tests;
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.pathtools.mergeEdge",
"Merge Shared Edge",
[],
None,
"{a, b: two path ids (they needn't be selected), at: [x, y] (where), diameter?: pt 0.25..200 (20; how near `at` the edge is looked for), tolerance?: pt 0..3 (0.002; how near two anchors count as coincident), follow?: \"average\" (half way between the two)|\"a\"|\"b\" (keep that path's outline), ends?: bool (false: true makes an end even where the paths could merge)} where the paths touch at two coincident anchors, one each side of `at`, replace the stretches between them with one shared edge; stretches much longer one than the other (by over 10%) or leaving an end at over 120° aren't merged. Otherwise make an end there: two near anchors meet, and an anchor only one path has there is matched by a new one on the other. Each path stays closed or open; one undo step → {a, b, made: \"edge\"|\"end\"|\"nothing\" (merged already)}",
has_doc,
merge_edge
),
cmd!(
"addon.pathtools.movePointsTogether",
"Keep Shared Points Together",
[],
None,
"{enabled?: bool (default: the opposite of now)} Keep Shared Points Together: whether anchors coincident (within the Shared Edge Merge Tool's `tolerance`) with one that Slide Anchor Along Path, Extend Path or Set Anchor moves move with it, on any editable path (the `together` option of tool `sharedEdge`, kept with the preferences; off by default) → {enabled}",
always,
move_points_together
),
]
}
/// A path a merge may edit.
fn merge_path<'a>(d: &'a Document, id: NodeId, cmd: &str) -> Result<&'a PathData> {
if !d.is_editable(id) {
return Err(bad(cmd, "the path is locked or hidden"));
}
match d.node(id).map(|n| &n.kind) {
Some(NodeKind::Path { path, guide: false, .. }) => Ok(path),
_ => Err(bad(cmd, "`a` and `b` must be two different paths")),
}
}
fn merge_edge(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.mergeEdge";
let a = checked_id(s, p.get("a").unwrap_or(&Value::Null), C)?;
let b = checked_id(s, p.get("b").unwrap_or(&Value::Null), C)?;
if a == b {
return Err(bad(C, "`a` and `b` must be two different paths"));
}
let [x, y] = p.get("at").and_then(finite_numbers::<2>).ok_or_else(|| bad(C, "`at` must be [x, y]"))?;
let at = Point::new(x, y);
let diameter = number_or(p, "diameter", DIAMETER, C)?;
if !(DIAMETER_RANGE.0..=DIAMETER_RANGE.1).contains(&diameter) {
return Err(bad(C, "`diameter` must be from 0.25 to 200 pt"));
}
let tolerance = number_or(p, "tolerance", pt::COINCIDENCE, C)?;
if !(0.0..=pt::MAX_COINCIDENCE).contains(&tolerance) {
return Err(bad(C, "`tolerance` must be from 0 to 3 pt"));
}
let follow = match text_param(p, "follow", C)? {
None => pt::Follow::Average,
Some(f) => pt::Follow::parse(f).ok_or_else(|| bad(C, "`follow` must be \"average\", \"a\" or \"b\""))?,
};
let ends = switch_or(p, "ends", false, C)?;
let d = &s.doc()?.doc;
let (pa, pb) = (merge_path(d, a, C)?, merge_path(d, b, C)?);
let radius = diameter / 2.0;
let edge = if ends { None } else { pt::stretches_at(pa, pb, at, radius, tolerance) };
let plan = edge.or_else(|| pt::ends_at(pa, pb, at, radius)).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?;
let (na, nb) = pt::apply_merge(pa, pb, &plan, follow).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?;
let changed: Vec<(NodeId, PathData)> =
[(a, pa, na), (b, pb, nb)].into_iter().filter(|(_, old, new)| *old != new).map(|(id, _, new)| (id, new)).collect();
let made = match plan {
_ if changed.is_empty() => "nothing",
pt::MergePlan::Edge { .. } => "edge",
pt::MergePlan::Ends { .. } => "end",
};
edit_whole(s, "Merge Shared Edge", changed)?;
Ok(json!({ "a": a.0, "b": b.0, "made": made }))
}
fn move_points_together(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.pathtools.movePointsTogether";
let now = s.tool_options_of(ID)["together"].as_bool().unwrap_or(false);
let enabled = switch_or(p, "enabled", !now, C)?;
s.set_tool_options(Some(ID), &Map::from_iter([("together".to_string(), json!(enabled))]));
Ok(json!({ "enabled": enabled }))
}
/// Anchors to move along with others: each with how far.
pub(super) type SharedPoints = Vec<(NodeId, AnchorRef, Vec2)>;
/// With Keep Shared Points Together on, the anchors of editable paths coincident with an anchor
/// that `changed` (paths in their new form) moves, and not moving themselves. Subpaths whose
/// anchors `changed` adds or removes move none: their anchors stay put.
pub(super) fn shared_points<'a>(s: &Session, changed: impl IntoIterator<Item = (NodeId, &'a PathData)>) -> Result<SharedPoints> {
let options = s.tool_options_of(ID);
if options["together"].as_bool() != Some(true) {
return Ok(vec![]);
}
let tol = options["tolerance"].as_f64().unwrap_or(pt::COINCIDENCE);
let d = &s.doc()?.doc;
let mut moved: BTreeSet<(NodeId, AnchorRef)> = BTreeSet::new();
let mut from: Vec<(Point, Vec2)> = vec![];
for (id, new) in changed {
let Some(old) = d.node(id).and_then(|n| n.path_data()) else { continue };
for (si, (o, n)) in old.subpaths.iter().zip(&new.subpaths).enumerate().filter(|(_, (o, n))| o.anchors.len() == n.anchors.len()) {
for (ai, (x, y)) in o.anchors.iter().zip(&n.anchors).enumerate().filter(|(_, (x, y))| x.p != y.p) {
moved.insert((id, (si, ai)));
from.push((x.p, y.p - x.p));
}
}
}
let mut out = vec![];
if from.is_empty() {
return Ok(out);
}
from.sort_by(|a, b| a.0.x.total_cmp(&b.0.x));
let editable = d.editable();
d.walk(|n| {
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
if !editable(n.id) {
return;
}
for (si, ai, a) in path.anchors() {
let start = from.partition_point(|(p, _)| p.x < a.p.x - tol);
let mut near = from.iter().skip(start).take_while(|(p, _)| p.x <= a.p.x + tol);
if let Some((_, by)) = near.find(|(p, _)| p.distance(a.p) <= tol)
&& !moved.contains(&(n.id, (si, ai)))
{
out.push((n.id, (si, ai), *by));
}
}
});
Ok(out)
}
/// Move the anchors [`shared_points`] found; what they are on stops being a live shape.
pub(super) fn move_shared(d: &mut Document, shared: SharedPoints) {
let mut by_path: BTreeMap<NodeId, Vec<(AnchorRef, Vec2)>> = BTreeMap::new();
for (id, at, by) in shared {
by_path.entry(id).or_default().push((at, by));
}
for (id, anchors) in by_path {
let Some(mut np) = d.node(id).and_then(|n| n.path_data()).cloned() else { continue };
for ((si, ai), by) in anchors {
if let Some(a) = np.anchor_mut(si, ai) {
a.translate(by);
}
}
set_path(d, id, np);
}
}
@@ -0,0 +1,204 @@
//! The Shared Edge Merge Tool's command and Keep Shared Points Together: one undo step each, bad
//! params refused, the tool's click through the session, and only the add-on's commands affected.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_geom::{PathData, Point};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
use crate::{Session, ViewInfo};
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId {
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap())
}
fn path(s: &Session, id: NodeId) -> PathData {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn points(s: &Session, id: NodeId) -> Vec<Point> {
path(s, id).anchors().map(|(_, _, a)| a.p).collect()
}
/// Two closed shapes with a bent edge each between (100, 100) and (200, 100).
fn shapes(s: &mut Session) -> (NodeId, NodeId) {
let a = line(s, &[(100.0, 100.0), (150.0, 104.0), (200.0, 100.0), (200.0, 50.0), (100.0, 50.0)], true);
let b = line(s, &[(200.0, 100.0), (150.0, 96.0), (100.0, 100.0), (100.0, 150.0), (200.0, 150.0)], true);
(a, b)
}
#[test]
fn merge_edge_replaces_both_stretches_as_one_undo_step() {
let mut s = session();
let (a, b) = shapes(&mut s);
s.execute("select.none", &json!({})).unwrap();
let (pa, pb) = (path(&s, a), path(&s, b));
let n = steps(&s);
let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap();
assert_eq!(r, json!({"a": a.0, "b": b.0, "made": "edge"}));
assert_eq!(steps(&s), n + 1);
assert!(path(&s, a).subpaths[0].closed && path(&s, b).subpaths[0].closed);
assert_eq!(points(&s, a)[..3], [Point::new(100.0, 100.0), Point::new(150.0, 100.0), Point::new(200.0, 100.0)]);
assert_eq!(points(&s, b)[..3], [Point::new(200.0, 100.0), Point::new(150.0, 100.0), Point::new(100.0, 100.0)]);
// Nothing left to do: no step.
let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap();
assert_eq!(r["made"], json!("nothing"));
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((path(&s, a), path(&s, b)), (pa, pb));
}
#[test]
fn merge_edge_follows_the_path_asked_and_makes_ends() {
let mut s = session();
let (a, b) = shapes(&mut s);
let pa = path(&s, a);
s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100], "follow": "a"})).unwrap();
assert_eq!(path(&s, a), pa);
assert_eq!(points(&s, b)[1], Point::new(150.0, 104.0));
// Ends asked for: the near anchors of two lines meet, one undo step.
let c = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)], false);
let d = line(&mut s, &[(54.0, 200.0), (90.0, 240.0)], false);
let n = steps(&s);
let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": c.0, "b": d.0, "at": [52, 200], "ends": true})).unwrap();
assert_eq!((r["made"].clone(), steps(&s)), (json!("end"), n + 1));
assert_eq!((points(&s, c)[1], points(&s, d)[0]), (Point::new(52.0, 200.0), Point::new(52.0, 200.0)));
}
#[test]
fn merge_edge_refuses_bad_params_and_locked_paths() {
let mut s = session();
let (a, b) = shapes(&mut s);
let (i, j) = (a.0, b.0);
let n = steps(&s);
for p in [
json!({}),
json!({"a": i, "b": i, "at": [125, 100]}),
json!({"a": i, "b": j}),
json!({"a": i, "b": j, "at": [1]}),
json!({"a": i, "b": j, "at": [1, "x"]}),
json!({"a": i, "b": j, "at": [125, 100], "diameter": 0.1}),
json!({"a": i, "b": j, "at": [125, 100], "diameter": 201}),
json!({"a": i, "b": j, "at": [125, 100], "tolerance": 3.5}),
json!({"a": i, "b": j, "at": [125, 100], "tolerance": -1}),
json!({"a": i, "b": j, "at": [125, 100], "follow": "up"}),
json!({"a": i, "b": j, "at": [125, 100], "ends": 1}),
json!({"a": i, "b": u64::MAX, "at": [125, 100]}),
json!({"a": i, "b": j, "at": [390, 290]}),
] {
assert!(s.execute("addon.pathtools.mergeEdge", &p).is_err(), "{p}");
}
assert_eq!(steps(&s), n);
s.execute("select.set", &json!({"ids": [i]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
assert!(s.execute("addon.pathtools.mergeEdge", &json!({"a": i, "b": j, "at": [125, 100]})).is_err());
}
#[test]
fn the_tool_merges_unselected_paths_on_a_click_with_shift_following_the_upper() {
let mut s = session();
let (lower, upper) = shapes(&mut s);
s.execute("select.none", &json!({})).unwrap();
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("sharedEdge", view).unwrap();
let keep = path(&s, upper);
let n = steps(&s);
let shifted = |kind| {
let mut e = PointerEvent::new(kind, 125.0, 100.0);
e.mods = Mods { shift: true, ..Mods::default() };
e
};
s.pointer(&shifted(PointerKind::Down), view).unwrap();
s.pointer(&shifted(PointerKind::Up), view).unwrap();
assert_eq!(steps(&s), n + 1);
assert_eq!(path(&s, upper), keep);
assert_eq!(points(&s, lower)[1], Point::new(150.0, 96.0));
}
#[test]
fn keep_shared_points_together_is_off_by_default_and_a_preference_of_the_tool() {
let mut s = session();
assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(false));
assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(), json!({"enabled": true}));
assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(true), "kept with another tool active");
assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({})).unwrap(), json!({"enabled": false}));
assert!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": 1})).is_err());
}
#[test]
fn a_slide_takes_coincident_anchors_along_in_one_step_when_the_option_is_on() {
let mut s = session();
let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false);
let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false);
let far = line(&mut s, &[(200.0, 101.0), (250.0, 200.0)], false);
let slide = json!({"id": a.0, "anchor": 1, "t": 0.5});
let n = steps(&s);
s.execute("addon.pathtools.slideAnchor", &slide).unwrap();
assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0), "off: it stays");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap();
s.execute("addon.pathtools.slideAnchor", &slide).unwrap();
assert_eq!(steps(&s), n + 1);
let moved = points(&s, a)[1];
assert!(moved.distance(Point::new(250.0, 100.0)) < 1e-6, "{moved:?}");
assert!(points(&s, b)[0].distance(moved) < 1e-9);
assert_eq!(points(&s, b)[1], Point::new(200.0, 200.0));
assert_eq!(points(&s, far)[0], Point::new(200.0, 101.0), "not coincident");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0));
// A wider coincidence reaches it, and a locked path stays.
s.set_tool_options(Some("sharedEdge"), &serde_json::Map::from_iter([("tolerance".to_string(), json!(2))]));
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("addon.pathtools.slideAnchor", &slide).unwrap();
assert!(points(&s, far)[0].distance(Point::new(250.0, 101.0)) < 1e-6);
assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0));
}
#[test]
fn set_anchor_and_extend_take_coincident_anchors_along_but_built_in_moves_do_not() {
let mut s = session();
let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0)], false);
let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false);
s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap();
// Set Anchor on one selected anchor.
s.select(|_, sel| {
sel.set([a]);
sel.anchors.insert(a, [(0, 1)].into_iter().collect());
})
.unwrap();
let n = steps(&s);
s.execute("addon.pathtools.setAnchor", &json!({"x": 220, "y": 90})).unwrap();
assert_eq!(steps(&s), n + 1);
assert_eq!(points(&s, b), [Point::new(220.0, 90.0), Point::new(200.0, 200.0)]);
// An edit that moves no anchor moves none.
s.execute("addon.pathtools.corner", &json!({})).unwrap();
assert_eq!(points(&s, b)[0], Point::new(220.0, 90.0));
// Extend Path moves an end only when it adds no anchor.
s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10, "mode": "bezier"})).unwrap();
let end = points(&s, a)[1];
assert!(points(&s, b)[0].distance(end) < 1e-9);
let end = points(&s, b)[0];
s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10})).unwrap();
assert_eq!(points(&s, a).len(), 3);
assert_eq!(points(&s, b)[0], end, "the end it left stays with what shares it");
// The app's own moves are untouched by the option.
s.select(|_, sel| {
sel.set([a]);
sel.anchors.insert(a, [(0, 1)].into_iter().collect());
})
.unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 5})).unwrap();
assert_eq!(points(&s, b)[0], end);
}
+219 -1
View File
@@ -4,7 +4,8 @@
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{LiveCorners, LiveShape, NodeId};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{AnchorKind, PathData, Point};
use vectorcraft_tools::{PointerEvent, PointerKind};
@@ -456,3 +457,220 @@ fn the_tool_draws_one_step_per_drag_and_arrows_change_the_count() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shape_of(&s, id).map(|s| s.width), Some(120.0));
}
// ---------- Corner Tool ----------
/// A square (100, 100)–(300, 300), plain and selected: anchors from the top left, clockwise.
fn square(s: &mut Session) -> NodeId {
let id = line(s, &[(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)], true);
select(s, &[id]);
id
}
fn live(s: &Session, id: NodeId) -> Option<LiveShape> {
s.doc().unwrap().doc.node(id).unwrap().live_shape().cloned()
}
fn drawn(s: &Session, id: NodeId, corner: usize) -> f64 {
LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(corner)
}
#[test]
fn corner_set_cuts_live_corners_as_one_undo_step() {
let mut s = session();
let id = square(&mut s);
let plain = path(&s, id);
let n = steps(&s);
// The selected path: all four.
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap();
assert_eq!(r, json!({"ids": [id.0], "corners": 4}));
assert_eq!((steps(&s), path(&s, id).anchor_count()), (n + 1, 8));
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).map(|c| (c.drawn_radius(3), c.kind(3))).unwrap();
assert_eq!(lc, (20.0, CornerKind::Chamfer));
// The same again changes nothing: no step.
s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap();
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((path(&s, id), live(&s, id)), (plain, None));
}
#[test]
fn corner_set_goes_by_anchors_the_selection_and_items_and_fits() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
// Named anchors, of each path by `items`, at once; an open end takes none.
let items = json!([{"id": id.0, "anchors": [1]}, {"id": other.0, "anchors": [0, 1]}]);
let n = steps(&s);
let r = s.execute("addon.pathtools.cornerSet", &json!({"items": items, "radius": 5})).unwrap();
assert_eq!((r["corners"].clone(), steps(&s)), (json!(2), n + 1));
assert_eq!((drawn(&s, id, 1), drawn(&s, id, 0), drawn(&s, other, 1)), (5.0, 0.0, 5.0));
// `ids` with `anchors`, keeping the kind each has.
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [1], "radius": 9})).unwrap();
assert_eq!(drawn(&s, id, 1), 9.0);
// Direct-selected anchors: only their corners, which stay selected as they gain anchors.
select_anchors(&mut s, id, &[0]);
s.execute("addon.pathtools.cornerSet", &json!({"radius": 7})).unwrap();
assert_eq!((drawn(&s, id, 0), drawn(&s, id, 2)), (7.0, 0.0));
let sel = s.doc().unwrap().selection.anchors[&id].clone();
let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
assert_eq!(c.corners_of(&sel), BTreeSet::from([0]));
// A radius that doesn't fit is drawn at what does.
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [2], "radius": 5000})).unwrap();
assert!(drawn(&s, id, 2) <= 200.0 - 7.0 + 1e-9, "{}", drawn(&s, id, 2));
}
#[test]
fn corner_remove_makes_corners_sharp_and_a_path_plain_again() {
let mut s = session();
let id = square(&mut s);
let plain = path(&s, id);
s.execute("addon.pathtools.cornerSet", &json!({"anchors": [0, 1], "radius": 10, "kind": "invertedRound"})).unwrap();
let n = steps(&s);
let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "anchors": [0]}]})).unwrap();
assert_eq!((r["corners"].clone(), steps(&s), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), n + 1, 0.0, 10.0));
s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap();
assert_eq!((steps(&s), path(&s, id), live(&s, id)), (n + 2, plain, None));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(drawn(&s, id, 1), 10.0);
}
#[test]
fn corner_commands_refuse_bad_params() {
let mut s = session();
let id = square(&mut s);
let smooth = circle(&mut s);
let i = id.0;
refuses(
&mut s,
"addon.pathtools.cornerSet",
&[
json!({"ids": [i]}),
json!({"ids": [i], "radius": -1}),
json!({"ids": [i], "radius": 1e308}),
json!({"ids": [i], "radius": "big"}),
json!({"ids": [i], "radius": 5, "kind": "spiky"}),
json!({"ids": [i], "anchors": "all", "radius": 5}),
json!({"ids": [i], "anchors": [-1], "radius": 5}),
json!({"ids": [i], "anchors": [9], "radius": 5}),
json!({"ids": [u64::MAX], "radius": 5}),
json!({"items": 3, "radius": 5}),
json!({"items": [{"anchors": [0]}], "radius": 5}),
json!({"ids": [smooth.0], "radius": 5}),
],
);
refuses(&mut s, "addon.pathtools.cornerRemove", &[json!({"anchors": [9], "ids": [i]}), json!({"ids": [smooth.0]})]);
// Locked: left alone.
s.execute("object.lock", &json!({"ids": [i]})).ok();
if !s.doc().unwrap().doc.is_editable(id) {
refuses(&mut s, "addon.pathtools.cornerSet", &[json!({"items": [{"id": i}], "radius": 5})]);
}
}
#[test]
fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() {
let mut s = session();
let id = square(&mut s);
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("cornerTool", view).unwrap();
s.set_tool_option("radius", &json!(15));
let n = steps(&s);
let press = |s: &mut Session, k, x, y| s.pointer(&PointerEvent::new(k, x, y), view).unwrap();
// A click on the top right anchor.
press(&mut s, PointerKind::Down, 300.0, 100.0);
press(&mut s, PointerKind::Up, 300.0, 100.0);
assert_eq!((steps(&s), drawn(&s, id, 1)), (n + 1, 15.0));
// A drag from the bottom right anchor, previewed, one step.
press(&mut s, PointerKind::Down, 300.0, 300.0);
press(&mut s, PointerKind::Drag, 280.0, 280.0);
assert_eq!(drawn(&s, id, 2), 20.0, "the preview shows");
press(&mut s, PointerKind::Drag, 270.0, 270.0);
press(&mut s, PointerKind::Up, 270.0, 270.0);
assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 2, 30.0));
// A drag on the marker resizes; a double-click on it removes.
press(&mut s, PointerKind::Down, 270.0, 270.0);
press(&mut s, PointerKind::Drag, 260.0, 260.0);
press(&mut s, PointerKind::Up, 260.0, 260.0);
assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 3, 40.0));
press(&mut s, PointerKind::DoubleClick, 260.0, 260.0);
assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 4, 0.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(drawn(&s, id, 2), 40.0);
// A click on a marker selects the corner and loads its values.
press(&mut s, PointerKind::Down, 285.0, 115.0);
press(&mut s, PointerKind::Up, 285.0, 115.0);
assert_eq!(steps(&s), n + 3, "selecting is no edit");
assert_eq!(s.doc().unwrap().selection.anchors.get(&id).map(|a| a.len()), Some(2));
// The bottom right one, resized by its marker, loads its radius.
press(&mut s, PointerKind::Down, 260.0, 260.0);
press(&mut s, PointerKind::Up, 260.0, 260.0);
assert_eq!(s.tool_options_of("cornerTool")["radius"], json!(40.0));
// An Alt-marquee over the left side: both anchors, in one step.
let alt = vectorcraft_tools::Mods { alt: true, ..Default::default() };
for (k, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 150.0, 350.0), (PointerKind::Up, 150.0, 350.0)] {
s.pointer(&PointerEvent::new(k, x, y).with_mods(alt), view).unwrap();
}
assert_eq!((steps(&s), drawn(&s, id, 0), drawn(&s, id, 3)), (n + 4, 40.0, 40.0));
}
// ---------- Slide Anchor Along Path ----------
#[test]
fn slide_anchor_moves_it_along_the_path_as_one_undo_step() {
let mut s = session();
let e = circle(&mut s);
let before = path(&s, e);
let area = kurbo::Shape::area(&before.to_bezpath()).abs();
let want = before.subpaths[0].segment(3);
let n = steps(&s);
let r = s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0.5})).unwrap();
assert!(r["strayed"].as_f64().unwrap() < 0.05, "{r}");
let after = path(&s, e);
assert_eq!((steps(&s), after.anchor_count()), (n + 1, 16));
assert!(after.subpaths[0].anchors[3].p.distance(kurbo::ParamCurve::eval(&want, 0.5)) < 1e-9);
assert!((kurbo::Shape::area(&after.to_bezpath()).abs() / area - 1.0).abs() < 1e-3);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(path(&s, e), before);
// No move, no step.
s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0})).unwrap();
assert_eq!(steps(&s), n);
}
#[test]
fn slide_anchor_refuses_bad_params() {
let mut s = session();
let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false);
let i = l.0;
refuses(
&mut s,
"addon.pathtools.slideAnchor",
&[
json!({"id": i, "anchor": 0, "t": 0.5}),
json!({"id": i, "anchor": 2, "t": -0.5}),
json!({"id": i, "anchor": 9, "t": 0.5}),
json!({"id": i, "anchor": 1, "t": 1.5}),
json!({"id": i, "anchor": 1}),
json!({"id": i, "t": 0.5}),
json!({"id": i, "subpath": 4, "anchor": 1, "t": 0.5}),
json!({"id": u64::MAX, "anchor": 1, "t": 0.5}),
],
);
}
#[test]
fn the_slide_tool_previews_and_commits_one_step() {
let mut s = session();
let l = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false);
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("slideAnchor", view).unwrap();
let n = steps(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 120.0), view).unwrap();
let at = |s: &Session| path(s, l).subpaths[0].anchors[1].p;
assert!(at(&s).distance(Point::new(250.0, 100.0)) < 1e-3, "the preview shows");
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), view).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), view).unwrap();
assert!(steps(&s) == n + 1 && at(&s).distance(Point::new(280.0, 100.0)) < 1e-3);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(at(&s), Point::new(200.0, 100.0));
}
+18 -6
View File
@@ -125,7 +125,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
has_doc,
copy_from
),
@@ -840,11 +840,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.copyFrom";
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?);
let defaults_only = switch_or(p, "defaultsOnly", false, C)?;
if defaults_only && (reverse || append || p.get("ids").is_some()) {
return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `reverse` or `append`"));
}
let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?;
let range = if !reverse && !append && p.get("ids").is_none() { super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { None };
let selected = match ids_param(p, "ids") {
Some(v) => outermost(&s.doc()?.doc, v),
None => selected_roots(s)?,
let range = if !defaults_only && !reverse && !append && p.get("ids").is_none() {
super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b)
} else {
None
};
let selected = if defaults_only {
vec![]
} else {
match ids_param(p, "ids") {
Some(v) => outermost(&s.doc()?.doc, v),
None => selected_roots(s)?,
}
};
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
// selected, what the Eyedropper picked up last does (#4382).
@@ -864,7 +876,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
};
let picked = Picked::of(&node);
if !reverse {
if !reverse && !defaults_only {
s.eyedropper_sample = Some(node);
}
let range = range.filter(|(id, _, _)| targets.contains(id));
+8 -16
View File
@@ -222,18 +222,16 @@ fn trace_params(s: &Session, c: &str, p: &Value) -> Result<tr::TraceParams> {
Ok(params)
}
/// Document swatch `w`'s solid color with the paint a trace fills with it: a global or spot color,
/// or a tint of one, linked to its swatch as `swatch_solid` (paint.rs) links it; any other color
/// unlinked. The color is the one the paint shows (a Lab spot color's CMYK equivalent when the Spot
/// Colors options use CMYK values).
/// Document swatch `w`'s displayed solid color and unlinked trace paint. A tint uses its tinted
/// color; a Lab spot color uses its CMYK equivalent when the Spot Colors options use CMYK values.
fn trace_swatch_paint(d: &Document, w: &Swatch) -> Option<(Color, Paint)> {
let linked = d.swatch_link(&w.name).and_then(|(base, tint)| d.tint_paint(&base, tint));
let color = linked.as_ref().and_then(Paint::color).or_else(|| w.paint.color())?;
Some((color, linked.unwrap_or_else(|| Paint::solid(color))))
Some((color, Paint::solid(color)))
}
/// Document Library with `colorGroup`: the solid colors of the active document's color group
/// `name` (so named exactly, else ignoring case), each with its paint ([`trace_swatch_paint`]).
/// `name` (so named exactly, else ignoring case), each with its unlinked paint ([`trace_swatch_paint`]).
/// Errors name command `c`. ([`trace_params`] has checked that the library is the document's
/// swatches.)
fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result<Vec<(Color, Paint)>> {
@@ -249,9 +247,7 @@ fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result<Vec<(Color, Pa
}
/// Document Library in Color mode: look the library's colors (or its color group's) up into
/// `params.swatches` → each one as traced (sRGB) with the paint to fill with. The document's
/// global and spot colors fill linked to their swatches ([`trace_swatch_paint`]); a swatch
/// library's colors fill unlinked. Errors name command `c`.
/// `params.swatches` → each one as traced (sRGB) with its unlinked paint. Errors name command `c`.
fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<Vec<([u8; 3], Paint)>> {
if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary {
return Ok(vec![]);
@@ -559,15 +555,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
let unit = xf.determinant().abs().sqrt();
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
// A library color fills with the swatch's own color (its model kept), linked to a
// global or spot swatch of the document. Of the swatches that trace as this color,
// the first linked one is taken, else the first. Build the lookup once per trace.
// A library color fills with the swatch's displayed color (its model kept), unlinked.
// Keep the first swatch that traces as a given color. Build the lookup once per trace.
let mut by_color: HashMap<[u8; 3], &Paint> = HashMap::new();
for (rgb, paint) in &library {
let chosen = by_color.entry(*rgb).or_insert(paint);
if !matches!(**chosen, Paint::Solid { swatch: Some(_), .. }) && matches!(paint, Paint::Solid { swatch: Some(_), .. }) {
*chosen = paint;
}
by_color.entry(*rgb).or_insert(paint);
}
let id = s.edit(label, |d, sel| {
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
+6 -6
View File
@@ -444,10 +444,10 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> {
})
}
/// Expand the pattern fills under `root` that paint a transparent image into the tiles they paint
/// Expand the pattern fills under `root` that paint a transparent or colorized image into the tiles they paint
/// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other
/// pattern fills stay. A tile image counts as
/// transparent when its key is in `see_through` (it has see-through pixels), or when it, a group
/// pattern fills stay. A tile image counts when its key is in `see_through` (it has see-through
/// pixels), when it has a colorize paint, or when it, a group
/// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending
/// mode. Returns how many shapes changed.
pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet<String>) -> Result<usize> {
@@ -473,12 +473,12 @@ fn blended(n: &Node) -> bool {
n.opacity < 1.0 || n.blend != BlendMode::Normal
}
/// Whether `n` is or holds a transparent image: one with see-through pixels (key in `keys`), or
/// with opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`.
/// Whether `n` is or holds an image with see-through pixels (key in `keys`), a colorize paint,
/// opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`.
fn transparent_image(n: &Node, keys: &BTreeSet<String>, on: bool) -> bool {
let on = on || blended(n);
match &n.kind {
NodeKind::Image(im) => on || keys.contains(&im.key),
NodeKind::Image(im) => on || keys.contains(&im.key) || n.extras().colorize.is_some(),
_ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))),
}
}
+2 -3
View File
@@ -161,9 +161,8 @@ fn expand_appearances(d: &mut Document) {
}
}
/// Expand every layer's pattern fills that paint a transparent image into their tiles, so those
/// images flatten like any other transparent image. The writer would otherwise draw them opaque
/// over white.
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
/// opacity or blending into their tiles, so those images can be flattened.
fn expand_image_patterns(d: &mut Document) -> Result<()> {
let keys = super::super::flatten::see_through_images(d);
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
+38 -14
View File
@@ -56,6 +56,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection_outside_isolation,
|s, _| other_layers(s, true)
),
cmd!(
"object.lock.unselected",
"Unselected Artwork",
["Object", "Lock"],
Some("Cmd+Alt+Shift+2"),
"{} lock unselected artwork in one undo step, including unselected members of partly selected groups, clipping groups and compound paths, and guides while Lock Guides is on; hidden art and art on locked layers stay unlocked; a selected layer's art counts as selected; in isolation, only art inside the isolated object is affected; object.unlockAll unlocks locked art document-wide → {count}",
has_selection,
|s, _| unselected_art(s, true)
),
cmd!(
"object.hide.above",
"All Artwork Above",
@@ -81,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
Some("Cmd+Alt+Shift+3"),
"{} hide, in one undo step, every object select.all takes that is not selected and holds no selected object; in a group that holds one it hides the other members one by one, and a clip group, compound path or other object that holds one stays as it is; the objects of a selected layer count as selected; while Lock Guides is on, guide paths count as selected and stay as they are; object.showAll shows them again; disabled in isolation mode → {count}",
has_selection_outside_isolation,
hide_unselected
|s, _| unselected_art(s, false)
),
cmd!(
"object.transformEach",
@@ -321,15 +330,24 @@ fn other_layers(s: &mut Session, lock: bool) -> Result<Value> {
Ok(json!({ "count": n }))
}
/// The objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and hold none of
/// them. The objects of a selected layer count as selected. Guide paths are left out while `guides_locked`, and so are
/// the objects that hold one. The walk goes into a plain group that holds a selected object or such a guide path; a
/// clip group, a Shaper group, a compound path and every other object that holds one is left out with its members.
fn unselected(d: &vectorcraft_doc::Document, iso: Option<NodeId>, selection: &[NodeId], roots: &[NodeId], guides_locked: bool) -> Vec<NodeId> {
/// Returns the objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and
/// hold none of them. A selected layer's objects count as selected. The walk goes into a plain group, but not a Shaper
/// group, that holds a selected object. With `lock`, it also goes into a clip group or compound path that holds one,
/// and includes guide paths while `guides_locked`. Without `lock`, guide paths and the objects that hold one are left
/// out while `guides_locked`; a clip group, Shaper group, compound path and every other object that holds a selected
/// object or such a guide are left out with their members.
fn unselected(
d: &vectorcraft_doc::Document,
iso: Option<NodeId>,
selection: &[NodeId],
roots: &[NodeId],
guides_locked: bool,
lock: bool,
) -> Vec<NodeId> {
let mut roots: HashSet<NodeId> = roots.iter().copied().collect();
roots.extend(selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()).flat_map(|l| l.layer_art(true)));
let mut kept: Vec<NodeId> = roots.iter().copied().collect();
if guides_locked {
if guides_locked && !lock {
super::select::walk_selectable(d, iso, |n| {
if matches!(n.kind, NodeKind::Path { guide: true, .. }) {
kept.push(n.id);
@@ -344,24 +362,30 @@ fn unselected(d: &vectorcraft_doc::Document, iso: Option<NodeId>, selection: &[N
out.push(n.id);
return false;
}
!roots.contains(&n.id) && matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.extras().shaper.is_none()
!roots.contains(&n.id)
&& (matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.extras().shaper.is_none()
|| lock && (matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Compound { .. })))
});
out
}
fn hide_unselected(s: &mut Session, _: &Value) -> Result<Value> {
fn unselected_art(s: &mut Session, lock: bool) -> Result<Value> {
let roots = selected_roots_to_transform(s)?;
let guides_locked = s.menu.guides_locked;
let st = s.doc()?;
let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked);
// With nothing to hide, the document and its undo history stay as they are.
let ids = unselected(&st.doc, st.isolation, &st.selection.objects, &roots, guides_locked, lock);
// With nothing to lock (Lock) or hide (Hide), the document and its undo history stay as they are.
if !ids.is_empty() {
s.edit("Hide", |d, _| {
// Hiding moves no node in the tree, so the paths found up front stay right.
s.edit(if lock { "Lock" } else { "Hide" }, |d, _| {
// Locking and hiding move no node in the tree, so the paths found up front stay right.
let paths = d.index_paths(ids.iter().copied());
for id in &ids {
if let Some(n) = paths.get(id).and_then(|p| d.node_mut_at(p)) {
n.visible = false;
if lock {
n.locked = true;
} else {
n.visible = false;
}
}
}
Ok(())
+1
View File
@@ -35,4 +35,5 @@ pub(crate) use arrange::group_nodes;
pub(crate) use bounds::bounds_rewrite;
pub use commands::specs;
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
+24 -9
View File
@@ -1,3 +1,6 @@
use vectorcraft_doc::AnchorRef;
use vectorcraft_geom::PathData;
use super::spans::Span;
use super::{
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
@@ -249,17 +252,29 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
Some(k) => k.clone(),
None => c.picked(partial.as_deref()),
};
let (selected, layout) = (partial.as_deref().map(|a| c.corners_of(a)), c.sources().to_vec());
set_corners(path, live, &picked, radius, kind);
// Direct-Selected corners stay selected as they gain or lose anchors.
if let (Some(anchors), Some(selected)) = (partial, selected)
&& let Some(c) = LiveCorners::new(path, live.as_deref())
&& c.sources() != layout
{
*anchors = c.anchors_of(&selected);
}
recut(path, live, partial, &picked, radius, kind);
}
Ok(())
})?;
ok()
}
/// [`set_corners`] with the Direct-Selected corners (`partial`, the path's selected anchors)
/// staying selected as they gain or lose anchors.
pub(in crate::cmd) fn recut(
path: &mut PathData,
live: &mut Option<Box<LiveShape>>,
partial: Option<&mut BTreeSet<AnchorRef>>,
picked: &BTreeSet<usize>,
radius: Option<f64>,
kind: Option<CornerKind>,
) {
let before = LiveCorners::new(path, live.as_deref()).map(|c| (partial.as_deref().map(|a| c.corners_of(a)), c.sources().to_vec()));
set_corners(path, live, picked, radius, kind);
if let (Some(anchors), Some((Some(selected), layout))) = (partial, before)
&& let Some(c) = LiveCorners::new(path, live.as_deref())
&& c.sources() != layout
{
*anchors = c.anchors_of(&selected);
}
}
+2 -2
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Step Type",
[],
None,
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the character before it, leading its paragraph), else every selected type object → {ids}",
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the character before it, leading its paragraph), else every selected type object → {ids}",
has_doc,
type_step
),
@@ -1133,7 +1133,7 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
/// Cmd/Ctrl+Alt+Q: tracking 0 and kerning Auto (0 in the Character panel) in the type objects in
/// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret,
/// only the kerning of the character before it changes, as Alt+←/→ kerns there.
/// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there.
fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> {
let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?;
if !ranges.is_empty() {
+11 -3
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sample Color",
[],
None,
"{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index} sample a colour into the active fill/stroke (and the selection); with `stop`, recolour that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
"{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
has_doc,
sample_color
),
@@ -343,7 +343,11 @@ fn eyedropper_options(s: &mut Session, p: &Value) -> Result<Value> {
fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paint.sampleColor";
let stroke = p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active);
let stroke = super::switch_or(p, "stroke", !s.fill_active, C)?;
let clear_stroke = super::switch_or(p, "clearStroke", false, C)?;
if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) {
return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`"));
}
let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?;
let (id, mut q) = match p.get("stop") {
None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })),
@@ -364,7 +368,11 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
q["ids"] = ids.clone();
}
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
(spec.run)(s, &q)
let result = (spec.run)(s, &q)?;
if clear_stroke {
s.paint.stroke = Paint::None;
}
Ok(result)
}
// ---------- artboards ----------
+125 -16
View File
@@ -2316,6 +2316,88 @@ fn live_paint_bucket_tool_fills_face() {
assert_eq!(s.doc().unwrap().selection.objects, vec![f.id]);
}
#[test]
fn live_paint_bucket_alt_sample_paints_next_face_without_changing_selection() {
let mut s = session();
let g = live(&mut s);
let src = rect(&mut s, 300.0, 0.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 12})).unwrap();
let dst = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
s.execute("paint.default", &json!({})).unwrap();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone());
let face_before = vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(125.0, 50.0)).unwrap().appearance.fill_paint();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { alt: true, ..Default::default() }), v).unwrap();
assert_eq!(s.paint.fill.color(), Some(Color::rgb8(255, 0, 0)));
assert_eq!(s.paint.stroke.color(), Some(Color::rgb8(0, 0, 255)));
assert_eq!(s.paint.stroke_width, 12.0);
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone()), before);
assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::WHITE));
assert_eq!(node(&s, src).appearance.fill_paint().color(), Some(Color::rgb8(255, 0, 0)));
assert_eq!(vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), face_before);
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 50.0), v).unwrap();
assert_eq!(
vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(125.0, 50.0)).unwrap().appearance.fill_paint().color(),
Some(Color::rgb8(255, 0, 0))
);
}
#[test]
fn live_paint_bucket_alt_image_samples_fill_and_clears_stroke() {
let mut s = session();
let img = image::RgbaImage::from_raw(1, 1, vec![0, 255, 0, 255]).unwrap();
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png));
let id = d.alloc_id();
let im = ImageObject {
key: "px".into(),
width: 1,
height: 1,
xf: Affine::translate((300.0, 0.0)) * Affine::scale(100.0),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| EngineError::Other(e.to_string()))
})
.unwrap();
let dst = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { alt: true, ..Default::default() }), v).unwrap();
assert_eq!(s.paint.fill.color(), Some(Color::rgb8(0, 255, 0)));
assert!(s.paint.stroke.is_none());
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone()), before);
assert_eq!(node(&s, dst).appearance.stroke_paint().color(), Some(Color::rgb8(0, 0, 255)));
}
#[test]
fn live_paint_bucket_alt_shift_gradient_samples_active_stroke_only() {
let mut s = session();
let src = rect(&mut s, 300.0, 0.0, 100.0, 100.0);
s.execute("paint.setFill", &json!({"gradient": {"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}})).unwrap();
let dst = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
s.execute("paint.setStroke", &json!({"color": "#ffffff"})).unwrap();
let fill = s.paint.fill.clone();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { alt: true, shift: true, ..Default::default() }), v).unwrap();
let sampled = s.paint.stroke.color().unwrap().to_rgb();
assert!(sampled[0] > 0.0 && sampled[2] > 0.0 && sampled[1] < 0.01, "{sampled:?}");
assert_eq!(s.paint.fill, fill);
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().selection.clone()), before);
assert_eq!(node(&s, dst).appearance.stroke_paint().color(), Some(Color::WHITE));
assert!(matches!(node(&s, src).appearance.fill_paint(), Paint::Gradient(_)));
}
#[test]
fn live_paint_selection_marquee_selects_what_it_touches() {
let mut s = session();
@@ -3106,7 +3188,7 @@ fn image_trace_document_library_uses_a_color_group() {
}
#[test]
fn image_trace_document_library_links_fills_to_global_swatches() {
fn image_trace_document_library_fills_are_unlinked() {
let mut s = session();
// A global color, a tint of another global color and a process color.
s.execute("swatch.new", &json!({"name": "Ink", "color": "#c82828", "global": true})).unwrap();
@@ -3126,7 +3208,7 @@ fn image_trace_document_library_links_fills_to_global_swatches() {
});
let img = add_image(&mut s, &r, Affine::IDENTITY);
let params = json!({"mode": "color", "palette": "documentLibrary", "library": "document", "colors": 3});
// Each fill as (its color, the swatch it links to, its tint), one per color.
// Each fill as (its color, its swatch link, its tint), one per color.
let fills = |s: &Session, id: &Value| {
let mut v: Vec<(String, Option<String>, f32)> = node(s, NodeId(id.as_u64().unwrap()))
.children()
@@ -3148,27 +3230,26 @@ fn image_trace_document_library_links_fills_to_global_swatches() {
let res = s.execute("imageTrace.makeAndExpand", &json!({"params": params})).unwrap();
let got = fills(&s, &res["id"]);
assert_eq!(got.len(), 3, "{got:?}");
assert!(got.contains(&fill("#c82828", Some("Ink"), 1.0)), "{got:?}");
assert!(got.contains(&fill(&tint, Some("Sky"), 0.5)), "{got:?}");
assert!(got.contains(&fill("#c82828", None, 1.0)), "{got:?}");
assert!(got.contains(&fill(&tint, None, 1.0)), "{got:?}");
assert!(got.contains(&fill("#28a03c", None, 1.0)), "{got:?}");
// Editing the global swatches recolors the trace: the tint at its own tint.
// Editing the global swatches leaves the traced colors unchanged.
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#ff8800"})).unwrap();
s.execute("swatch.edit", &json!({"name": "Sky", "color": "#000000"})).unwrap();
let tint = hex_of(&mut s, "Sky 50%");
let got = fills(&s, &res["id"]);
assert!(got.contains(&fill("#ff8800", Some("Ink"), 1.0)), "{got:?}");
assert!(got.contains(&fill(&tint, Some("Sky"), 0.5)), "{got:?}");
assert!(got.contains(&fill("#c82828", None, 1.0)), "{got:?}");
assert!(got.contains(&fill(&tint, None, 1.0)), "{got:?}");
assert!(got.contains(&fill("#28a03c", None, 1.0)), "{got:?}");
for _ in 0..3 {
s.execute("edit.undo", &json!({})).unwrap();
}
// A color group's global swatches link too.
// A color group's global swatches also fill without links.
s.execute("swatch.newGroup", &json!({"name": "Brand", "swatches": ["Ink", "Leaf"]})).unwrap();
let mut group = params.clone();
group["colorGroup"] = json!("Brand");
let res = s.execute("imageTrace.makeAndExpand", &json!({"id": img.0, "params": group})).unwrap();
let got = fills(&s, &res["id"]);
assert!(got.contains(&fill("#c82828", Some("Ink"), 1.0)) && got.contains(&fill("#28a03c", None, 1.0)), "{got:?}");
assert!(got.contains(&fill("#c82828", None, 1.0)) && got.contains(&fill("#28a03c", None, 1.0)), "{got:?}");
s.execute("edit.undo", &json!({})).unwrap();
// A swatch library's colors stay unlinked.
let mut web = params.clone();
@@ -3179,7 +3260,7 @@ fn image_trace_document_library_links_fills_to_global_swatches() {
}
#[test]
fn image_trace_document_library_links_to_a_global_swatch_after_a_process_swatch_of_its_color() {
fn image_trace_document_library_same_color_stays_unlinked_in_swatch_order() {
let mut s = session();
// A process swatch, then two global swatches, all of one color.
s.execute("swatch.new", &json!({"name": "Red", "color": "#c82828"})).unwrap();
@@ -3204,15 +3285,43 @@ fn image_trace_document_library_links_to_a_global_swatch_after_a_process_swatch_
let red = Color::rgb8(200, 40, 40);
let reds: Vec<&Paint> = got.iter().filter(|p| p.color().map(|c| c.to_rgba8(1.0)) == Some(red.to_rgba8(1.0))).collect();
assert!(!reds.is_empty(), "{got:?}");
assert!(reds.iter().all(|p| matches!(p, Paint::Solid { swatch: Some(w), .. } if w == "Ink")), "{got:?}");
assert!(reds.iter().all(|p| matches!(p, Paint::Solid { swatch: None, .. })), "{got:?}");
let tints: Vec<&Paint> = got.iter().filter(|p| p.color().map(|c| c.to_rgba8(1.0)) == Some([tr, tg, tb, 255])).collect();
assert!(!tints.is_empty(), "{got:?}");
assert!(tints.iter().all(|p| matches!(p, Paint::Solid { swatch: Some(w), tint, .. } if w == "Sky" && *tint == 0.5)), "{got:?}");
// Editing the global swatch recolors the trace.
assert!(tints.iter().all(|p| matches!(p, Paint::Solid { swatch: None, .. })), "{got:?}");
// Editing the global swatch leaves the trace unchanged.
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#ff8800"})).unwrap();
let g = node(&s, NodeId(res["id"].as_u64().unwrap()));
let orange = Color::rgb8(255, 136, 0).to_rgba8(1.0);
assert!(g.children().unwrap().iter().any(|n| n.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) == Some(orange)));
assert!(!g.children().unwrap().iter().any(|n| n.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) == Some(orange)));
assert_eq!(g.children().unwrap().iter().map(|n| n.appearance.fill_paint()).collect::<Vec<_>>(), got);
}
#[test]
fn image_trace_document_library_same_color_is_unlinked_in_both_swatch_orders() {
let trace_fill = |global_first: bool| {
let mut s = session();
for global in [global_first, !global_first] {
s.execute("swatch.new", &json!({"name": if global { "Ink" } else { "Red" }, "color": "#c82828", "global": global})).unwrap();
}
let r = vectorcraft_trace::Raster::from_fn(60, 60, |_, _| [200, 40, 40, 255]);
add_image(&mut s, &r, Affine::IDENTITY);
let res = s
.execute(
"imageTrace.makeAndExpand",
&json!({"params": {"mode": "color", "palette": "documentLibrary", "library": "document", "colors": 2}}),
)
.unwrap();
let g = node(&s, NodeId(res["id"].as_u64().unwrap()));
let fills: Vec<Paint> = g.children().unwrap().iter().map(|n| n.appearance.fill_paint()).collect();
assert!(!fills.is_empty());
assert!(fills.iter().all(|p| matches!(p, Paint::Solid { swatch: None, .. })), "{fills:?}");
fills
};
let process_first = trace_fill(false);
let global_first = trace_fill(true);
assert_eq!(process_first, global_first);
assert!(process_first.iter().all(|p| p.color() == Some(Color::rgb8(200, 40, 40))));
}
#[test]
@@ -3255,7 +3364,7 @@ fn image_trace_document_library_matches_a_lab_spot_by_its_cmyk_equivalent() {
let res = s.execute("imageTrace.makeAndExpand", &json!({"params": params})).unwrap();
let g = node(&s, NodeId(res["id"].as_u64().unwrap()));
let got: Vec<Paint> = g.children().unwrap().iter().map(|n| n.appearance.fill_paint()).collect();
let spot = Paint::Solid { color: shown, swatch: Some("Lab Ink".into()), tint: 1.0 };
let spot = Paint::solid(shown);
assert!(got.contains(&spot), "{got:?}");
assert!(!got.iter().any(|p| p.color() == Some(process)), "{got:?}");
}
+107
View File
@@ -68,6 +68,113 @@ fn picking_up_without_weight_keeps_the_target_weight() {
assert!(s.execute("appearance.copyFrom", &json!({"source": src.0, "pickUp": {"nope": true}})).is_err());
}
#[test]
fn bucket_attribute_sample_changes_only_defaults_and_respects_options() {
let mut s = session();
let (src, dst) = source_and_target(&mut s);
let art = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo = undo_len(&s);
s.execute("eyedropper.setOptions", &json!({"pickUp": {"appearance": {"stroke": {"weight": false}}}})).unwrap();
let width = s.paint.stroke_width;
s.execute("appearance.copyFrom", &json!({"source": src.0, "defaultsOnly": true})).unwrap();
assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#ff0000");
assert_eq!(s.paint.stroke.color().unwrap().to_hex(), "#0000ff");
assert_eq!(s.paint.stroke_width, width);
assert_eq!(s.doc().unwrap().doc, art);
assert_eq!(s.doc().unwrap().selection, selection);
assert_eq!(undo_len(&s), undo);
assert_eq!(node(&s, dst).appearance.fill_paint().color().unwrap().to_hex(), "#ffffff");
for extra in [json!({"ids": []}), json!({"reverse": true}), json!({"append": true})] {
let mut p = json!({"source": src.0, "defaultsOnly": true});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
assert!(s.execute("appearance.copyFrom", &p).is_err());
}
assert!(s.execute("appearance.copyFrom", &json!({"source": src.0, "defaultsOnly": "yes"})).is_err());
assert_eq!(s.doc().unwrap().doc, art);
assert_eq!(undo_len(&s), undo);
}
#[test]
fn bucket_attribute_sample_does_not_replace_last_eyedropper_sample() {
let mut s = session();
let (src, dst) = source_and_target(&mut s);
s.execute("appearance.copyFrom", &json!({"source": src.0, "defaultsOnly": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("appearance.copyFrom", &json!({"source": dst.0, "reverse": true})).is_err());
}
#[test]
fn bucket_attribute_sample_does_not_commit_highlighted_type() {
let mut s = session();
s.prefs.placeholder_text = false;
let src = rect(&mut s, 300.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let view = ViewInfo::default();
s.select_tool("type", view).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 20.0, 300.0), view).unwrap();
}
let dst = s.doc().unwrap().selection.objects[0];
s.tool_text("ABCD", view).unwrap();
s.set_tool_option("select", &json!({"start": 0, "end": 2}));
let before = node(&s, dst);
let undo = undo_len(&s);
s.execute("appearance.copyFrom", &json!({"source": src.0, "defaultsOnly": true})).unwrap();
assert_eq!(node(&s, dst), before);
assert_eq!(undo_len(&s), undo, "sampling does not commit pending typing");
assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#ff0000");
}
#[test]
fn bucket_color_sample_changes_only_defaults_and_supplies_next_fill() {
let mut s = session();
let src = rect(&mut s, 300.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let dst = rect(&mut s, 10.0);
s.execute("paint.setFill", &json!({"color": "#0000ff", "ids": [dst.0]})).unwrap();
let dst_before = node(&s, dst);
let art = s.doc().unwrap().doc.clone();
let undo = undo_len(&s);
s.execute("paint.sampleColor", &json!({"color": "#00ff00", "ids": []})).unwrap();
assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#00ff00");
assert_eq!(node(&s, dst), dst_before);
assert_eq!(s.doc().unwrap().doc, art);
assert_eq!(undo_len(&s), undo);
s.execute("appearance.copyFrom", &json!({"source": src.0, "defaultsOnly": true})).unwrap();
assert_eq!(node(&s, dst), dst_before);
assert_eq!(undo_len(&s), undo);
let r = s.execute("livePaint.fill", &json!({"ids": [dst.0], "point": [35, 35]})).unwrap();
let face = NodeId(r["face"].as_u64().unwrap());
assert_eq!(node(&s, face).appearance.fill_paint().color().unwrap().to_hex(), "#ff0000");
}
#[test]
fn image_color_sample_sets_only_fill_default_and_clears_stroke() {
let mut s = session();
let dst = rect(&mut s, 10.0);
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
let before = (node(&s, dst), s.doc().unwrap().selection.clone());
s.execute("paint.sampleColor", &json!({"color": "#00ff00", "stroke": false, "ids": [], "clearStroke": true})).unwrap();
assert_eq!(s.paint.fill.color(), Some(Color::rgb8(0, 255, 0)));
assert!(s.paint.stroke.is_none());
assert_eq!((node(&s, dst), s.doc().unwrap().selection.clone()), before);
let state = (s.paint.clone(), node(&s, dst));
for p in [
json!({"color": "#ffffff", "stroke": true, "ids": [], "clearStroke": true}),
json!({"color": "#ffffff", "ids": [], "clearStroke": true}),
json!({"color": "#ffffff", "stroke": false, "clearStroke": true}),
json!({"color": "#ffffff", "stroke": false, "ids": [dst.0], "clearStroke": true}),
json!({"color": "#ffffff", "stroke": false, "ids": [], "stop": 0, "clearStroke": true}),
json!({"color": "#ffffff", "stroke": false, "ids": [], "clearStroke": "yes"}),
json!({"color": "#ffffff", "stroke": "no", "ids": [], "clearStroke": true}),
json!({"color": {"bad": true}, "stroke": false, "ids": [], "clearStroke": true}),
] {
assert!(s.execute("paint.sampleColor", &p).is_err(), "{p}");
assert_eq!((s.paint.clone(), node(&s, dst)), state, "{p}");
}
}
#[test]
fn every_appearance_attribute_copies_the_whole_stack() {
let mut s = session();
+61
View File
@@ -520,6 +520,67 @@ fn pattern_over_blue(tile: &[u8], opacity: f32) -> Session {
s
}
/// A pattern of opaque grayscale pixels whose black squares draw red and white squares leave the blue background visible.
fn colorized_pattern_over_blue() -> Session {
fn colorize_image(n: &mut vectorcraft_doc::Node) -> bool {
if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) {
n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))));
return true;
}
n.children_mut().is_some_and(|children| children.iter_mut().any(|child| colorize_image(std::sync::Arc::make_mut(child))))
}
let tile = image::GrayImage::from_fn(32, 32, |x, y| image::Luma([if (x < 16) == (y < 16) { 0 } else { 255 }]));
let mut bytes = vec![];
tile.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let mut s = pattern_over_blue(&bytes, 1.0);
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
assert!(d.patterns[0].art.iter_mut().any(|art| colorize_image(std::sync::Arc::make_mut(art))));
s
}
#[test]
fn a_colorized_grayscale_image_pattern_fill_is_expanded() {
let mut s = colorized_pattern_over_blue();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let keys = crate::cmd::flatten::see_through_images(d);
assert!(keys.is_empty());
let layer = d.layers[0].id;
assert_eq!(crate::cmd::expand::expand_transparent_image_patterns(d, layer, &keys).unwrap(), 1);
let mut patterns = 0;
let mut tile_images = 0;
d.walk(|n| {
patterns += n
.appearance
.items
.iter()
.filter(
|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(f.paint, vectorcraft_color::Paint::Pattern { .. })),
)
.count();
tile_images += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)));
});
assert_eq!(patterns, 0);
assert!(tile_images > 0);
}
#[test]
fn colorized_grayscale_image_pattern_keeps_its_colors_in_legacy_ai() {
let mut s = colorized_pattern_over_blue();
let points = [(72.0, 72.0), (88.0, 72.0), (136.0, 152.0), (152.0, 152.0)];
let before: Vec<[u8; 3]> = points.iter().map(|&(x, y)| colour_at(&s.doc().unwrap().doc, x, y)).collect();
assert_eq!(before[0], [255, 0, 0], "{before:?}");
assert_eq!(before[1], [0, 0, 255], "{before:?}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "flatten"})).unwrap();
let saved_warnings = warnings(&r);
s.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let after: Vec<[u8; 3]> = points.iter().map(|&(x, y)| colour_at(&s.doc().unwrap().doc, x, y)).collect();
for (a, b) in before.iter().zip(&after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "before {before:?} after {after:?}");
}
assert!(saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}");
}
/// #3666: a pattern fill whose tile is an image, under opacity, is flattened with the art under it
/// like a transparent image, instead of being written opaque over white.
#[test]
+159 -5
View File
@@ -518,8 +518,9 @@ fn lock_and_hide_with_nothing_to_lock_or_hide_record_no_undo_step() {
/// Hide › Unselected Artwork hides, in one undo step, each object that is not selected and holds no selected object:
/// here `b`, the member `n` of the group that holds the selected `m`, and `p` on another layer. The selected objects,
/// that group, the clip group that holds the selected `c2` with all its members, a locked object, the art on a locked
/// layer and an object hidden before stay as they are, and so does the selection. Show All shows them again.
/// that group, the clip group that holds the selected `c2` with all its members, the compound path that holds the
/// selected `hole` with both paths, a guide under Lock Guides, a locked object, the art on a locked layer and an
/// object hidden before stay as they are, and so does the selection. Show All shows them again.
#[test]
fn hide_unselected_artwork_hides_every_object_that_is_not_selected() {
let mut s = session();
@@ -534,6 +535,14 @@ fn hide_unselected_artwork_hides_every_object_that_is_not_selected() {
let c3 = rect(&mut s, 80.0, 0.0, 30.0, 30.0);
sel(&mut s, &[c1, c2, c3]);
let clip = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
let outer = rect(&mut s, 0.0, 200.0, 100.0, 100.0);
let hole = rect(&mut s, 40.0, 240.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let guide = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
sel(&mut s, &[guide]);
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
let k = rect(&mut s, 120.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": k.0, "locked": true})).unwrap();
let h = rect(&mut s, 140.0, 0.0, 10.0, 10.0);
@@ -544,13 +553,13 @@ fn hide_unselected_artwork_hides_every_object_that_is_not_selected() {
let q = rect(&mut s, 20.0, 100.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": locked_layer.0, "locked": true})).unwrap();
let shown = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).visible).collect::<Vec<_>>();
sel(&mut s, &[a, m, c2]);
sel(&mut s, &[a, m, c2, hole]);
let steps = undo_len(&s);
assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 3}));
assert_eq!(shown(&s, &[b, n, p, h]), [false; 4]);
assert_eq!(shown(&s, &[a, m, g, c1, c2, c3, clip, k, q]), [true; 9]);
assert_eq!(shown(&s, &[a, m, g, c1, c2, c3, clip, compound, outer, hole, guide, k, q]), [true; 13]);
assert!(node(&s, k).locked);
assert_eq!((undo_len(&s), selected(&s)), (steps + 1, vec![a, m, c2]));
assert_eq!((undo_len(&s), selected(&s)), (steps + 1, vec![a, m, c2, hole]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(shown(&s, &[b, n, p]), [true; 3]);
s.execute("edit.redo", &json!({})).unwrap();
@@ -650,6 +659,151 @@ fn hide_unselected_artwork_keeps_groups_with_locked_guides_and_the_selected_laye
assert_eq!(selected(&s), [other]);
}
/// Lock Unselected Artwork locks `b`, `n` in the group that holds selected `m`, `p` on another layer, and the clip
/// group's unselected members `c1` and clipping path `c3` in one undo step labeled "Lock". The clip group container,
/// `c2`, the selected objects, group `g`, hidden object `h` and art `q` on a locked layer stay unlocked. `k` was locked
/// before. The selection stays as it is. Unlock All unlocks all six locked objects and selects them.
#[test]
fn lock_unselected_artwork_locks_every_object_that_is_not_selected() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let m = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let n = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[m, n]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let c1 = rect(&mut s, 80.0, 0.0, 10.0, 10.0);
let c2 = rect(&mut s, 85.0, 5.0, 10.0, 10.0);
let c3 = rect(&mut s, 80.0, 0.0, 30.0, 30.0);
sel(&mut s, &[c1, c2, c3]);
let clip = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
let k = rect(&mut s, 120.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": k.0, "locked": true})).unwrap();
let h = rect(&mut s, 140.0, 0.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": h.0, "visible": false})).unwrap();
s.execute("layer.new", &json!({})).unwrap();
let p = rect(&mut s, 0.0, 100.0, 10.0, 10.0);
let locked_layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let q = rect(&mut s, 20.0, 100.0, 10.0, 10.0);
s.execute("layer.setProps", &json!({"id": locked_layer.0, "locked": true})).unwrap();
let locked = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).locked).collect::<Vec<_>>();
sel(&mut s, &[a, m, c2]);
let steps = undo_len(&s);
assert_eq!(s.execute("object.lock.unselected", &json!({})).unwrap(), json!({"count": 5}));
assert_eq!(locked(&s, &[b, n, p, c1, c3, k]), [true; 6]);
assert_eq!(locked(&s, &[a, m, g, c2, clip, h, q]), [false; 7]);
assert_eq!((undo_len(&s), selected(&s)), (steps + 1, vec![a, m, c2]));
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Lock");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(locked(&s, &[b, n, p]), [false; 3]);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(locked(&s, &[b, n, p]), [true; 3]);
assert_eq!(s.execute("object.unlockAll", &json!({})).unwrap(), json!({"count": 6}));
assert_eq!(locked(&s, &[b, n, p, c1, c3, k]), [false; 6]);
let mut unlocked = selected(&s);
unlocked.sort();
let mut want = vec![b, n, p, c1, c3, k];
want.sort();
assert_eq!(unlocked, want);
}
/// Lock Unselected Artwork affects only the isolated group's other members. Lock Guides does not protect an unselected
/// guide from this command. With nothing left to lock it records no undo step.
#[test]
fn lock_unselected_artwork_scopes_isolation_and_locks_guides() {
let mut s = session();
let guide = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
sel(&mut s, &[guide]);
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
let out = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let m = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let n = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[m, n]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let lock = |s: &mut Session| s.execute("object.lock.unselected", &json!({})).unwrap();
let locked = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).locked).collect::<Vec<_>>();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
select_with_a_step_to_redo(&mut s, &[m]);
let info = find_command("object.lock.unselected").unwrap().info(&s);
assert!(info.enabled, "{info:?}");
let before = undo_len(&s);
assert_eq!(lock(&mut s), json!({"count": 1}));
assert_eq!(locked(&s, &[m, n, out, guide]), [false, true, false, false]);
assert_eq!((undo_len(&s), selected(&s)), (before + 1, vec![m]));
s.execute("object.exitIsolation", &json!({})).unwrap();
sel(&mut s, &[m]);
assert!(find_command("object.lock.unselected").unwrap().info(&s).enabled);
assert_eq!(lock(&mut s), json!({"count": 2}));
assert_eq!(locked(&s, &[n, out, guide, g, m]), [true, true, true, false, false]);
select_with_a_step_to_redo(&mut s, &[m]);
let before = history(&s);
assert_eq!(lock(&mut s), json!({"count": 0}));
assert_eq!(history(&s), before);
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
}
/// Lock Unselected Artwork locks the unselected path of a partly selected compound path, but needs a selection.
#[test]
fn lock_unselected_artwork_descends_into_compound_and_needs_selection() {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let hole = rect(&mut s, 40.0, 40.0, 20.0, 20.0);
sel(&mut s, &[outer, hole]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
s.execute("select.none", &json!({})).unwrap();
let before = history(&s);
assert!(!find_command("object.lock.unselected").unwrap().info(&s).enabled);
assert!(matches!(s.execute("object.lock.unselected", &json!({})), Err(EngineError::Disabled(..))));
assert_eq!(history(&s), before);
sel(&mut s, &[hole]);
assert_eq!(s.execute("object.lock.unselected", &json!({})).unwrap(), json!({"count": 1}));
assert!(node(&s, outer).locked);
assert!(!node(&s, hole).locked);
assert!(!node(&s, compound).locked);
assert_eq!(selected(&s), [hole]);
}
/// Lock Unselected Artwork leaves all art on a selected layer unlocked and locks unselected art on another layer.
#[test]
fn lock_unselected_artwork_keeps_a_selected_layers_art() {
let mut s = session();
let selected_layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
sel(&mut s, &[selected_layer]);
assert_eq!(s.execute("object.lock.unselected", &json!({})).unwrap(), json!({"count": 1}));
assert_eq!([a, b, other].map(|id| node(&s, id).locked), [false, false, true]);
assert_eq!(selected(&s), [selected_layer]);
}
/// In a plain group, Lock and Hide Unselected Artwork affect the same members of identical documents.
#[test]
fn lock_and_hide_unselected_artwork_choose_the_same_objects() {
let prepare = || {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let m = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
let n = rect(&mut s, 60.0, 0.0, 10.0, 10.0);
sel(&mut s, &[m, n]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
sel(&mut s, &[a, m]);
(s, [a, b, m, n, g])
};
let (mut locked, lock_ids) = prepare();
let (mut hidden, hide_ids) = prepare();
assert_eq!(lock_ids, hide_ids);
assert_eq!(locked.execute("object.lock.unselected", &json!({})).unwrap(), json!({"count": 2}));
assert_eq!(hidden.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 2}));
let changed_by_lock: Vec<_> = lock_ids.into_iter().filter(|id| node(&locked, *id).locked).collect();
let changed_by_hide: Vec<_> = hide_ids.into_iter().filter(|id| !node(&hidden, *id).visible).collect();
assert_eq!(changed_by_lock, changed_by_hide);
assert_eq!(changed_by_lock, [lock_ids[1], lock_ids[3]]);
}
// ---------- Transform Each ----------
#[test]
+51
View File
@@ -368,6 +368,57 @@ fn transforms_without_transform_objects_move_only_the_pattern() {
}
}
#[test]
fn selection_backquote_drag_changes_pattern_fill_and_stroke_without_moving_mixed_art() {
let mut s = session();
make_dots(&mut s);
let patterned = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
let solid = rect(&mut s, 220.0, 100.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [patterned.0], "swatch": "Dots"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [patterned.0], "swatch": "Dots"})).unwrap();
s.execute("prefs.set", &json!({"key": "transformPatternTiles", "value": false})).unwrap();
sel(&mut s, &[patterned, solid]);
let before_patterned = node(&s, patterned);
let before_solid = node(&s, solid);
let history = crate::tests::history(&s).0;
let v = ViewInfo { show_bbox: false, ..Default::default() };
s.select_tool("selection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 125.0), v).unwrap();
s.pointer(&PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Drag, 145.0, 125.0) }, v).unwrap();
s.pointer(&PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 145.0, 125.0) }, v).unwrap();
let after = node(&s, patterned);
assert_eq!(after.geometric_bounds(), before_patterned.geometric_bounds());
assert_eq!(node(&s, solid), before_solid);
for paint in [after.appearance.fill_paint(), after.appearance.stroke_paint()] {
let Paint::Pattern { xf, .. } = paint else { panic!("pattern paint expected") };
assert_eq!(xf.as_coeffs()[4], 20.0);
}
assert_eq!(crate::tests::history(&s).0, history + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, patterned), before_patterned);
assert_eq!(node(&s, solid), before_solid);
}
#[test]
fn selection_backquote_drag_changes_stroke_only_pattern() {
let mut s = session();
make_dots(&mut s);
let id = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [id.0], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "swatch": "Dots"})).unwrap();
sel(&mut s, &[id]);
let before = node(&s, id).geometric_bounds();
let v = ViewInfo { show_bbox: false, ..Default::default() };
s.select_tool("selection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 125.0), v).unwrap();
s.pointer(&PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Drag, 120.0, 125.0) }, v).unwrap();
s.pointer(&PointerEvent { backquote: true, ..PointerEvent::new(PointerKind::Up, 120.0, 125.0) }, v).unwrap();
let after = node(&s, id);
assert_eq!(after.geometric_bounds(), before);
let Paint::Pattern { xf, .. } = after.appearance.stroke_paint() else { panic!("pattern stroke expected") };
assert_eq!(xf.as_coeffs()[4], 20.0);
}
#[test]
fn list_reports_patterns_and_edit_state() {
let mut s = session();
+2 -2
View File
@@ -112,10 +112,10 @@ fn alt_smooth_fidelity(s: &mut Session) -> Option<f64> {
})
}
/// Alt switches Pencil and Blob Brush to Smooth, using Smooth Tool Options' stored Fidelity.
/// Alt switches Pencil, Paintbrush and Blob Brush to Smooth, using Smooth Tool Options' stored Fidelity.
#[test]
fn alt_smoothing_takes_the_smooth_tools_fidelity() {
for id in ["pencil", "blobBrush"] {
for id in ["pencil", "paintbrush", "blobBrush"] {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
select(&mut s, "smooth");
+4 -4
View File
@@ -220,8 +220,8 @@ impl Session {
}
}
}
// Alt switches the Pencil or Blob Brush to Smooth, using Smooth Tool Options' Fidelity.
if matches!(t.id(), "pencil" | "blobBrush")
// Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity.
if matches!(t.id(), "pencil" | "paintbrush" | "blobBrush")
&& let Some(v) = prefs.tool_settings.get("smooth").and_then(|s| s.get("fidelity"))
{
t.set_option("smoothFidelity", v);
@@ -633,8 +633,8 @@ impl Session {
/// Set options of tool `id` (default: the active tool). Another tool's persistent options are
/// stored for when it is chosen, and the active tool takes those it shares with it (the
/// Liquify tools' Global Brush Dimensions, the Smooth tool's Fidelity for the Pencil's and
/// Blob Brush's Alt smoothing). Returns the tool's options.
/// Liquify tools' Global Brush Dimensions, the Smooth tool's Fidelity for Pencil, Paintbrush
/// and Blob Brush Alt smoothing). Returns the tool's options.
pub fn set_tool_options(&mut self, id: Option<&str>, values: &Map<String, Value>) -> Value {
let active = id.is_none_or(|id| id == self.tool.id());
self.tool_set_since_reset |= active;
+90
View File
@@ -419,6 +419,18 @@ fn structured_junk() {
"addon.color.filter",
json!({"effect": "addon.color.duotone", "params": {"tones": [{"color": "#ff0000", "swatch": "[Registration]"}], "skipSpot": true}}),
),
("effect.apply", json!({"effect": "addon.path.dashes", "params": {"dash1": 1e308, "gap1": 1e308, "offset": -1e308, "alignCorners": true}})),
("effect.apply", json!({"effect": "addon.path.dashes", "params": {"dash1": -1e308, "gap1": 1e-308, "dash5": 1e-9, "gap5": 0}})),
("effect.apply", json!({"effect": "addon.path.addAnchors", "params": {"target": "x", "spacing": "x", "count": 1e308, "maxCount": 1e308}})),
("effect.apply", json!({"effect": "addon.path.addAnchors", "params": {"spacing": "distance", "distance": 1e-308, "maxCount": -1e308}})),
("effect.apply", json!({"effect": "addon.path.extend", "params": {"startLength": 1e308, "endLength": -1e308, "startPercent": -1e308}})),
("effect.apply", json!({"effect": "addon.path.extend", "params": {"endPercent": 1e308, "endShape": "arc", "startShape": "x"}})),
("effect.apply", json!({"effect": "addon.path.close", "params": {"mode": "x"}})),
("effect.apply", json!({"effect": "addon.path.smooth", "params": {"ratio": 1e308}})),
("effect.apply", json!({"effect": "addon.path.retract", "params": {"handles": "shorter", "length": 1e308}})),
("effect.apply", json!({"effect": "addon.path.reverse"})),
("effect.apply", json!({"effect": "addon.path.simplify", "params": {"tolerance": 1e308, "protectCorners": false}})),
("effect.apply", json!({"effect": "addon.path.split", "params": {"anchors": "x"}})),
("addon.color.printFixes", json!({"inkLimit": 1e308, "overprintBlack": -1e308})),
("addon.color.printFixes", json!({"inkLimit": 1, "overprintBlack": 1, "removeWhiteOverprint": true, "scope": "document", "textOnly": true})),
("addon.color.printFixes", json!({"inkLimit": [300], "scope": 3, "ids": "x"})),
@@ -543,6 +555,30 @@ fn structured_junk() {
("addon.pathtools.shape.set", json!({"id": 2, "center": [1, 2, 3], "radius": "big"})),
("addon.pathtools.shape.convert", json!({"ids": [0, 1, 2, 3, u64::MAX]})),
("addon.pathtools.shape.convert", json!({"ids": "all"})),
// Path Precision Tools: the Corner Tool and Slide Anchor Along Path.
("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 1e6, "kind": "chamfer"})),
("addon.pathtools.cornerSet", json!({"ids": [2, 3], "anchors": [0, 1, u64::MAX], "radius": 5})),
("addon.pathtools.cornerSet", json!({"items": [{"id": 2, "anchors": [0]}, {"id": u64::MAX}], "radius": 1e-300})),
("addon.pathtools.cornerSet", json!({"items": [1, null, {"anchors": "x"}], "radius": 1})),
("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 1e308, "kind": "spiky"})),
("addon.pathtools.cornerSet", json!({"items": "all", "radius": f64::NAN, "anchors": [-1, 1.5, "x"]})),
("addon.pathtools.cornerRemove", json!({"ids": [0, 1, 2, 3, u64::MAX]})),
("addon.pathtools.cornerRemove", json!({"items": [{"id": 2, "anchors": [u64::MAX]}]})),
("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.98})),
("addon.pathtools.slideAnchor", json!({"id": 2, "subpath": u64::MAX, "anchor": 0, "t": -0.5})),
("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": u64::MAX, "t": 1e308})),
("addon.pathtools.slideAnchor", json!({"id": u64::MAX, "anchor": "x", "t": "y"})),
// Path Precision Tools: the Shared Edge Merge Tool and Keep Shared Points Together.
("addon.pathtools.mergeEdge", json!({"a": 2, "b": 3, "at": [0, 0]})),
("addon.pathtools.mergeEdge", json!({"a": 2, "b": 3, "at": [10, 10], "diameter": 200, "tolerance": 3, "ends": true})),
("addon.pathtools.mergeEdge", json!({"a": 2, "b": 2, "at": [0, 0]})),
("addon.pathtools.mergeEdge", json!({"a": 2, "b": u64::MAX, "at": [1e308, -1e308]})),
("addon.pathtools.mergeEdge", json!({"a": 2, "b": 3, "at": [1, 2, 3], "diameter": 1e308, "tolerance": -1, "follow": "up"})),
("addon.pathtools.mergeEdge", json!({"a": "x", "b": null, "at": "y", "follow": 3, "ends": "z"})),
("addon.pathtools.movePointsTogether", json!({"enabled": "maybe"})),
("addon.pathtools.movePointsTogether", json!({"enabled": true})),
("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.5})),
("addon.pathtools.movePointsTogether", json!({"enabled": false})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
@@ -559,6 +595,23 @@ fn structured_junk() {
("addon.pen.reshape", json!({"id": 2, "segment": 0, "t": "x", "dx": 1, "dy": 1, "mode": "symmetric"})),
("addon.pen.nextSegment", json!({"curved": "yes"})),
("addon.pen.closeJoin", json!({"ids": [u64::MAX]})),
("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})),
("addon.cleanup.breakText", json!({"by": ["lines"]})),
("addon.cleanup.breakText", json!({"by": "paragraphs"})),
("addon.cleanup.breakText", json!({"by": "words", "ids": "all"})),
("addon.cleanup.combineText", json!({"ids": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})),
("addon.cleanup.combineText", json!({"ids": [-1, 1e308]})),
("addon.cleanup.removeBreaks", json!({"kind": "paragraph", "ids": [1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})),
("addon.cleanup.removeBreaks", json!({"kind": 3})),
("addon.cleanup.removeBreaks", json!({"kind": "line", "ids": null})),
("addon.cleanup.splitText", json!({"at": 1e308})),
("addon.cleanup.alignInPlace", json!({"align": "right", "ids": [1, 2, 3, 4, 5, 6, 7, 8]})),
("addon.cleanup.alignInPlace", json!({"align": null, "ids": [-1]})),
("addon.cleanup.resetTextTransform", json!({"scale": "yes"})),
("addon.cleanup.resetTextTransform", json!({"scale": true, "ids": [1, 2, 3, 4, 5, 6, 7, 8]})),
("addon.cleanup.replaceFonts", json!({"font": ""})),
("addon.cleanup.replaceFonts", json!({"font": ["Source Sans 3"]})),
("addon.cleanup.replaceFonts", json!({"font": "\u{0}"})),
];
let mut failures = vec![];
for fx in Fixture::ALL {
@@ -571,6 +624,43 @@ fn structured_junk() {
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// Artwork Cleanup's text tools while a Type tool edits type with junk ranges (past the end,
/// reversed, inside a character): never a panic, and the document stays sound.
#[test]
fn cleanup_text_tools_with_junk_editing_ranges() {
let ranges = [(0, u64::MAX / 4), (u64::MAX, 1), (5, 5), (1, 2), (u64::MAX / 4, u64::MAX / 4)];
let mut failures = vec![];
for fx in Fixture::ALL {
let mut texts = vec![];
for l in &fx.session().doc().unwrap().doc.layers {
l.walk(&mut |n| {
if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) {
texts.push(n.id.0);
}
});
}
for id in texts {
for (anchor, caret) in ranges {
for (cmd, p) in [("addon.cleanup.splitText", json!({})), ("addon.cleanup.removeBreaks", json!({"kind": "paragraph"}))] {
let mut s = fx.session();
let r = catch_quiet(|| {
let _ = s.execute("select.set", &json!({"ids": [id]}));
let _ = s.select_tool("type", Default::default());
s.set_tool_option("textSelection", &json!({"editing": id, "anchor": anchor, "caret": caret}));
no_panic(s.execute(cmd, &p))
});
if let Err(msg) = r {
failures.push(format!("PANIC {cmd} {id} {anchor}..{caret} [{fx:?}]: {msg}"));
} else if let Err(e) = check_session(&s) {
failures.push(format!("{cmd} {id} {anchor}..{caret} [{fx:?}]: {e}"));
}
}
}
}
}
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// Shape Builder Tool Options (Gap Detection) with junk values: never a panic, and the tool still
/// answers with options and works on a drag afterwards.
#[test]
+22 -2
View File
@@ -245,8 +245,9 @@ impl MeshReader {
_ => return None,
};
let &[x, y, nx, ny, nw, px, py, pw] = geometry else { return None };
// Non-unit rational weights need a different surface representation.
if nw != 1.0 || pw != 1.0 {
// Weights are 1, or 0 on some corners, which draw as the same cubic edges (checked
// against the files' pages). Others would need a rational surface.
if ![nw, pw].iter().all(|w| *w == 1.0 || *w == 0.0) {
return None;
}
if ![opacity, x, y, nx, ny, px, py].iter().all(|v| v.is_finite()) {
@@ -631,6 +632,25 @@ mod tests {
assert!((first.handles[H_DOWN] - Vec2::new(0.0, 1.0)).hypot() < 1e-9, "{:?}", first.handles);
}
/// A corner's handle weights are 1, or 0 on some corners, which draw as the same patch; any
/// other weight leaves the patch unread.
#[test]
fn corners_with_handle_weights_of_zero_are_read() {
let read = |nw: f64, pw: f64| {
let mut reader = MeshReader::default();
patch(&mut reader, &[0.5, 1.0, 0.0, 0.0, 0.0, 0.3, nw, 0.3, 0.0, pw]);
reader
};
for (nw, pw) in [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] {
let reader = read(nw, pw);
assert!(!reader.unread, "{nw} {pw}");
let p = &reader.patches[0].points[0];
assert_eq!((p.handles[H_DOWN], p.handles[H_RIGHT]), (Vec2::new(0.0, 0.3), Vec2::new(0.3, 0.0)));
}
let reader = read(0.5, 1.0);
assert!(reader.unread && reader.patches.is_empty());
}
#[test]
fn hostile_meshes_are_capped_and_checked() {
let mut reader = MeshReader::default();
+8
View File
@@ -183,8 +183,14 @@ struct Reader<'a> {
blend_budget: usize,
/// A group just ended, its state (`Xy`, `Xd`, `XW`) not yet read.
group_ended: bool,
/// A gradient mesh just ended (`/End X!`), its own state (`Xy`) not yet read: also after its
/// dictionary (its name, its opacity mask and the mask's art).
mesh_ended: bool,
/// A layer's own state (`Xy` after its art, before `LB`), until something says the art moves on.
layer_state: Option<(f32, BlendMode, bool, Knockout)>,
/// The state a mesh or blend had before an `Xy` right after its end, which is the layer's
/// instead when the layer's `LB` follows rather than their own `6 () XW`.
mesh_undo: Option<(f32, BlendMode, bool, Knockout)>,
/// Painted copies of clipping paths that have a fill (drawn under what they clip).
clip_fills: HashSet<NodeId>,
/// Groups closed as an object's drawn look (`9 () XW`).
@@ -288,7 +294,9 @@ impl<'a> Reader<'a> {
compound_groups: HashSet::new(),
text_looks: HashSet::new(),
group_ended: false,
mesh_ended: false,
layer_state: None,
mesh_undo: None,
styles: HashMap::new(),
palette: super::palette::Palette::default(),
restyled: vec![],
+6 -2
View File
@@ -235,7 +235,9 @@ impl<'a> Reader<'a> {
let mut node = self.new_node(NodeKind::Mesh(one), &gs);
node.opacity = gs.opacity;
node.blend = gs.blend;
return self.add(node, hidden);
self.add(node, hidden)?;
self.mesh_ended = true;
return Ok(());
}
Err(crate::import::ai::mesh::NotOne::Unjoined) => {
self.warn("a gradient mesh whose patches don't join up comes in as a group of its patches")
@@ -249,7 +251,9 @@ impl<'a> Reader<'a> {
};
node.opacity = gs.opacity;
node.blend = gs.blend;
self.add(node, hidden)
self.add(node, hidden)?;
self.mesh_ended = true;
Ok(())
}
/// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state.
+17 -4
View File
@@ -19,6 +19,7 @@ impl<'a> Reader<'a> {
children: Vec::new(),
hidden,
after: self.after_object,
mesh_ended: self.mesh_ended,
gs: self.gs.clone(),
base,
clips: Vec::new(),
@@ -171,7 +172,14 @@ impl<'a> Reader<'a> {
}
pub(super) fn end_layer(&mut self) -> Result<(), String> {
let f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?;
let mut f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?;
let state = self.layer_state.take();
// An `Xy` right after the layer's last mesh or blend, then `LB`: the layer's, not theirs.
if let (Some(_), Some(before)) = (state, self.mesh_undo.take())
&& let Some(mesh) = f.children.last_mut().filter(|n| matches!(n.kind, NodeKind::Mesh(_) | NodeKind::Blend { .. }))
{
(mesh.opacity, mesh.blend, mesh.isolate, mesh.knockout) = before;
}
let Kind::Layer(a) = f.kind else { return Ok(()) };
let (children, clip) = self.clip_first(f.children, &f.clips);
let color = a.color.unwrap_or(LayerColor::Preset(0));
@@ -183,7 +191,7 @@ impl<'a> Reader<'a> {
layer.visible = a.visible;
layer.locked = a.locked;
// The layer's own opacity, blend and knockout, written after its art (#2003).
if let Some((opacity, blend, isolate, knockout)) = self.layer_state.take() {
if let Some((opacity, blend, isolate, knockout)) = state {
(layer.opacity, layer.blend, layer.isolate, layer.knockout) = (opacity, blend, isolate, knockout);
}
match self.frames.last_mut() {
@@ -236,6 +244,7 @@ impl<'a> Reader<'a> {
let art = self.new_node(NodeKind::Group { children, clip }, &f.gs);
self.gs = f.gs;
self.after_object = f.after;
self.mesh_ended = f.mesh_ended;
let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last_mut() else {
return Err("mask art ends outside a mask dictionary".into());
};
@@ -251,13 +260,15 @@ impl<'a> Reader<'a> {
return Ok(());
}
let Some(f) = self.frames.pop() else { return Ok(()) };
let Frame { kind, children, base, hidden, gs, after, .. } = f;
let Frame { kind, children, base, hidden, gs, after, mesh_ended, .. } = f;
let Kind::Obj(mut o) = kind else { return Ok(()) };
obj::close(&mut o, &mut self.stack, base);
self.obj_hidden = hidden;
// Art made inside a dictionary (type's paths) isn't kept.
// Art made inside a dictionary (type's paths, a mask's art) isn't kept, and doesn't end what
// follows the object the dictionary is about: a mesh's state comes after its mask.
self.gs = gs;
self.after_object = after;
self.mesh_ended = mesh_ended;
if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) {
return self.push(V::Obj(Rc::new(*o)));
}
@@ -392,6 +403,8 @@ impl<'a> Reader<'a> {
self.warn(crate::import::ai::blend::DRAWN);
}
}
// The blend's own state block follows its record, as a group's follows its end.
self.after_object = true;
}
}
+45 -13
View File
@@ -72,13 +72,9 @@ impl<'a> Reader<'a> {
"X+" => return Ok(()),
_ => {}
}
// What follows an object (its name, transparency and style) ends with anything else. The
// state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the `LB`.
if !matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") {
self.after_object = false;
self.layer_state = None;
}
self.state_block_continues(w);
let group_ended = std::mem::take(&mut self.group_ended);
let mesh_ended = std::mem::take(&mut self.mesh_ended);
let vals = self.operands();
let vals = self.take_head(vals);
// Only `Bh` reads an undefined number. Anywhere else it would reach a point or a size, so
@@ -201,7 +197,7 @@ impl<'a> Reader<'a> {
}
}
// Transparency and state.
"Xy" => self.transparency(&vals),
"Xy" => self.transparency(&vals, mesh_ended),
// A group's own state (`Xd`, `6 () XW`) without an `Xy` keeps the current transparency, as
// the file's PDF part draws it. A look's group (`9 () XW`) has no state of its own.
"Xd" if group_ended => {
@@ -212,7 +208,13 @@ impl<'a> Reader<'a> {
}
"Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0),
"A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0),
"XW" => self.style_marker(&vals, hidden),
"XW" => {
// An object's own state block ends `6 () XW`: an `Xy` after a mesh's end was the mesh's.
if Self::nums(&vals).last() == Some(&6.0) && self.mesh_undo.take().is_some() {
self.layer_state = None;
}
self.style_marker(&vals, hidden)
}
// Gradients.
"Bd" => self.gradient_def = GradientDef::begin(&vals),
"Bs" | "BD" => {}
@@ -388,8 +390,26 @@ impl<'a> Reader<'a> {
});
}
/// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too.
fn transparency(&mut self, vals: &[V]) {
/// Operator `w` ends what follows an object (its name, transparency and style) unless it is part
/// of a state block.
/// The state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the
/// `LB`, and can have the stroke style between its `Xy` and `Xd`: that keeps the layer's state,
/// and what a mesh or blend before it had (`mesh_undo`).
fn state_block_continues(&mut self, w: &str) {
if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") {
return;
}
self.after_object = false;
if !matches!(w, "J" | "j" | "w" | "M" | "d" | "XR") {
self.layer_state = None;
self.mesh_undo = None;
}
}
/// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too, and right
/// after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and `6 () XW`),
/// theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`).
fn transparency(&mut self, vals: &[V], mesh_ended: bool) {
let n = Self::nums(vals);
let [mode, opacity, rest @ ..] = n.as_slice() else { return };
let gs = &mut self.gs;
@@ -403,7 +423,16 @@ impl<'a> Reader<'a> {
};
gs.knockout_shape = rest.get(2).is_some_and(|v| *v != 0.0);
let gs = self.gs.clone();
if self.last_object().is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) {
let in_layer = matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. }));
if let Some(n) =
self.last_object().filter(|n| (mesh_ended && matches!(n.kind, NodeKind::Mesh(_))) || matches!(n.kind, NodeKind::Blend { .. }))
{
// The mesh's or blend's, or the layer's when it is the layer's last object: kept for either.
let before = (n.opacity, n.blend, n.isolate, n.knockout);
(n.opacity, n.blend, n.isolate, n.knockout) = (gs.opacity, gs.blend, gs.isolate, gs.knockout);
self.mesh_undo = Some(before);
self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout));
} else if self.last_object().is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) {
if let Some(n) = self.last_object() {
n.opacity = gs.opacity;
n.blend = gs.blend;
@@ -415,8 +444,7 @@ impl<'a> Reader<'a> {
// After a layer's art and before its `LB`: the layer's own state (#2003). Kept until
// an operator that isn't part of the state block (or the `LB` that takes it) says the
// art moves on, so a path's state before its paint isn't read as its layer's.
self.layer_state =
matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })).then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout));
self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout));
}
}
@@ -427,6 +455,10 @@ impl<'a> Reader<'a> {
let code = Self::nums(vals).last().copied().unwrap_or(0.0);
let style = vals.iter().rev().find_map(V::text).unwrap_or_default();
let after = std::mem::take(&mut self.after_object);
// An object's own state block ends `6 () XW` (a layer's `7 () XW`): an `Xy` before it isn't the layer's.
if code == 6.0 {
self.layer_state = None;
}
if code == 9.0
&& let Some(look) = self
.frames
+5
View File
@@ -142,6 +142,8 @@ pub(super) struct Frame {
pub(super) hidden: bool,
/// [`Reader::after_object`] when it opened.
pub(super) after: bool,
/// [`Reader::mesh_ended`] when it opened.
pub(super) mesh_ended: bool,
/// The state when it opened (a container's lock and visibility; a dictionary's state to go
/// back to).
pub(super) gs: GState,
@@ -246,6 +248,9 @@ pub(super) const SKIPPED: &[(&str, &str)] = &[
("BeginSymbolList", "EndSymbolList"),
("BeginTextDocument", "EndTextDocument"),
("BeginEncoding", "EndEncoding"),
// The printer's crop marks, drawn after the layers (`userdict /AI3_noCropMarks known not {
// … } if`); the crop area they mark is `%AI3_Cropmarks`.
("BeginCrops", "EndCrops"),
];
/// The note for versioned content whose `%AI17_End_Versioned_Content` is missing: every
+137
View File
@@ -391,6 +391,53 @@ fn a_layer_keeps_its_own_transparency() {
let doc = read_ok(&layer(&art_)).doc;
assert_eq!(doc.layers[0].opacity, 1.0, "no layer state written: the layer stays opaque");
assert_eq!(art(&doc)[0].opacity, 0.5, "the group's own state");
// A layer whose last object is a gradient mesh: an `Xy` right after the mesh's end is the
// layer's when `LB` follows (directly or after the layer's `Xd` and `7 () XW`), and the mesh's
// when its own `6 () XW` follows.
let corner =
|x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1);
let mesh = format!(
"0 0.8 0 0 0 Xy\n/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n",
corner(0, 0, (0, 10), (10, 0)),
corner(0, 40, (10, 40), (0, 30)),
corner(40, 40, (40, 30), (30, 40)),
corner(40, 0, (30, 0), (40, 10)),
);
for (after, layer_state, mesh_state) in [
("1 0.35 0 0 0 Xy\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)),
("1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)),
("1 0.35 0 0 0 Xy\n0 0 Xd\n6 () XW\n", (1.0, BlendMode::Normal), (0.35, BlendMode::Multiply)),
// The stroke style in the layer's state block.
("1 0.35 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n7 () XW\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)),
] {
let doc = read_ok(&layer(&format!("{mesh}{after}"))).doc;
let l = &doc.layers[0];
assert!(matches!(art(&doc)[0].kind, NodeKind::Mesh(_)), "{after:?}");
assert_eq!((l.opacity, l.blend), layer_state, "the layer's state after {after:?}");
assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), mesh_state, "the mesh's state after {after:?}");
}
}
#[test]
fn a_layers_state_keeps_through_the_stroke_style_written_in_it() {
// GUARDS: a layer's state block can have the stroke style between its `Xy` and `Xd`; read as
// the art moving on, it lost the layer's opacity and the layer drew opaque.
let state = "0 0.25 0 2 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n7 () XW\n";
let clip_group = format!(
"q\n{}h\nW\nn\n0 Ae\nu\n{RED}{}f\nU\n9 () XW\nQ\n9 () XW\n{state}",
rect_path(10.0, 10.0, 90.0, 90.0),
rect_path(0.0, 0.0, 100.0, 100.0)
);
let path = format!("{RED}{}f\n{state}", rect_path(0.0, 0.0, 10.0, 10.0));
for body in [clip_group, path] {
let doc = read_ok(&layer(&body)).doc;
let l = &doc.layers[0];
assert_eq!((l.opacity, l.knockout), (0.25, Knockout::Neutral), "{body}");
assert_eq!(art(&doc)[0].opacity, 1.0, "{body}");
}
// An object's own state block (`6 () XW`) isn't the layer's.
let note = format!("{RED}{}f\n{}", rect_path(0.0, 0.0, 10.0, 10.0), state.replace("7 () XW", "6 () XW"));
assert_eq!(read_ok(&layer(&note)).doc.layers[0].opacity, 1.0);
}
#[test]
@@ -410,6 +457,57 @@ fn transparency_of_objects_and_groups() {
assert_eq!((a[2].opacity, a[2].blend), (1.0, BlendMode::Normal), "the next object's state isn't the group's");
}
#[test]
fn a_gradient_mesh_takes_the_transparency_written_after_it() {
// GUARDS: a mesh's own state (`Xy`) comes right after its `/End X!`, before `Xd` and `XW`, as a
// group's does after `U`; read as the next object's, a Multiply shadow mesh painted opaque.
let corner =
|x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1);
let mesh = |x: i32| {
format!(
"/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n",
corner(x, 0, (x, 10), (x + 10, 0)),
corner(x, 40, (x + 10, 40), (x, 30)),
corner(x + 40, 40, (x + 40, 30), (x + 30, 40)),
corner(x + 40, 0, (x + 30, 0), (x + 40, 10)),
)
};
let art_ = format!(
"0 1 0 0 0 Xy\n{}1 0.8 0 0 0 Xy\n0 0 Xd\n6 () XW\n{}0 0 Xd\n6 () XW\n2 0.7 0 0 0 Xy\n{RED}{}f\n",
mesh(0),
mesh(50),
rect_path(100.0, 0.0, 110.0, 10.0)
);
let doc = read_ok(&layer(&art_)).doc;
let a = art(&doc);
assert!(matches!(a[0].kind, NodeKind::Mesh(_)) && matches!(a[1].kind, NodeKind::Mesh(_)), "{a:#?}");
assert_eq!((a[0].opacity, a[0].blend), (0.8, BlendMode::Multiply), "the state after the mesh is its own");
assert_eq!((a[1].opacity, a[1].blend), (0.8, BlendMode::Multiply), "the next mesh keeps the current state");
assert_eq!((a[2].opacity, a[2].blend), (0.7, BlendMode::Screen), "a state after the mesh's `Xd` and `XW` is the next object's");
}
#[test]
fn a_masked_gradient_mesh_takes_the_transparency_written_after_its_mask() {
// GUARDS: a mesh with an opacity mask has its state after the mask's dictionary, whose art (on
// `%_` lines) has operators of its own; read as the next object's, each masked mesh in a run
// drew with the blend mode of the one before it.
let corners: String = ["10 20 10 25 1 15 20 1", "10 50 15 50 1 10 45 1", "40 50 40 45 1 35 50 1", "40 20 35 20 1 40 25 1"]
.iter()
.map(|g| format!("%_[0.5 1 {g}] /N X#\n"))
.collect();
let mesh = format!("/Mesh X!\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n");
let mask = "%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_u\n%_1 g\n%_10 20 m\n%_10 50 L\n%_40 50 L\n%_40 20 L\n%_f\n%_U\n%_X+\n\
%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n";
let next = format!("0 1 0 0 0 Xy\n{RED}{}f\n", rect_path(60.0, 20.0, 80.0, 40.0));
for (state, expected) in [("1 0.5 0 0 0 Xy\n", (0.5, BlendMode::Multiply)), ("", (1.0, BlendMode::Overlay))] {
let a = art(&read_ok(&layer(&format!("3 1 0 0 0 Xy\n{mesh}{mask}{state}0 0 Xd\n6 () XW\n{next}"))).doc);
assert_eq!(a.len(), 2, "{a:?}");
assert!(matches!(a[0].kind, NodeKind::Mesh(_)) && a[0].extras().mask.is_some(), "{:?}", a[0]);
assert_eq!((a[0].opacity, a[0].blend), expected, "{state:?}: the state after the mask is the mesh's");
assert_eq!((a[1].opacity, a[1].blend), (1.0, BlendMode::Normal), "the next object's own state");
}
}
#[test]
fn gradients() {
let defs = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n<00FF>\n0\n0 0 0 0 1 0 0 2 1 6 %_BS\n\
@@ -1871,6 +1969,33 @@ fn a_blend_it_cant_read_keeps_its_drawn_steps() {
}
}
/// A blend's transparency (here knockout on, as blends are written) is the state block after its
/// record, as a group's follows its end: the live blend's, or its drawn steps' where they stay. It
/// is the blend's own, not the next object's.
#[test]
fn a_blends_transparency_follows_its_record() {
let state = "0 0.6 0 1 0 Xy\n0 0 Xd\n6 () XW\n";
let next = format!("0 1 0 0 0 Xy\n{RED}{}f\n", rect_path(150.0, 40.0, 170.0, 60.0));
let straight = "%_10 50 m\n%_110 50 L\n";
let garbled = "(Adobe Path Blends) 1 0 16 XP\n%00112233445566778899AABBCCDDEEFF\n".to_string();
for (record, live) in [(blend_record(&['A', 'B']), true), (garbled, false)] {
let body = format!("{}{state}{next}", blend_file(straight, [Some("A"), Some("B")], &record));
let a = art(&read_ok(&layer(&body)).doc);
assert_eq!(a.len(), 2, "{a:?}");
assert_eq!(matches!(a[0].kind, NodeKind::Blend { .. }), live, "{:?}", a[0].kind);
assert_eq!((a[0].opacity, a[0].knockout), (0.6, Knockout::On), "live: {live}");
assert_eq!(a[1].opacity, 1.0, "the next object's own state");
}
// A layer whose last object is a blend: a state block that ends `7 () XW` before `LB` is the
// layer's, and the blend keeps the state it had.
let body = format!("{}1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n", blend_file(straight, [Some("A"), Some("B")], &blend_record(&['A', 'B'])));
let doc = read_ok(&layer(&body)).doc;
assert_eq!((doc.layers[0].opacity, doc.layers[0].blend), (0.35, BlendMode::Multiply), "the layer's state");
let a = art(&doc);
assert!(matches!(a[0].kind, NodeKind::Blend { .. }), "{:?}", a[0].kind);
assert_eq!((a[0].opacity, a[0].blend), (1.0, BlendMode::Normal), "the blend's own state");
}
/// The blend is live: moving a key moves the steps between it and the other key with it.
#[test]
fn moving_a_blends_key_moves_its_steps() {
@@ -1900,3 +2025,15 @@ fn a_blend_record_is_read_to_its_length() {
let (blend, warnings) = read_blend(&blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &longer));
assert!(matches!(blend.kind, NodeKind::Blend { .. }), "{warnings:?}");
}
/// The printer's crop marks Illustrator draws after the last layer (`%AI3_BeginCrops`, inside
/// `userdict /AI3_noCropMarks known not { … } if`) aren't art outside the layers: the file reads
/// from its layers, without them (the crop area is `%AI3_Cropmarks`).
#[test]
fn crop_marks_after_the_layers_are_not_art() {
let crops = "%AI3_BeginCrops\nuserdict /AI3_noCropMarks known not {\n0 A\nu\n0 R\n1 1 1 1 ([Registration]) 0 XS\n\
0 J 0 j 0.5 w 4 M []0 d\n0 XR\n-9 -400 m\n-36 -400 L\nS\nU\n} if\n%AI3_EndCrops\n";
let r = read_ok(&format!("{}{crops}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n"))));
assert_eq!(art(&r.doc).len(), 1);
assert_eq!(r.doc.layers.len(), 1);
}
+106 -2
View File
@@ -281,6 +281,8 @@ pub(super) struct Story {
paras: Vec<(usize, Para)>,
/// `(characters, style)` in order.
runs: Vec<(usize, Style)>,
/// Type on a path: the spacing its first frame's layout implies ([`path_spacing`]).
path_spacing: f64,
}
#[derive(Clone, Debug)]
@@ -408,8 +410,11 @@ impl Texts {
return None;
}
// The first frame's layout, when the file keeps one: where its lines start.
let (mut anchor, mut lines) = ((0.0, 0.0), vec![]);
let (mut anchor, mut lines, mut path_spacing) = ((0.0, 0.0), vec![], 0.0);
if let Some(f) = view.get("2").and_then(|l| find_node(l, "F")) {
if matches!(frames.first(), Some(FrameKind::OnPath { .. })) {
path_spacing = self::path_spacing(f);
}
if let Some(a) = f.get("0").and_then(|a| a.get("0")).and_then(Val::nums)
&& let [x, y, ..] = a.as_slice()
{
@@ -441,7 +446,7 @@ impl Texts {
if runs.is_empty() {
runs.push((text.chars().count(), self.style(None)));
}
Some(Story { text, anchor, lines, frames, paras, runs })
Some(Story { text, anchor, lines, frames, paras, runs, path_spacing })
}
/// A paragraph's attributes: its own keys, else the document's.
@@ -572,6 +577,50 @@ fn length_fraction(segments: &[[f64; 8]], t: f64) -> f64 {
((before + within) / total).clamp(0.0, 1.0)
}
/// The spacing (Type on a Path Options › Spacing) that the layout `f` of type on a path implies.
/// The file closes its glyphs up round the outside of a curve and opens them up round the inside,
/// even where its frame keeps no spacing; the text engine spaces glyphs that way by the spacing
/// (`vectorcraft_text`'s `path_steps`): between two glyphs' centres, the path's length `s`, their
/// advances' mean `a` and how far it turns `t` (away from their tops) make `s + t × spacing = a`.
/// Fitted over every pair of the layout's glyphs; none where the path doesn't turn under them.
fn path_spacing(f: &Val) -> f64 {
let mut found = vec![];
find_nodes(f, "G", &mut found);
let (mut sum, mut turns) = (0.0, 0.0);
for g in found {
// Each glyph's origin, its matrix (along its baseline, then towards its foot) and where it
// ends along the line; the lists end with where the line ends.
let Some(at) = g.get("21") else { continue };
let list = |k: &str| at.get(k).and_then(Val::nums).unwrap_or_default();
let (xs, ys, matrices, ends) = (list("1"), list("2"), list("3"), list("4"));
let glyphs: Vec<(Point, f64, kurbo::Vec2, kurbo::Vec2)> = xs
.iter()
.zip(&ys)
.zip(matrices.as_chunks::<6>().0)
.zip(ends.windows(2))
.map(|(((x, y), [a, b, c, d, ..]), e)| {
let advance = e.get(1).zip(e.first()).map_or(0.0, |(e1, e0)| e1 - e0);
let along = kurbo::Vec2::new(*a, *b);
(Point::new(*x, *y) + along * (advance * 0.5), advance, along, kurbo::Vec2::new(*c, *d))
})
.collect();
for w in glyphs.windows(2) {
let [(p, a0, along, foot), (q, a1, next, _)] = w else { continue };
let turn = next.dot(*foot).atan2(next.dot(*along));
// The length of the arc between the centres (the path is taken to be round there). A
// corner (a turn of more than a radian between two glyphs) isn't round: left out.
let half = turn.abs() * 0.5;
let length = if half > 1e-9 { (*q - *p).hypot() * half / half.sin() } else { (*q - *p).hypot() };
if turn.abs() <= 1.0 && length.is_finite() && a0.is_finite() && a1.is_finite() {
sum += ((a0 + a1) * 0.5 - length) * turn;
turns += turn * turn;
}
}
}
let spacing = sum / turns;
if turns > 1e-6 && spacing.is_finite() { spacing.clamp(-1000.0, 1000.0) } else { 0.0 }
}
impl Story {
/// How many bytes of text the story has.
pub(super) fn len(&self) -> usize {
@@ -711,6 +760,9 @@ impl Story {
if paras.len() > 1 && paras.iter().any(|p| *p != t.para) {
t.paras = paras;
}
if matches!(kind, TextKind::OnPath { .. }) && !threaded {
t.path_spacing = self.path_spacing * scale;
}
t.kind = kind;
t.xf = xf;
Some(Node::new(id, NodeKind::Text(Box::new(t))))
@@ -1015,9 +1067,61 @@ mod tests {
caps: 0,
},
)],
path_spacing: 0.0,
}
}
/// A layout of glyphs `advances` wide round a circle of radius `radius` (y down), from its left,
/// outside it (their feet towards its centre) or inside it, the length of the circle between
/// their centres `fraction` of their advances' mean.
fn round_layout(advances: &[f64], radius: f64, outside: bool, fraction: f64) -> Val {
let sign = if outside { 1.0 } else { -1.0 };
let (mut xs, mut ys, mut matrices, mut ends) = (vec![], vec![], vec![], vec![0.0]);
let mut angle = std::f64::consts::PI;
for (i, a) in advances.iter().enumerate() {
if i > 0 {
angle += sign * (advances[i - 1] + a) * 0.5 * fraction / radius;
}
// Outside, clockwise on the page (y down); inside, the other way round.
let along = (-angle.sin() * sign, angle.cos() * sign);
let centre = (radius * angle.cos(), radius * angle.sin());
xs.push(centre.0 - along.0 * a * 0.5);
ys.push(centre.1 - along.1 * a * 0.5);
matrices.extend([along.0, along.1, -along.1, along.0, 0.0, 0.0]);
ends.push(ends[i] + a);
}
let nums = |v: &[f64]| v.iter().map(|n| format!("{n}")).collect::<Vec<_>>().join(" ");
let doc = format!(
"/0 << /99 /F /6 [ << /99 /L /6 [ << /99 /S /6 [ << /99 /G /21 << /1 [ {} ] /2 [ {} ] /3 [ {} ] /4 [ {} ] >> >> ] >> ] >> ] >>",
nums(&xs),
nums(&ys),
nums(&matrices),
nums(&ends)
);
read(doc.as_bytes()).unwrap().get("0").unwrap().clone()
}
/// The file lays type on a path out closer round the outside of a curve and further apart round
/// the inside: the spacing that does that is read from its layout, as the text engine's model
/// has it (length + turn × spacing = advance).
#[test]
fn the_layout_of_type_on_a_path_gives_its_spacing() {
let advances = [20.0, 30.0, 10.0, 25.0, 20.0];
// Outside a circle of radius 100, 10 above the path: the centres are 100/110 of the advances apart.
let spacing = path_spacing(&round_layout(&advances, 100.0, true, 100.0 / 110.0));
assert!((spacing - 10.0).abs() < 1e-6, "{spacing}");
// Inside it, 20 above the path: 100/80 of them.
let spacing = path_spacing(&round_layout(&advances, 100.0, false, 100.0 / 80.0));
assert!((spacing - 20.0).abs() < 1e-6, "{spacing}");
// At their advances: none.
assert!(path_spacing(&round_layout(&advances, 100.0, true, 1.0)).abs() < 1e-6);
// Corners (here a turn of about four radians from glyph to glyph) aren't taken for a curve.
assert_eq!(path_spacing(&round_layout(&advances, 5.0, true, 1.0)), 0.0);
// A straight line turns nowhere, and a layout without glyphs says nothing.
assert_eq!(path_spacing(&round_layout(&advances, 1e12, true, 0.9)), 0.0);
assert_eq!(path_spacing(&read(b"/99 /F").unwrap()), 0.0);
}
/// The leading of the text object a story comes in as.
fn leading_of(story: &Story) -> Option<f64> {
let node = story.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY)?;
+162 -9
View File
@@ -1,8 +1,8 @@
use super::compare::{MAX_DIFFERENCE, PageView, compare};
use super::compare::{MAX_DIFFERENCE, PageView, compare, difference};
use super::plan::plan;
use super::slots::{
ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots,
text_objects,
letters, text_objects, words,
};
use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai};
@@ -85,6 +85,10 @@ pub(super) fn build_from(
// scale, which `to_doc` carries, so its art and the page reach the same size (#2031).
let fits = |r: &Rect| (r.width() - page_rect.width()).abs() <= 0.5 && (r.height() - page_rect.height()).abs() <= 0.5;
let mut rect = to_doc.transform_rect_bbox(art_box);
// A PDF saved with some of its artboards has pages for those only, the first of them not
// always the first artboard: the editing data keeps them all (`first`, the page's).
let first = shown_artboard(&doc, visible, page, page_rect, fits);
rect = doc.artboards.get(first).filter(|_| first > 0).map_or(rect, |a| a.rect);
// A `.ai` whose PDF part's pages are cropped to its art (each page the box of all of it,
// the editing data's bounding box) rather than to its artboards: the layers are compared
// with the page on that box, and keep their artboards. Each page then holds all the art
@@ -127,9 +131,7 @@ pub(super) fn build_from(
// A `.ai` read as its PDF part has a page for each artboard, in a row: the type on each
// goes where the layers have that artboard.
let pages: Vec<Rect> = visible.artboards.iter().map(|a| a.rect).collect();
let same =
|(a, p): (&vectorcraft_doc::Artboard, &Rect)| (a.rect.width() - p.width()).abs() <= 0.5 && (a.rect.height() - p.height()).abs() <= 0.5;
let boards = (pages.len() == doc.artboards.len() && doc.artboards.iter().zip(&pages).all(same)).then_some(&doc.artboards);
let boards = page_boards(&doc.artboards, first, &pages);
// The page with most of an object, the first for what is on none.
let page_of = |object: &[Arc<Node>]| {
extent(object).and_then(|r| {
@@ -178,9 +180,9 @@ pub(super) fn build_from(
if outlined && infos.iter().any(|i| i.shown) {
return Err("its type is to come in as outlines, which only its page has".into());
}
if infos.iter().all(|i| !i.shown) && !shown.is_empty() {
return Err("its page has text, and its layers have no text objects to put it in".into());
}
// The page's type that needs no text object of the layers: the layers' own legacy text, or
// placed files that show it.
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
// The page's type is compared with every text object of the layers: that has its limits.
if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS {
return Err("it has too many text objects".into());
@@ -228,6 +230,9 @@ pub(super) fn build_from(
if short > 0 {
notes.push(format!("{short} {PAGE_TYPE_WITHOUT_OUTLINES}"));
}
if as_outlines > 0 {
notes.push(format!("{as_outlines} {PAGE_TYPE_AS_OUTLINES}"));
}
if !hidden_unread.is_empty() {
notes.push(format!("{ART_LEFT_OUT} ({}), left out of them", few(hidden_unread)));
}
@@ -242,7 +247,22 @@ pub(super) fn build_from(
let unseen = prune_unseen(&frame, &mut view, &mut doc);
let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}"));
match compare(&frame, &mut view, &doc) {
Ok(note) => notes.extend(unseen_note(unseen).into_iter().chain(note)),
// Placed files at the other point their data gives, where that draws closer to the
// page: a small image in the wrong place differs too little to fail.
Ok(note) => {
let closer = other.and_then(|mut other| {
let unseen = prune_unseen(&frame, &mut view, &mut other);
let closer = view.difference(&other, frame.rect).any < view.difference(&doc, frame.rect).any;
closer.then(|| compare(&frame, &mut view, &other).ok()).flatten().map(|note| (other, unseen, note))
});
match closer {
Some((other, unseen, note)) => {
doc = other;
notes.extend(unseen_note(unseen).into_iter().chain(note));
}
None => notes.extend(unseen_note(unseen).into_iter().chain(note)),
}
}
// Placed files at the other point their data gives, where that draws as the page.
Err(why) => match other.map(|mut other| {
let unseen = prune_unseen(&frame, &mut view, &mut other);
@@ -284,12 +304,108 @@ fn elsewhere(doc: &Document, placed: &[(NodeId, Affine)]) -> Option<Document> {
Some(doc)
}
/// The page's type that needs no text object of the layers, taken out of `shown` and `hidden` (the
/// page's text objects that show and that don't): how many of them the layers have as outlines.
/// Type in the legacy format (`To` … `TO`, as files saved for Illustrator 10 and earlier keep it)
/// is read as text objects of the layers' own, with no slot (`no_slots`) for the page's type; the
/// page's type that their words don't hold is outlines on the layers, and the comparison with the
/// page says whether they draw it. Without such text and with no slot that shows (`none_shown`),
/// the page's type must all lie inside placed files, which show it.
fn page_type_elsewhere(
no_slots: bool,
none_shown: bool,
shown: &mut Vec<Vec<Arc<Node>>>,
hidden: &mut Vec<Vec<Arc<Node>>>,
doc: &Document,
placed: &[(NodeId, Affine)],
) -> Result<usize, String> {
let mut own = vec![];
own_text(&doc.layers, &mut own);
let mut as_outlines = 0;
if no_slots && !own.is_empty() {
as_outlines = shown.iter().filter(|o| !in_own_text(o, &own)).count();
shown.clear();
hidden.clear();
}
if none_shown && !shown.is_empty() && own.is_empty() {
if !in_placed_files(shown, doc, placed) {
return Err("its page has text, and its layers have no text objects to put it in".into());
}
// The page's type is all inside placed files: it is theirs, which their previews show, and
// needs no text object.
shown.clear();
}
Ok(as_outlines)
}
/// Is the page's text object `object` the layers' own text (`own`, from [`own_text`]): one with its
/// words next to it? The rest of the page's type is what the editing data keeps as outlines (what
/// the legacy format can't hold), and the comparison with the page says whether the layers draw it.
fn in_own_text(object: &[Arc<Node>], own: &[(Rect, String)]) -> bool {
let Some(r) = extent(object) else { return false };
let near: String =
own.iter().filter(|(b, _)| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(r).is_zero_area()).map(|(_, l)| l.as_str()).collect();
let page_words: Vec<String> = object
.iter()
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_lowercase())) } else { None })
.flatten()
.collect();
!near.is_empty() && page_words.iter().all(|w| near.contains(w.as_str()))
}
/// The text objects of their own (not slots for the page's type) that show in `nodes`: their
/// bounds and their letters, in lower case.
fn own_text(nodes: &[Arc<Node>], out: &mut Vec<(Rect, String)>) {
for n in nodes.iter().filter(|n| n.visible) {
match &n.kind {
NodeKind::Text(t) => out.extend(n.visual_bounds().map(|b| (b, letters(&t.plain_text().to_lowercase())))),
NodeKind::Compound { .. } => {}
_ => {
if let Some(c) = n.children() {
own_text(c, out);
}
}
}
}
}
/// Has `r` the size of `page`'s first artboard (in points)?
fn same_size(r: Option<Rect>, page: &Document) -> bool {
let (Some(r), Some(p)) = (r, page.artboards.first().map(|a| a.rect)) else { return false };
(r.width() - p.width()).abs() <= 0.5 && (r.height() - p.height()).abs() <= 0.5
}
/// Does all of `objects` (the page's text objects) lie inside placed files that show in `doc`? The
/// page draws a placed file, type and all, where the layers show its preview (a linked image, see
/// `ai::Reader::end_place`), at its first placement or at the other one that `placed` lists (see
/// [`elsewhere`]).
fn in_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(NodeId, Affine)]) -> bool {
let inside = |d: &Document| {
let mut files = vec![];
placed_files(&d.layers, &mut files);
!files.is_empty()
&& objects
.iter()
.all(|o| extent(o).is_some_and(|r| files.iter().any(|f: &Rect| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r))))
};
inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other))
}
/// Where the placed files that show in `nodes` are: the linked images the editing data's reader
/// makes of them.
fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) {
for n in nodes.iter().filter(|n| n.visible) {
match &n.kind {
NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()),
_ => {
if let Some(c) = n.children() {
placed_files(c, out);
}
}
}
}
}
/// Does the editing data's first artboard `board` (in the document read from it: art space through
/// `to_doc`) have the size of `page`'s first artboard in units of `unit` points, `unit` being above
/// 1, and not its size in points? `page` is a PDF part read in points from pages of `unit` points a
@@ -300,6 +416,40 @@ fn in_units(board: Option<Rect>, page: &Document, unit: f64) -> bool {
unit.is_finite() && unit > 1.0 && fits(unit) && !fits(1.0)
}
/// The most artboards [`shown_artboard`] weighs, a render each.
const MAX_BOARDS_WEIGHED: usize = 16;
/// Which of the artboards of `doc` (the layers' document) the page `page_rect` of `visible` shows,
/// when `visible` has fewer pages than `doc` has artboards (a PDF saved with a range of them): of
/// those of the page's size (`fits`), the one whose art draws most like the page, the first of
/// them on a tie. Else (and for an EPS, whose page is its art) the first artboard (0).
fn shown_artboard(doc: &Document, visible: &Document, page: Page, page_rect: Rect, fits: impl Fn(&Rect) -> bool) -> usize {
if matches!(page, Page::Art) || visible.artboards.len() >= doc.artboards.len() {
return 0;
}
let sized: Vec<usize> = doc.artboards.iter().enumerate().filter(|(_, a)| fits(&a.rect)).map(|(i, _)| i).take(MAX_BOARDS_WEIGHED).collect();
if let [only] = sized.as_slice() {
return *only;
}
let mut best: Option<(usize, f64)> = None;
for (i, a) in sized.iter().filter_map(|&i| Some((i, doc.artboards.get(i)?))) {
let d = difference(visible, page_rect, doc, a.rect).any;
if best.is_none_or(|(_, b)| d < b) {
best = Some((i, d));
}
}
best.map_or(0, |(i, _)| i)
}
/// The artboards of the layers' document (`boards`) that the pages show, one a page from the
/// first page's (`first`), when they are the pages' sizes: every artboard, or those of a PDF saved
/// with some of them (`first` after the first artboard).
fn page_boards<'a>(boards: &'a [vectorcraft_doc::Artboard], first: usize, pages: &[Rect]) -> Option<&'a [vectorcraft_doc::Artboard]> {
let same = |(a, p): (&vectorcraft_doc::Artboard, &Rect)| (a.rect.width() - p.width()).abs() <= 0.5 && (a.rect.height() - p.height()).abs() <= 0.5;
let shown = boards.get(first..first.saturating_add(pages.len()))?;
((first > 0 || pages.len() == boards.len()) && shown.iter().zip(pages).all(same)).then_some(shown)
}
/// Draw `doc`'s layers and artboards `k` times as large, from the origin, with their strokes,
/// effects and pattern tiles.
fn scale_document(doc: &mut Document, k: f64) {
@@ -327,6 +477,9 @@ const UNSEEN_TEXT: &str = "text objects that the file keeps but its page doesn't
/// left out.
const PAGE_TYPE_WITHOUT_OUTLINES: &str = "text objects hold their type as the page draws it, without the characters the page has only as outlines";
/// The page's text objects that the layers have as outlines, as the editing data keeps them.
const PAGE_TYPE_AS_OUTLINES: &str = "text objects of the page are outlines on the layers, as the file's editing data keeps them";
/// How much more of the page (0 to 1) the layers may differ without a text object and still look no worse.
const UNSEEN_MARGIN: f64 = 5e-5;
+211
View File
@@ -192,6 +192,33 @@ fn text_and_its_strokes_come_from_the_page_into_the_layer_of_its_text_object() {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
/// A point type object in the legacy format (`To` … `TO`), as an EPS saved for Illustrator 10
/// keeps its type in the editing data: no `/AI11Text` for the page's type to go in.
fn legacy_text(x: u32, y: u32, text: &str) -> String {
format!("0 To\n1 0 0 1 {x} {y} 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n({text}) Tx\nTO")
}
#[test]
fn type_in_the_legacy_format_is_the_layers_own_and_the_page_has_text() {
let page = format!("{}\n0 0 0 1 setcmykcolor /Helvetica findfont 12 scalefont setfont 10 50 moveto (Hi) show", page_square(10, 10));
let art = native(&(layer("Art", true, &square(10, 10)) + &layer("Words", true, &legacy_text(10, 50, "Hi"))));
let r = import(&eps(&page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art", "Words"], "{:?}", r.warnings);
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
assert_eq!(texts[0].plain_text(), "Hi");
assert!(!r.warnings.iter().any(|w| w.contains("left out") || w.contains("weren't read")), "{:?}", r.warnings);
// Type the editing data keeps as outlines (here a stand-in, a small square where the page has
// more type) comes in as they are, and the import says so.
let page = format!("{page}\n/Helvetica findfont 4 scalefont setfont 60 20 moveto (o) show");
let outlines = format!("{}\n0 0 0 1 k\n60.5 20 m\n62.5 20 L\n62.5 22 L\n60.5 22 L\nf", legacy_text(10, 50, "Hi"));
let art = native(&(layer("Art", true, &square(10, 10)) + &layer("Words", true, &outlines)));
let r = import(&eps(&page, &art)).unwrap();
assert_eq!(names(&r.document), ["Art", "Words"], "{:?}", r.warnings);
assert_eq!(kinds(&r.document.layers[1]), ["text", "path"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.starts_with("1 text objects of the page are outlines on the layers")), "{:?}", r.warnings);
}
#[test]
fn a_damaged_editing_copy_leaves_the_page() {
// Not ASCII85, ASCII85 of something that isn't Zstandard, Zstandard of something that isn't art.
@@ -266,6 +293,57 @@ fn an_ai_file_with_an_image_too_large_for_its_editing_data_comes_in_as_its_pdf_p
assert!(read, "{warnings:?}");
}
/// A `.ai` whose layers hold a placed PDF and no text object: its PDF part draws the placed file,
/// type and all, where the layers show the file's preview. That type is the placed file's and needs
/// no text object, so the file comes in from its layers, the placed file where its matrix takes the
/// canvas point of art space's origin or at the corner of its box (see
/// `a_placed_file_at_its_boxs_corner_matches_the_page`). Type outside the placed file still needs
/// one, and without it the file comes in as its PDF part.
#[test]
fn type_of_the_page_inside_a_placed_file_needs_no_text_object() {
// A file placed on (30, 30)–(70, 70) whose preview is 2 × 2 pixels of half-transparent black,
// as in `a_placed_file_at_its_boxs_corner_matches_the_page`; with the template box, the canvas
// point of art space's origin puts it off the page, and the box's corner on it.
let place = format!(
"%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -7970 8070] 8000 8000 8040 8040 4 4 0\n(/files/pages.pdf)`\n\
%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n",
"\x7f\0\0\0".repeat(4)
);
let at_origin = native(&layer("Pages", true, &place));
let at_corner = at_origin.replace("%AI5_NumLayers", "%AI3_TemplateBox: 100 50 100 50\n%AI5_NumLayers");
// The PDF part: the placed file's page in 50% grey, and type at (`x`, 55).
let pdf = |x: f64| {
let mut d = Document::new(100.0, 100.0);
let grey = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::gray(0.5)));
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0));
let page = Node::path(
d.alloc_id(),
rect,
vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(grey)], ..Default::default() },
);
let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(x, 55.0), "Hi", style);
let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(text)));
let layer = d.layers[0].id;
d.insert(Some(layer), 0, page).unwrap();
d.insert(Some(layer), 1, text).unwrap();
d
};
for data in [&at_origin, &at_corner] {
let (d, warnings, read) = crate::layered_ai(&private(data), pdf(38.0), vec![], false, false, 1.0);
assert!(read, "{warnings:?}");
assert_eq!(names(&d), ["Pages"]);
let mut links = vec![];
d.visit_images(|_, im| links.extend(im.link.as_ref().map(|l| l.path.clone())));
assert_eq!(links, ["/files/pages.pdf"], "{warnings:?}");
assert!(warnings.iter().all(|w| !w.contains("no text object")), "the type is the placed file's, not left out: {warnings:?}");
// Type beside the placed file is a text object's, which the layers don't have.
let (_, warnings, read) = crate::layered_ai(&private(data), pdf(5.0), vec![], false, false, 1.0);
assert!(!read, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("its layers have no text objects")), "{warnings:?}");
}
}
/// A palette of `[None]` and White, and a color group `Inks` holding a spot color, Red ink.
const PALETTE: &str =
"%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n1 (Inks) 1 Pg\n0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\nPB\n%AI5_EndPalette\n";
@@ -422,6 +500,36 @@ fn type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once() {
assert!((e - 30.0).abs() < 1e-6 && (f + 10.0).abs() < 1e-6, "{:?}", texts[0].xf);
}
/// A PDF saved with only the second of its two artboards has a page for that one, while its
/// editing data keeps both: the layers are compared with the page on that artboard, and the page's
/// type goes there.
#[test]
fn a_pdf_of_its_second_artboard_is_compared_on_that_artboard() {
// Two 100-point artboards side by side, 50 apart (art space, y up), a square on each, and a
// text object with no story in the file.
let board = |x0: i32| {
format!(
"%_/Dictionary :\n%_{x0} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n",
x0 + 100
)
};
let boards = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", board(0), board(150));
let art = native(&(boards + &layer("Art", true, &(square(10, 10) + "\n" + &square(180, 50) + "\n" + &text_object(0)))));
// The page: the second artboard, its square 30 from the left and 46 down, and the type.
let mut pdf = pdf_part(30.0, 46.0);
let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(40.0, 20.0), "Hi", style);
let (layer_id, id) = (pdf.layers[0].id, pdf.alloc_id());
pdf.insert(Some(layer_id), 1, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0);
assert!(read, "{w:?}");
assert_eq!(d.artboards.len(), 2, "both artboards are kept");
let texts = text_of(&d.layers[0]);
assert_eq!(texts.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Hi"], "{w:?}");
let [.., e, f] = texts[0].xf.as_coeffs();
assert!((e - 190.0).abs() < 1e-6 && (f - 20.0).abs() < 1e-6, "on the second artboard: {:?}", texts[0].xf);
}
#[test]
fn an_ai_file_that_cant_be_read_through_its_editing_data_keeps_its_pdf_part() {
let pdf = pdf_part(10.0, 86.0);
@@ -1439,6 +1547,84 @@ fn area_type_and_type_on_a_path_come_from_the_text_document() {
assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
}
/// A story of `text` on frame 0 whose layout sets glyphs `advance` wide round the outside of a
/// circle of radius `radius`, the circle's length between their centres `fraction` of an advance.
fn round_story(text: &str, advance: f64, radius: f64, fraction: f64) -> String {
let n = text.chars().count();
let (mut xs, mut ys, mut matrices, mut ends) = (vec![], vec![], vec![], vec![]);
for i in 0..=n {
// From the circle's left, clockwise on the canvas (y down), feet towards its centre.
let angle = std::f64::consts::PI + i as f64 * advance * fraction / radius;
let along = (-angle.sin(), angle.cos());
xs.push(radius * angle.cos() - along.0 * advance * 0.5);
ys.push(radius * angle.sin() - along.1 * advance * 0.5);
matrices.push(format!("{} {} {} {} 0 0", along.0, along.1, -along.1, along.0));
ends.push(i as f64 * advance);
}
let nums = |v: &[f64]| v.iter().map(|x| format!("{x}")).collect::<Vec<_>>().join(" ");
format!(
"<< /0 << /0 ({text}) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 12.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 0 >> ] \
/2 [ << /99 /PC /6 [ << /99 /F /6 [ << /99 /L /6 [ << /99 /S /6 [ << /99 /G /21 << /1 [ {} ] /2 [ {} ] /3 [ {} ] /4 [ {} ] >> >> ] >> ] >> ] >> ] >> ] >> >>",
nums(&xs),
nums(&ys),
matrices.join(" "),
nums(&ends)
)
}
/// The file closes type up round the outside of a curve (its layout puts the glyphs' centres
/// closer than their advances), though the frame has no spacing of its own: the type comes in
/// spaced as the layout is, not at its advances, so it doesn't run on past where the page ends it.
#[test]
fn type_round_a_circle_is_spaced_as_the_file_lays_it_out() {
// A circle of radius 40 round the middle of the page, in four cubics from its right, clockwise
// on the page; the type from its left, over the top, round almost all of it.
let k = 40.0 * 0.552_284_75;
let points = [
(90.0, 50.0),
(90.0, 50.0 - k),
(50.0 + k, 10.0),
(50.0, 10.0),
(50.0 - k, 10.0),
(10.0, 50.0 - k),
(10.0, 50.0),
(10.0, 50.0 + k),
(50.0 - k, 90.0),
(50.0, 90.0),
(50.0 + k, 90.0),
(90.0, 50.0 + k),
(90.0, 50.0),
];
let all: Vec<(f64, f64)> = points.iter().map(|(x, y)| canvas(*x, *y)).collect();
let segment = |i: usize| (0..4).map(|j| format!("{} {}", all[i * 3 + j].0, all[i * 3 + j].1)).collect::<Vec<_>>().join(" ");
let frame =
format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 2 /6 [ 2.0 5.99 ] >> >> >>", (0..4).map(segment).collect::<Vec<_>>().join(" "));
// Glyphs 5 apart, their centres 5 × 40/48 apart round the circle: spaced 8 above the path.
let doc = document_of(&[frame], &[round_story("abcdefgh", 5.0, 40.0, 40.0 / 48.0)]);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
let t = texts[0];
assert!(matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }), "{:?}", t.kind);
assert!((t.path_spacing - 8.0).abs() < 0.05, "{}", t.path_spacing);
// Laid out, the glyphs' centres are 40/48 of their advances apart round the circle.
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let centres: Vec<(f64, f64)> = layout
.glyphs
.iter()
.map(|g| (g.origin.x + g.angle.cos() * g.advance * 0.5 - 50.0, g.origin.y + g.angle.sin() * g.advance * 0.5 - 50.0, g.advance))
.map(|(x, y, a)| (y.atan2(x), a))
.collect();
assert_eq!(centres.len(), 8);
for w in centres.windows(2) {
let turn = (w[1].0 - w[0].0 + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;
let ratio = turn.abs() * 40.0 / ((w[0].1 + w[1].1) * 0.5);
assert!((ratio - 40.0 / 48.0).abs() < 0.01, "{ratio}");
}
}
#[test]
fn threaded_area_type_flows_through_its_frames() {
let frames = [
@@ -1677,6 +1863,31 @@ fn a_placed_file_at_its_boxs_corner_matches_the_page() {
assert!([b.x0 - 30.0, b.y0 - 30.0, b.x1 - 70.0, b.y1 - 70.0].iter().all(|v| v.abs() < 0.01), "on the page's square: {b:?}");
}
#[test]
fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() {
// A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to
// (30, 30)–(32, 32), as the page draws it. The template box's canvas point puts it at
// (10, 10)–(12, 12): on the page too, and small enough that the layers pass the comparison
// there all the same.
let place = format!(
"%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -7970 8070] 8000 8000 8002 8002 4 4 0\n(logo.png)`\n\
%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n",
"\x7f\0\0\0".repeat(4)
);
let data = native(&layer("Jig", true, &place)).replace("%AI5_NumLayers", "%AI3_TemplateBox: 211.5 -211.5 211.5 -211.5\n%AI5_NumLayers");
let mut page = Document::new(100.0, 100.0);
let id = page.alloc_id();
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(30.0, 30.0, 32.0, 32.0));
let grey = vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::gray(0.5)));
let n = Node::path(id, path, vectorcraft_doc::Appearance { items: vec![vectorcraft_doc::AppearanceItem::Fill(grey)], ..Default::default() });
let l = page.layers[0].id;
page.insert(Some(l), 0, n).unwrap();
let (d, w, read) = crate::layered_ai(&private(&data), page, vec![], false, false, 1.0);
assert!(read, "{w:?}");
let b = d.layers[0].children().unwrap()[0].geometric_bounds().unwrap();
assert!([b.x0 - 30.0, b.y0 - 30.0, b.x1 - 32.0, b.y1 - 32.0].iter().all(|v| v.abs() < 0.01), "on the page's square: {b:?}");
}
#[test]
fn text_a_placed_file_covers_only_at_its_first_placement_is_kept() {
const OPAQUE: &str = "<opaque>";
+21
View File
@@ -171,6 +171,27 @@ fn rich_document_roundtrips() {
assert_eq!(v["version"], vectorcraft_format::VERSION);
}
/// A file's Path Effects are its own business: whatever their parameters hold, they load and save
/// as they are (the engine's tests draw them).
#[test]
fn path_effects_with_junk_params_round_trip() {
let mut d = rich_doc();
let mut id = None;
d.walk(|n| id = id.or(n.path_data().map(|_| n.id)));
let id = id.unwrap();
let effects: Vec<vectorcraft_doc::Effect> = [
("addon.path.dashes", json!({"dash1": 1e308, "gap1": -1e308, "offset": "x", "alignCorners": 3})),
("addon.path.addAnchors", json!({"count": 1e308, "maxCount": 1e308, "distance": -1e308, "spacing": "distance", "target": []})),
("addon.path.extend", json!(null)),
]
.into_iter()
.map(|(id, params)| vectorcraft_doc::Effect { id: id.into(), params, visible: true })
.collect();
d.node_mut(id).unwrap().appearance.effects = effects.clone();
let back = load(&save(&d, true)).unwrap();
assert_eq!(back.node(id).unwrap().appearance.effects, effects);
}
#[test]
fn sniff_distinguishes_formats() {
assert!(sniff(&save(&Document::new(1.0, 1.0), false)));
+3 -1
View File
@@ -192,7 +192,9 @@ impl Headless {
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base);
let ev = PointerEvent { kind, pos: Point::new(x, y), mods, pressure: PointerEvent::json_pressure(e) };
let backquote =
e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false));
let ev = PointerEvent { kind, pos: Point::new(x, y), mods, backquote, pressure: PointerEvent::json_pressure(e) };
let reqs = self.session.pointer(&ev, self.view).map_err(|e| e.to_string())?;
self.apply_ui_requests(reqs, &mut requests)?;
// With no frames to show the highlight in later, a hover waits for the work the tool
+24
View File
@@ -1398,6 +1398,30 @@ fn selection_preferences_apply_to_pointer_gestures() {
assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does");
}
#[test]
fn pointer_gesture_forwards_backquote_on_each_event() {
let mut s = server();
let made = call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 50, "height": 50, "fill": "#ff0000"}));
let id = serde_json::from_str::<Value>(&text_of(&made)).unwrap()["id"].as_u64().unwrap();
let selected = call(&mut s, 2, "run_command", json!({"command": "select.set", "params": {"ids": [id]}}));
assert_eq!(selected["isError"], false, "{selected}");
let drag = call(
&mut s,
3,
"pointer_gesture",
json!({"tool": "selection", "backquote": true, "events": [
{"kind": "down", "x": 125, "y": 125},
{"kind": "drag", "x": 145, "y": 125},
{"kind": "up", "x": 145, "y": 125}
]}),
);
assert_eq!(drag["isError"], false, "{drag}");
let inspected = call(&mut s, 4, "inspect_document", json!({}));
let doc = serde_json::from_str::<Value>(&text_of(&inspected)).unwrap();
let rect = doc["layers"][0]["children"].as_array().unwrap().iter().find(|n| n["id"] == id).unwrap();
assert_eq!(rect["bounds"]["x"], 100.0, "{doc}");
}
/// A Shift-drag marquee reaches agents (#483): `pointer_gesture` with `mods.shift` toggles the
/// objects it reaches, so a selected one leaves the selection and an unselected one joins it.
#[test]
+2
View File
@@ -209,11 +209,13 @@ pub fn tool_definitions() -> Vec<Value> {
"x": num("Document x (pt)"),
"y": num("Document y (pt)"),
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Backquote held for this event: Selection and transform tool drags transform only pattern paint"},
"pressure": num("Pen pressure 0..1 (default 1): the Liquify tools' intensity with Use Pressure Pen on"),
"holdMs": num("Milliseconds the pointer then holds still, button down (0..60000): Twirl, Pucker and Bloat keep applying"),
}), &["kind", "x", "y"]),
},
"mods": mods_schema(),
"backquote": {"type": "boolean", "description": "Default backquote held state for events: Selection and transform tool drags transform only pattern paint"},
}),
&["events"],
),
+3
View File
@@ -141,6 +141,9 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<ToolResult, Str
if let Some(m) = a.get("mods") {
p["mods"] = m.clone();
}
if let Some(backquote) = a.get("backquote") {
p["backquote"] = backquote.clone();
}
j(b.call("ui.pointer", p)?)
}
"draw_path" => j(draw_path(b, a)?),
+3 -2
View File
@@ -5,7 +5,8 @@
//! - [`cleanup`]: Artwork Cleanup's path repairs (collinear, duplicate and near anchors, tiny
//! handles, nearly closed paths) and Rejoin Path Pieces.
//! - [`pathtools`]: Path Precision Tools' anchor edits, path readouts, extending open paths,
//! finding where paths cross and the Parametric Shape Tool's re-editable shapes.
//! finding where paths cross, sliding anchors along their path, merging touching edges and the
//! Parametric Shape Tool's re-editable shapes.
//! - [`segment_reshape`]: bending a segment by dragging a point on it (shared by the tools that
//! reshape segments directly).
//! - [`pen`]: the Smart Pen's straight and curved segments and its point edits.
@@ -19,5 +20,5 @@ pub mod segment_reshape;
pub use cleanup::{
Rejoined, close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles,
};
pub use keep_shape::{SHARP_CORNER_DEG, remove_anchor_keep_shape, simplify_anchors_keep_shape, simplify_keep_shape};
pub use keep_shape::{PT_PER_TOLERANCE, SHARP_CORNER_DEG, remove_anchor_keep_shape, simplify_anchors_keep_shape, simplify_keep_shape};
pub use segment_reshape::{ReshapeMode, reshape_segment};
+3
View File
@@ -13,6 +13,9 @@ use crate::fit::{end_tangent, start_tangent};
/// The turn (degrees) at an anchor above which `protect_corners` keeps it.
pub const SHARP_CORNER_DEG: f64 = 30.0;
/// The drift (pt) each step of the tolerance the add-ons offer allows.
pub const PT_PER_TOLERANCE: f64 = 0.02;
/// Points sampled along each curve to measure how far two outlines are apart.
const SAMPLES: usize = 8;
+75 -4
View File
@@ -1,21 +1,29 @@
//! Path Precision Tools' geometry: anchor edits for the Anchor Inspector (smooth by the auto-smooth
//! rule, equalise handles, add evenly spaced anchors, close), the readouts the Measure & Inspect
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]) and the places
//! where paths cross ([`crossings`]), and the Parametric Shape Tool's shapes ([`shapes`]).
//! rule, equalise handles, add evenly spaced anchors, close), what its live path effects add to them
//! ([`add_anchors`], [`smooth_anchors`], [`split_at_anchors`]), the readouts the Measure & Inspect
//! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places
//! where paths cross ([`crossings`]), anchors slid along their path ([`slide`]), touching edges
//! merged ([`shared_edge`]) and the Parametric Shape Tool's shapes ([`shapes`]).
mod crossings;
mod extend;
pub mod shapes;
mod shared_edge;
mod slide;
#[cfg(test)]
mod tests;
use std::collections::BTreeSet;
use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2};
use vectorcraft_geom::{AnchorKind, PathData, SubPath};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
pub use crossings::{MAX_CROSSING_SEGMENTS, crossings, insert_at};
pub use extend::{ExtendMode, extend_length_to, extend_open};
pub use shared_edge::{
COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at,
};
pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at};
use crate::fit::{end_tangent, start_tangent};
@@ -148,6 +156,69 @@ pub fn add_points(sp: &SubPath, segments: Option<&BTreeSet<usize>>, count: usize
insert_at(sp, &hits)
}
/// The segments [`add_anchors`] adds to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SegmentKind {
All,
Curved,
Straight,
}
/// How [`add_anchors`] spaces its anchors along a segment.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnchorSpacing {
/// This many, evenly spaced by length.
Count(usize),
/// One every this many points from the segment's start, none on its end.
Distance(f64),
}
/// `sp` with anchors added on the segments `which` picks, spaced as `spacing` says and at most `cap`
/// on one segment; the shape doesn't change. `None` when that would add more than `room` anchors.
pub fn add_anchors(sp: &SubPath, which: SegmentKind, spacing: AnchorSpacing, cap: usize, mut room: usize) -> Option<SubPath> {
let mut hits = vec![];
for seg in 0..sp.segment_count() {
let picked = match which {
SegmentKind::All => true,
SegmentKind::Curved => !sp.segment_is_line(seg),
SegmentKind::Straight => sp.segment_is_line(seg),
};
let c = sp.segment(seg);
let len = c.arclen(ACCURACY);
if !picked || !(len > TINY && len.is_finite()) {
continue;
}
let (count, step) = match spacing {
AnchorSpacing::Count(n) => (n, len / (n as f64 + 1.0)),
AnchorSpacing::Distance(d) if d > 0.0 => (((len / d).ceil() as usize).saturating_sub(1), d),
AnchorSpacing::Distance(_) => (0, 0.0),
};
let count = count.min(cap);
room = room.checked_sub(count)?;
hits.extend((1..=count).map(|k| (seg, c.inv_arclen(step * k as f64, ACCURACY))));
}
Some(insert_at(sp, &hits).0)
}
/// Make every anchor of `sp` smooth by the auto-smooth rule ([`auto_smooth`]). An open path's ends
/// come last, so each aims at the handle its neighbour ended up with, whichever way the path runs.
pub fn smooth_anchors(sp: &mut SubPath, ratio: f64) {
let (n, closed) = (sp.anchors.len(), sp.closed);
let ends = if closed { vec![] } else { vec![0, n.saturating_sub(1)] };
for i in (0..n).filter(|&i| closed || (i > 0 && i + 1 < n)).chain(ends) {
auto_smooth(sp, i, ratio);
}
}
/// `sp` cut at its `corners`, its `smooth` anchors, or both ([`SubPath::cut_at`]); the shape doesn't
/// change. An anchor is smooth when its handles stand in line, as the outline shows it, whatever
/// kind it was given.
pub fn split_at_anchors(sp: &SubPath, corners: bool, smooth: bool) -> Vec<SubPath> {
let is_smooth = |a: &Anchor| Anchor::with_handles(a.p, a.h_in, a.h_out).kind == AnchorKind::Smooth;
let at = sp.anchors.iter().enumerate().filter(|(_, a)| if is_smooth(a) { smooth } else { corners }).map(|(i, _)| i).collect();
sp.cut_at(&at)
}
/// How [`close`] joins an open subpath's ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CloseMode {
@@ -22,7 +22,7 @@ const END: f64 = 1e-6;
/// A place on a path: (subpath, segment, t).
pub type Place = (usize, usize, f64);
fn control_box(c: &CubicBez) -> Rect {
pub(super) fn control_box(c: &CubicBez) -> Rect {
Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3)
}
@@ -44,7 +44,7 @@ const MAX_RADIUS: f64 = 1e6;
/// The farthest (in its parameter) [`ExtendMode::Bezier`] stretches a segment.
const MAX_STRETCH: f64 = 1024.0;
fn finite(sp: &SubPath) -> bool {
pub(super) fn finite(sp: &SubPath) -> bool {
let ok = |p: Point| p.x.is_finite() && p.y.is_finite();
sp.anchors.iter().all(|a| ok(a.p) && ok(a.h_in) && ok(a.h_out))
}
@@ -0,0 +1,489 @@
//! Merging two touching edges: where two paths meet at two pairs of coincident anchors, the
//! stretches of path between those anchors become one shared edge ([`stretches_at`]); where the
//! anchors aren't there yet, near ones are brought together and a missing one is added
//! ([`ends_at`]). [`merge_preview`] says what a plan would do and [`apply_merge`] does it. The
//! Shared Edge Merge Tool and `addon.pathtools.mergeEdge` drive both from the same plan.
use std::collections::BTreeMap;
use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
use super::crossings::control_box;
use super::extend::finite;
use super::{ACCURACY, TINY, insert_at, unit};
use crate::fit::{end_tangent, is_straight, start_tangent};
#[cfg(test)]
mod tests;
/// How near two anchors count as one, by default and at most (pt).
pub const COINCIDENCE: f64 = 0.002;
pub const MAX_COINCIDENCE: f64 = 3.0;
/// Stretches differing in length by more than this ratio aren't the same edge.
const MAX_LENGTH_RATIO: f64 = 1.1;
/// The cosine of the widest angle (120°) stretches may make at an end: past it they run apart.
const MIN_END_COS: f64 = -0.5;
/// Paths with more anchors than this aren't searched.
const MAX_PATH_ANCHORS: usize = 200_000;
/// Most segments a stretch runs.
const MAX_STRETCH: usize = 5_000;
/// Most segments under the brush looked at on each path.
const MAX_NEAR: usize = 16;
/// Anchors of the two stretches closer than this share of the length are one anchor of the result.
const SAME_PLACE: f64 = 0.01;
/// How close (pt along a segment) a cut has to be to the segment's end to be that end.
const AT_END: f64 = 1e-6;
/// The cosine of the widest bend (5°) the average's joints are straightened out of.
const MIN_JOINT_COS: f64 = 0.9962;
/// Control points this close (pt) are the same edge.
const SAME_EDGE: f64 = 1e-6;
/// Which outline a merge keeps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Follow {
/// Half way between the two.
Average,
/// The first path's: it doesn't change.
First,
/// The second path's.
Second,
}
impl Follow {
pub const ALL: [Self; 3] = [Self::Average, Self::First, Self::Second];
pub fn id(self) -> &'static str {
match self {
Self::Average => "average",
Self::First => "a",
Self::Second => "b",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|f| f.id() == s)
}
}
/// `segments` segments of a subpath from anchor `start` forward; `reversed` when the merge runs
/// along them backward.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Stretch {
pub subpath: usize,
pub start: usize,
pub segments: usize,
pub reversed: bool,
}
/// One path's side of making an end.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EndSide {
/// The anchor it has there.
Anchor { subpath: usize, anchor: usize },
/// It has none: one goes on this segment.
Insert { subpath: usize, segment: usize, t: f64 },
}
/// What a click can do.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MergePlan {
/// Replace these two stretches, running the same way, with one edge.
Edge { a: Stretch, b: Stretch },
/// Bring the two sides to one point.
Ends { a: EndSide, b: EndSide },
}
/// What a plan would do.
#[derive(Clone, Debug, PartialEq)]
pub enum MergePreview {
/// The two stretches and the edge replacing them; `done` when they are that edge already.
Edge { a: Vec<CubicBez>, b: Vec<CubicBez>, merged: Vec<CubicBez>, done: bool },
/// Where the two sides are and where they meet.
Ends { a: Point, b: Point, to: Point },
}
fn searchable(a: &PathData, b: &PathData, at: Point) -> bool {
let fits = |p: &PathData| p.anchor_count() <= MAX_PATH_ANCHORS && p.subpaths.iter().all(finite);
at.x.is_finite() && at.y.is_finite() && fits(a) && fits(b)
}
impl Stretch {
/// Its segments in the order the merge runs along them.
fn chain(&self, path: &PathData) -> Option<Vec<CubicBez>> {
let sp = path.subpaths.get(self.subpath)?;
let count = sp.segment_count();
if count == 0 || self.segments == 0 || self.segments > count {
return None;
}
let forward: Vec<CubicBez> = (0..self.segments).map(|k| sp.segment((self.start + k) % count)).collect();
Some(if self.reversed { backward(&forward) } else { forward })
}
}
/// `chain` run the other way.
fn backward(chain: &[CubicBez]) -> Vec<CubicBez> {
chain.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect()
}
fn length(chain: &[CubicBez]) -> f64 {
chain.iter().map(|c| c.arclen(ACCURACY)).sum()
}
/// A subpath's anchors in order of x, to find the ones at a point quickly.
struct ByX<'a> {
sp: &'a SubPath,
order: Vec<(f64, usize)>,
}
impl<'a> ByX<'a> {
fn new(sp: &'a SubPath) -> Self {
let mut order: Vec<(f64, usize)> = sp.anchors.iter().enumerate().map(|(i, a)| (a.p.x, i)).collect();
order.sort_by(|x, y| x.0.total_cmp(&y.0));
Self { sp, order }
}
/// Its anchor nearest `p`, within `tol`.
fn partner(&self, p: Point, tol: f64) -> Option<usize> {
let from = self.order.partition_point(|(x, _)| *x < p.x - tol);
let within = self.order.iter().skip(from).take_while(|(x, _)| *x <= p.x + tol);
let near = within.filter_map(|(_, i)| Some((self.sp.anchors.get(*i)?.p.distance(p), *i))).filter(|(d, _)| *d <= tol);
near.min_by(|x, y| x.0.total_cmp(&y.0)).map(|(_, i)| i)
}
}
/// The segments of `path` within `radius` of `at`, nearest first: (distance, subpath, segment).
fn segments_near(path: &PathData, at: Point, radius: f64) -> Vec<(f64, usize, usize)> {
let mut out = vec![];
for (si, sp) in path.subpaths.iter().enumerate() {
for s in 0..sp.segment_count() {
let c = sp.segment(s);
if !control_box(&c).inflate(radius, radius).contains(at) {
continue;
}
let d = c.nearest(at, ACCURACY).distance_sq.sqrt();
if d <= radius {
out.push((d, si, s));
}
}
}
out.sort_by(|x, y| x.0.total_cmp(&y.0));
out.truncate(MAX_NEAR);
out
}
/// The stretch of `sa` around segment `seg` between the nearest anchors each way that `b` has a
/// coincident one for, and the stretch of `b` between those that holds its segment `seg_b`.
fn matching((si_a, sa): (usize, &SubPath), seg: usize, (si_b, by_x): (usize, &ByX), seg_b: usize, tol: f64) -> Option<(Stretch, Stretch)> {
let (n, m) = (sa.anchors.len(), by_x.sp.anchors.len());
let limit = sa.segment_count().min(MAX_STRETCH);
let partner = |i: usize| by_x.partner(sa.anchors.get(i)?.p, tol);
let back = (0..limit).take_while(|k| sa.closed || *k <= seg).find_map(|k| Some((k, partner((seg + n - k) % n)?)));
let ahead = (0..limit).take_while(|k| sa.closed || seg + 1 + k < n).find_map(|k| Some((k, partner((seg + 1 + k) % n)?)));
let ((back, b0), (ahead, b1)) = (back?, ahead?);
let segments = back + ahead + 1;
// Round to the same anchor, or to the same one of the other path: there is no stretch between.
if b0 == b1 || (sa.closed && segments >= n) {
return None;
}
let first = Stretch { subpath: si_a, start: (seg + n - back) % n, segments, reversed: false };
let run = |from: usize, to: usize| (to + m - from) % m;
let holds = |from: usize, to: usize| (seg_b + m - from) % m < run(from, to);
let second = if (by_x.sp.closed || b0 < b1) && holds(b0, b1) {
Stretch { subpath: si_b, start: b0, segments: run(b0, b1), reversed: false }
} else if (by_x.sp.closed || b1 < b0) && holds(b1, b0) {
Stretch { subpath: si_b, start: b1, segments: run(b1, b0), reversed: true }
} else {
return None;
};
Some((first, second))
}
/// Could these two run along one another: much the same length, not leaving their ends in
/// opposite directions?
fn alike(a: &[CubicBez], b: &[CubicBez]) -> bool {
let (la, lb) = (length(a), length(b));
let ((Some(a0), Some(a1)), (Some(b0), Some(b1))) = ((a.first(), a.last()), (b.first(), b.last())) else { return false };
la.min(lb) > TINY
&& la.max(lb) <= la.min(lb) * MAX_LENGTH_RATIO
&& start_tangent(a0).dot(start_tangent(b0)) >= MIN_END_COS
&& end_tangent(a1).dot(end_tangent(b1)) >= MIN_END_COS
}
/// The two stretches of `a` and `b` that can merge within `radius` of `at`, each pair of ends
/// coincident within `tol`: the pair nearest `at`. `None` when there is none.
pub fn stretches_at(a: &PathData, b: &PathData, at: Point, radius: f64, tol: f64) -> Option<MergePlan> {
if !searchable(a, b, at) {
return None;
}
let (near_a, near_b) = (segments_near(a, at, radius), segments_near(b, at, radius));
let index: BTreeMap<usize, ByX> = near_b.iter().filter_map(|&(_, si, _)| Some((si, ByX::new(b.subpaths.get(si)?)))).collect();
let mut pairs: Vec<_> = near_a.iter().flat_map(|&(da, sa, ga)| near_b.iter().map(move |&(db, sb, gb)| (da + db, (sa, ga), (sb, gb)))).collect();
pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
pairs.into_iter().find_map(|(_, (sa, ga), (sb, gb))| {
let (x, y) = matching((sa, a.subpaths.get(sa)?), ga, (sb, index.get(&sb)?), gb, tol)?;
alike(&x.chain(a)?, &y.chain(b)?).then_some(MergePlan::Edge { a: x, b: y })
})
}
/// The anchor of `path` nearest `at`, within `radius`: (subpath, anchor, where).
fn anchor_near(path: &PathData, at: Point, radius: f64) -> Option<(usize, usize, Point)> {
let near = path.anchors().map(|(si, ai, a)| (a.p.distance(at), si, ai, a.p)).filter(|x| x.0 <= radius);
near.min_by(|x, y| x.0.total_cmp(&y.0)).map(|(_, si, ai, p)| (si, ai, p))
}
/// Where `path` takes an anchor to match one at `p`, if the place is within `radius` of `at`.
fn matching_place(path: &PathData, p: Point, at: Point, radius: f64) -> Option<EndSide> {
let (subpath, segment, t, q, _) = path.nearest(p)?;
(q.distance(at) <= radius).then_some(EndSide::Insert { subpath, segment, t })
}
/// What making an end within `radius` of `at` takes: the two paths' nearest anchors there, or the
/// anchor one has and the place on the other for its match. `None` when neither has an anchor
/// there, or they are together already.
pub fn ends_at(a: &PathData, b: &PathData, at: Point, radius: f64) -> Option<MergePlan> {
if !searchable(a, b, at) {
return None;
}
let anchor = |(subpath, anchor, _): (usize, usize, Point)| EndSide::Anchor { subpath, anchor };
match (anchor_near(a, at, radius), anchor_near(b, at, radius)) {
(Some(x), Some(y)) => (x.2.distance(y.2) > TINY).then(|| MergePlan::Ends { a: anchor(x), b: anchor(y) }),
(Some(x), None) => Some(MergePlan::Ends { a: anchor(x), b: matching_place(b, x.2, at, radius)? }),
(None, Some(y)) => Some(MergePlan::Ends { a: matching_place(a, y.2, at, radius)?, b: anchor(y) }),
(None, None) => None,
}
}
/// Where the anchors between `chain`'s segments fall, as shares of its length.
fn fractions(chain: &[CubicBez]) -> Vec<f64> {
let total = length(chain);
let mut run = 0.0;
let inner = chain.iter().take(chain.len().saturating_sub(1));
inner
.map(|c| {
run += c.arclen(ACCURACY);
run / total
})
.collect()
}
/// The places (share of the length on each stretch) both stretches get an anchor: each one's own
/// anchors, where two nearly meet the pair of them, and otherwise the same share on the other.
fn shared_cuts(fa: &[f64], fb: &[f64]) -> Vec<(f64, f64)> {
let (mut i, mut j) = (0, 0);
let mut out = vec![];
loop {
match (fa.get(i), fb.get(j)) {
(Some(&x), Some(&y)) if (x - y).abs() <= SAME_PLACE => {
out.push((x, y));
i += 1;
j += 1;
}
(Some(&x), Some(&y)) if x < y => {
out.push((x, x));
i += 1;
}
(Some(&x), None) => {
out.push((x, x));
i += 1;
}
(_, Some(&y)) => {
out.push((y, y));
j += 1;
}
(None, None) => return out,
}
}
}
/// `chain` with a joint at each of the shares of its length `at`; those at a joint already add none.
fn cut(chain: &[CubicBez], mut at: Vec<f64>) -> Vec<CubicBez> {
at.sort_by(f64::total_cmp);
let total = length(chain);
let mut next = at.into_iter().peekable();
let mut run = 0.0;
let mut out = vec![];
for c in chain {
let len = c.arclen(ACCURACY);
let mut ts = vec![0.0];
while let Some(along) = next.peek().map(|f| f * total - run).filter(|d| *d < len - AT_END) {
next.next();
if along > AT_END {
ts.push(c.inv_arclen(along, ACCURACY));
}
}
ts.push(1.0);
out.extend(ts.windows(2).filter_map(|w| Some(c.subsegment(*w.first()?..*w.get(1)?))));
run += len;
}
out
}
/// The curve half way between `a` and `b`; a straight one has its handles on its anchors.
fn halfway(a: &CubicBez, b: &CubicBez) -> CubicBez {
let c = CubicBez::new(a.p0.midpoint(b.p0), a.p1.midpoint(b.p1), a.p2.midpoint(b.p2), a.p3.midpoint(b.p3));
if is_straight(&c, SAME_EDGE) { CubicBez::new(c.p0, c.p0, c.p3, c.p3) } else { c }
}
/// Bring the handles at `chain`'s joints in line where they all but are: averaging leaves a small
/// bend at what was a smooth anchor on both stretches.
fn align_joints(chain: &mut [CubicBez]) {
for k in 1..chain.len() {
let (before, after) = chain.split_at_mut(k);
let (Some(x), Some(y)) = (before.last_mut(), after.first_mut()) else { continue };
let (Some(i), Some(o)) = (unit(x.p3 - x.p2), unit(y.p1 - y.p0)) else { continue };
if i.dot(o) < MIN_JOINT_COS {
continue;
}
let Some(dir) = unit(i + o) else { continue };
x.p2 = x.p3 - dir * (x.p3 - x.p2).hypot();
y.p1 = y.p0 + dir * (y.p1 - y.p0).hypot();
}
}
/// The edge replacing stretches `a` and `b`, which run the same way. `None` when their anchors
/// can't be matched up.
fn merged_edge(a: &[CubicBez], b: &[CubicBez], follow: Follow) -> Option<Vec<CubicBez>> {
match follow {
Follow::First => return Some(a.to_vec()),
Follow::Second => return Some(b.to_vec()),
Follow::Average => {}
}
// A segment of no length has nothing to average.
let solid = |c: &[CubicBez]| -> Vec<CubicBez> { c.iter().filter(|s| s.arclen(ACCURACY) > TINY).copied().collect() };
let (a, b) = (solid(a), solid(b));
let cuts = shared_cuts(&fractions(&a), &fractions(&b));
let (pa, pb) = (cut(&a, cuts.iter().map(|c| c.0).collect()), cut(&b, cuts.iter().map(|c| c.1).collect()));
if pa.is_empty() || pa.len() != pb.len() {
return None;
}
let mut out: Vec<CubicBez> = pa.iter().zip(&pb).map(|(x, y)| halfway(x, y)).collect();
align_joints(&mut out);
Some(out)
}
fn in_line(a: &Anchor) -> bool {
match (unit(a.h_out - a.p), unit(a.p - a.h_in)) {
(Some(o), Some(i)) => o.cross(i).abs() <= 1e-6 && o.dot(i) > 0.0,
_ => false,
}
}
/// `sp` with `st` replaced by `chain`, which runs the way the merge does: the anchors inside are
/// `chain`'s joints and the two at the ends move to `chain`'s ends, their outer handles with them.
/// An end whose handles no longer line up turns into a corner.
fn splice(sp: &SubPath, st: Stretch, chain: &[CubicBez]) -> Option<SubPath> {
let own = backward(chain);
let chain = if st.reversed { own.as_slice() } else { chain };
let (first, last) = (chain.first()?, chain.last()?);
let mut out = sp.anchors.clone();
let start = st.start.min(out.len());
out.rotate_left(start);
let settle = |a: &mut Anchor| {
if a.kind == AnchorKind::Smooth && !in_line(a) {
a.kind = AnchorKind::Corner;
}
};
let a = out.first_mut()?;
a.translate(first.p0 - a.p);
a.h_out = first.p1;
settle(a);
let b = out.get_mut(st.segments)?;
b.translate(last.p3 - b.p);
b.h_in = last.p2;
settle(b);
let joints = chain.windows(2).filter_map(|w| match w {
[x, y] => {
let mut a = Anchor { p: y.p0, h_in: x.p2, h_out: y.p1, kind: AnchorKind::Corner };
if in_line(&a) {
a.kind = AnchorKind::Smooth;
}
Some(a)
}
_ => None,
});
out.splice(1..st.segments, joints);
// Back in its place; a stretch over the start of a closed subpath only shifts where it starts.
let start = start.min(out.len());
out.rotate_right(start);
Some(SubPath::new(out, sp.closed))
}
/// Where a side of an end is now.
fn side_at(path: &PathData, side: EndSide) -> Option<Point> {
match side {
EndSide::Anchor { subpath, anchor } => Some(path.subpaths.get(subpath)?.anchors.get(anchor)?.p),
EndSide::Insert { subpath, segment, t } => {
let sp = path.subpaths.get(subpath)?;
(segment < sp.segment_count()).then(|| sp.segment(segment).eval(t.clamp(0.0, 1.0)))
}
}
}
/// Where the two sides of an end meet: on the path followed; with neither, half way between two
/// anchors, or at the anchor when the other side is a place on a path.
fn meeting_point((a, sa): (Point, EndSide), (b, sb): (Point, EndSide), follow: Follow) -> Point {
match (follow, sa, sb) {
(Follow::First, ..) | (Follow::Average, EndSide::Anchor { .. }, EndSide::Insert { .. }) => a,
(Follow::Second, ..) | (Follow::Average, EndSide::Insert { .. }, EndSide::Anchor { .. }) => b,
_ => a.midpoint(b),
}
}
/// `path` with `side`'s anchor (added if it lacks one) at `to`.
fn put_side(path: &PathData, side: EndSide, to: Point) -> Option<PathData> {
let mut out = path.clone();
let anchor = match side {
EndSide::Anchor { subpath, anchor } => out.anchor_mut(subpath, anchor)?,
EndSide::Insert { subpath, segment, t } => {
let sp = out.subpaths.get_mut(subpath)?;
let (new, added) = insert_at(sp, &[(segment, t)]);
*sp = new;
sp.anchors.get_mut(*added.first()?)?
}
};
anchor.translate(to - anchor.p);
Some(out)
}
fn same_edge(x: &[CubicBez], y: &[CubicBez]) -> bool {
let near = |p: Point, q: Point| p.distance(q) <= SAME_EDGE;
x.len() == y.len() && x.iter().zip(y).all(|(c, d)| near(c.p0, d.p0) && near(c.p1, d.p1) && near(c.p2, d.p2) && near(c.p3, d.p3))
}
/// What `plan` would do to `a` and `b`, following `follow`.
pub fn merge_preview(a: &PathData, b: &PathData, plan: &MergePlan, follow: Follow) -> Option<MergePreview> {
match *plan {
MergePlan::Edge { a: sa, b: sb } => {
let (ca, cb) = (sa.chain(a)?, sb.chain(b)?);
let merged = merged_edge(&ca, &cb, follow)?;
let done = same_edge(&merged, &ca) && same_edge(&merged, &cb);
Some(MergePreview::Edge { a: ca, b: cb, merged, done })
}
MergePlan::Ends { a: ea, b: eb } => {
let (pa, pb) = (side_at(a, ea)?, side_at(b, eb)?);
Some(MergePreview::Ends { a: pa, b: pb, to: meeting_point((pa, ea), (pb, eb), follow) })
}
}
}
/// `a` and `b` as `plan` leaves them, following `follow`: each subpath stays closed or open, and
/// the stretch of the path followed doesn't change. `None` when the plan doesn't fit them.
pub fn apply_merge(a: &PathData, b: &PathData, plan: &MergePlan, follow: Follow) -> Option<(PathData, PathData)> {
match (*plan, merge_preview(a, b, plan, follow)?) {
(MergePlan::Edge { a: sa, b: sb }, MergePreview::Edge { merged, .. }) => {
let replaced = |path: &PathData, st: Stretch, keep: Follow| {
let mut out = path.clone();
if follow != keep {
let sp = out.subpaths.get_mut(st.subpath)?;
*sp = splice(sp, st, &merged)?;
}
Some(out)
};
Some((replaced(a, sa, Follow::First)?, replaced(b, sb, Follow::Second)?))
}
(MergePlan::Ends { a: ea, b: eb }, MergePreview::Ends { to, .. }) => Some((put_side(a, ea, to)?, put_side(b, eb, to)?)),
_ => None,
}
}
@@ -0,0 +1,270 @@
use kurbo::{ParamCurve, Point};
use vectorcraft_geom::{Anchor, PathData, SubPath};
use super::*;
fn pt(x: f64, y: f64) -> Point {
Point::new(x, y)
}
/// A closed shape above y = 0 whose lower edge runs right to left from (100, 0) to (0, 0), curved
/// down by `bulge` control-point height.
fn above(bulge: f64) -> SubPath {
SubPath::new(
vec![
Anchor::corner(pt(0.0, -50.0)),
Anchor::corner(pt(100.0, -50.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(100.0, 0.0), pt(70.0, bulge)),
Anchor::with_handles(pt(0.0, 0.0), pt(30.0, bulge), pt(0.0, 0.0)),
],
true,
)
}
/// A closed shape below y = 0 whose upper edge runs left to right, curved up by `bulge`.
fn below(bulge: f64) -> SubPath {
SubPath::new(
vec![
Anchor::with_handles(pt(0.0, 0.0), pt(0.0, 0.0), pt(30.0, -bulge)),
Anchor::with_handles(pt(100.0, 0.0), pt(70.0, -bulge), pt(100.0, 0.0)),
Anchor::corner(pt(100.0, 50.0)),
Anchor::corner(pt(0.0, 50.0)),
],
true,
)
}
fn single(sp: SubPath) -> PathData {
PathData::single(sp)
}
/// The plan at `at` with a 20 pt brush.
fn plan(a: &PathData, b: &PathData, at: Point) -> MergePlan {
stretches_at(a, b, at, 10.0, COINCIDENCE).expect("a stretch")
}
/// The outline of `chain` run one way, sampled.
fn samples(chain: &[CubicBez]) -> Vec<Point> {
let n = chain.len() * 16;
let at = |k: usize| {
let f = k as f64 / n as f64 * chain.len() as f64;
let i = (f.floor() as usize).min(chain.len() - 1);
chain[i].eval(f - i as f64)
};
(0..=n).map(at).collect()
}
/// The edge as `path` now has it between anchors `from` (inclusive) and `to`, along the path.
fn edge(path: &PathData, from: usize, segments: usize) -> Vec<CubicBez> {
let sp = &path.subpaths[0];
(0..segments).map(|k| sp.segment((from + k) % sp.segment_count())).collect()
}
/// The farthest apart two chains are, sampled alike.
fn apart(x: &[CubicBez], y: &[CubicBez]) -> f64 {
samples(x).iter().zip(samples(y)).map(|(p, q)| p.distance(q)).fold(0.0, f64::max)
}
#[test]
fn the_merged_edge_lies_half_way_and_both_paths_keep_their_topology() {
let (a, b) = (single(above(6.0)), single(below(2.0)));
let plan = plan(&a, &b, pt(50.0, 0.0));
assert_eq!(
plan,
MergePlan::Edge {
a: Stretch { subpath: 0, start: 2, segments: 1, reversed: false },
b: Stretch { subpath: 0, start: 0, segments: 1, reversed: true },
}
);
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Average).unwrap();
assert!(na.subpaths[0].closed && nb.subpaths[0].closed);
assert_eq!((na.anchor_count(), nb.anchor_count()), (4, 4));
// Everything else is where it was.
assert_eq!((na.subpaths[0].anchors[0], na.subpaths[0].anchors[1]), (a.subpaths[0].anchors[0], a.subpaths[0].anchors[1]));
assert_eq!((nb.subpaths[0].anchors[2], nb.subpaths[0].anchors[3]), (b.subpaths[0].anchors[2], b.subpaths[0].anchors[3]));
// One edge, run opposite ways by the two paths, between the two it replaced.
let (ea, eb) = (edge(&na, 2, 1), edge(&nb, 0, 1));
assert!(apart(&ea, &backward(&eb)) < 1e-9);
let (upper, lower) = (a.subpaths[0].segment(2), b.subpaths[0].segment(0));
for k in 0..=16 {
let t = k as f64 / 16.0;
let (p, u, l) = (ea[0].eval(t), upper.eval(t), lower.eval(1.0 - t));
assert!(p.distance(u.midpoint(l)) < 1e-9, "{p:?} is half way between {u:?} and {l:?}");
assert!(l.y - 1e-9 <= p.y && p.y <= u.y + 1e-9);
}
// Merged: there is nothing left to do, and it says so.
let again = stretches_at(&na, &nb, pt(50.0, 0.0), 10.0, COINCIDENCE).unwrap();
assert!(matches!(merge_preview(&na, &nb, &again, Follow::Average), Some(MergePreview::Edge { done: true, .. })));
let (ma, mb) = apply_merge(&na, &nb, &again, Follow::Average).unwrap();
assert!(apart(&edge(&ma, 2, 1), &edge(&na, 2, 1)) < 1e-9 && apart(&edge(&mb, 0, 1), &edge(&nb, 0, 1)) < 1e-9);
}
#[test]
fn following_a_path_keeps_it_and_the_other_takes_its_edge() {
let (a, b) = (single(above(6.0)), single(below(2.0)));
let plan = plan(&a, &b, pt(50.0, 0.0));
let (na, nb) = apply_merge(&a, &b, &plan, Follow::First).unwrap();
assert_eq!(na, a);
assert!(apart(&edge(&nb, 0, 1), &backward(&edge(&a, 2, 1))) < 1e-9);
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Second).unwrap();
assert_eq!(nb, b);
assert!(apart(&edge(&na, 2, 1), &backward(&edge(&b, 0, 1))) < 1e-9);
}
#[test]
fn stretches_of_different_anchor_counts_get_the_same_anchors() {
let (with_two, _) = insert_at(&above(6.0), &[(2, 0.3)]);
assert_eq!(with_two.anchors.len(), 5);
let (a, b) = (single(with_two), single(below(2.0)));
let plan = plan(&a, &b, pt(50.0, 0.0));
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Average).unwrap();
assert_eq!((na.anchor_count(), nb.anchor_count()), (5, 5));
let (ea, eb) = (edge(&na, 2, 2), edge(&nb, 0, 2));
assert!(apart(&ea, &backward(&eb)) < 1e-9);
assert_eq!(ea[0].p3, eb[0].p3);
// The anchors were smooth on the one and a point of a curve on the other: the joint stays smooth.
assert_eq!(na.subpaths[0].anchors[3].kind, AnchorKind::Smooth);
// Anchors at nearly the same place stand for one.
let (b2, _) = insert_at(&below(2.0), &[(0, 0.7)]);
let (a2, b2) = (a.clone(), single(b2));
let (na, nb) = apply_merge(&a2, &b2, &stretches_at(&a2, &b2, pt(50.0, 0.0), 10.0, COINCIDENCE).unwrap(), Follow::Average).unwrap();
assert_eq!((na.anchor_count(), nb.anchor_count()), (5, 5), "one anchor inside, not two");
}
#[test]
fn open_paths_stay_open_and_keep_what_lies_beyond_the_stretch() {
let a = single(SubPath::polyline(&[pt(-50.0, 0.0), pt(0.0, 0.0), pt(50.0, 4.0), pt(100.0, 0.0), pt(150.0, 40.0)], false));
let b = single(SubPath::polyline(&[pt(100.0, 0.0), pt(50.0, -4.0), pt(0.0, 0.0), pt(-20.0, 60.0)], false));
let plan = plan(&a, &b, pt(25.0, 0.0));
assert_eq!(
plan,
MergePlan::Edge {
a: Stretch { subpath: 0, start: 1, segments: 2, reversed: false },
b: Stretch { subpath: 0, start: 0, segments: 2, reversed: true },
}
);
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Average).unwrap();
assert!(!na.subpaths[0].closed && !nb.subpaths[0].closed);
let (pa, pb) = (&na.subpaths[0].anchors, &nb.subpaths[0].anchors);
assert_eq!(pa.iter().map(|x| x.p).collect::<Vec<_>>(), [pt(-50.0, 0.0), pt(0.0, 0.0), pt(50.0, 0.0), pt(100.0, 0.0), pt(150.0, 40.0)]);
assert_eq!(pb.iter().map(|x| x.p).collect::<Vec<_>>(), [pt(100.0, 0.0), pt(50.0, 0.0), pt(0.0, 0.0), pt(-20.0, 60.0)]);
}
#[test]
fn a_stretch_over_the_start_of_a_closed_path_stays_closed_and_whole() {
// The edge along y = 0 runs from anchor 3 over anchor 0, which has no partner, to anchor 1.
let a = single(SubPath::polyline(&[pt(50.0, 1.0), pt(100.0, 0.0), pt(100.0, -50.0), pt(0.0, 0.0)], true));
let b = single(SubPath::polyline(&[pt(100.0, 0.0), pt(0.0, 0.0), pt(0.0, 50.0), pt(100.0, 50.0)], true));
let plan = plan(&a, &b, pt(25.0, 0.5));
let MergePlan::Edge { a: sa, .. } = plan else { panic!("{plan:?}") };
assert_eq!((sa.start, sa.segments), (3, 2));
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Average).unwrap();
assert!(na.subpaths[0].closed && nb.subpaths[0].closed);
assert_eq!((na.anchor_count(), nb.anchor_count()), (4, 5));
// Every anchor of the new outlines is where one was, or on the merged edge at y 0.5.
let at = |path: &PathData, p: Point| path.anchors().any(|(_, _, x)| x.p.distance(p) < 1e-4);
assert!(at(&na, pt(100.0, -50.0)) && at(&nb, pt(0.0, 50.0)) && at(&nb, pt(100.0, 50.0)));
assert!(at(&na, pt(50.0, 0.5)) && at(&nb, pt(50.0, 0.5)), "{na:?}");
}
#[test]
fn the_stretch_under_the_brush_is_the_one_along_the_shared_edge_not_the_long_way_round() {
let square = |x: f64| single(SubPath::polyline(&[pt(x, 0.0), pt(x + 100.0, 0.0), pt(x + 100.0, 100.0), pt(x, 100.0)], true));
let (a, b) = (square(0.0), square(100.0));
// Above the corner, each path's top edge is nearest: their long ways round face each other.
let MergePlan::Edge { a: sa, b: sb } = plan(&a, &b, pt(99.0, -2.0)) else { panic!() };
assert_eq!((sa.start, sa.segments), (1, 1));
assert_eq!((sb.start, sb.segments), (3, 1));
}
#[test]
fn stretches_too_unlike_or_without_two_coincident_ends_are_left_alone() {
let (a, b) = (single(above(6.0)), single(below(2.0)));
assert_eq!(stretches_at(&a, &b, pt(50.0, 40.0), 10.0, COINCIDENCE), None, "the brush doesn't touch both");
// One coincident anchor only.
let c = single(SubPath::polyline(&[pt(0.0, 0.0), pt(101.0, 0.0)], false));
assert_eq!(stretches_at(&a, &c, pt(50.0, 0.0), 10.0, COINCIDENCE), None);
// Coincident within a wider tolerance.
assert!(stretches_at(&a, &c, pt(50.0, 2.0), 10.0, 1.5).is_some());
// One side twice as long as the other, both ends coincident.
let hump = single(SubPath::polyline(&[pt(0.0, 0.0), pt(50.0, 5.0), pt(50.0, 60.0), pt(100.0, 0.0)], false));
let flat = single(SubPath::polyline(&[pt(0.0, 0.0), pt(100.0, 0.0)], false));
assert_eq!(stretches_at(&hump, &flat, pt(25.0, 1.0), 10.0, COINCIDENCE), None);
// Past the limits, or not finite.
let mut bad = a.clone();
bad.subpaths[0].anchors[0].p.x = f64::NAN;
assert_eq!(stretches_at(&bad, &b, pt(50.0, 0.0), 10.0, COINCIDENCE), None);
assert_eq!(ends_at(&bad, &b, pt(50.0, 0.0), 10.0), None);
assert_eq!(stretches_at(&a, &b, pt(f64::NAN, 0.0), 10.0, COINCIDENCE), None);
assert_eq!(stretches_at(&PathData::default(), &b, pt(50.0, 0.0), 10.0, COINCIDENCE), None);
assert_eq!(ends_at(&PathData::default(), &PathData::default(), pt(50.0, 0.0), 10.0), None);
}
#[test]
fn near_anchors_meet_half_way_or_on_the_path_followed() {
let a = single(SubPath::polyline(&[pt(0.0, 0.0), pt(100.0, 0.0)], false));
let b = single(SubPath::polyline(&[pt(104.0, 2.0), pt(200.0, 0.0)], false));
let plan = ends_at(&a, &b, pt(102.0, 1.0), 10.0).unwrap();
let ends = |f| {
let (na, nb) = apply_merge(&a, &b, &plan, f).unwrap();
(na.subpaths[0].anchors[1].p, nb.subpaths[0].anchors[0].p)
};
assert_eq!(ends(Follow::Average), (pt(102.0, 1.0), pt(102.0, 1.0)));
assert_eq!(ends(Follow::First), (pt(100.0, 0.0), pt(100.0, 0.0)));
assert_eq!(ends(Follow::Second), (pt(104.0, 2.0), pt(104.0, 2.0)));
assert_eq!(merge_preview(&a, &b, &plan, Follow::Average), Some(MergePreview::Ends { a: pt(100.0, 0.0), b: pt(104.0, 2.0), to: pt(102.0, 1.0) }));
// Together already: nothing to do.
let c = single(SubPath::polyline(&[pt(100.0, 0.0), pt(100.0, 90.0)], false));
assert_eq!(ends_at(&a, &c, pt(100.0, 1.0), 10.0), None);
// Nothing there.
assert_eq!(ends_at(&a, &b, pt(50.0, 1.0), 10.0), None);
}
#[test]
fn an_anchor_one_path_lacks_is_added_to_match() {
let a = single(SubPath::polyline(&[pt(0.0, 0.0), pt(100.0, 2.0), pt(100.0, 90.0)], false));
let b = single(SubPath::polyline(&[pt(0.0, 0.0), pt(200.0, 0.0)], false));
let plan = ends_at(&a, &b, pt(100.0, 1.0), 10.0).unwrap();
assert!(matches!(plan, MergePlan::Ends { a: EndSide::Anchor { anchor: 1, .. }, b: EndSide::Insert { .. } }), "{plan:?}");
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Average).unwrap();
assert_eq!(na, a, "the anchor stays");
assert_eq!(nb.anchor_count(), 3);
assert!(nb.subpaths[0].anchors[1].p.distance(pt(100.0, 2.0)) < 1e-9);
// Following the path that lacks it, the anchor comes to it.
let (na, nb) = apply_merge(&a, &b, &plan, Follow::Second).unwrap();
assert!(na.subpaths[0].anchors[1].p.distance(pt(100.0, 0.0)) < 1e-6);
assert!(nb.subpaths[0].anchors[1].p.distance(na.subpaths[0].anchors[1].p) < 1e-9);
// The same the other way round.
let swapped = ends_at(&b, &a, pt(100.0, 1.0), 10.0).unwrap();
let (nb, na) = apply_merge(&b, &a, &swapped, Follow::Average).unwrap();
assert_eq!((na.anchor_count(), nb.anchor_count()), (3, 3));
// With both paths' ends made, the stretch between can merge.
let c = single(SubPath::polyline(&[pt(100.0, 2.0), pt(100.0, 90.0)], false));
let d = single(SubPath::polyline(&[pt(95.0, 2.0), pt(95.0, 90.0)], false));
assert_eq!(stretches_at(&c, &d, pt(97.0, 50.0), 10.0, COINCIDENCE), None);
let first = ends_at(&c, &d, pt(97.0, 3.0), 10.0).unwrap();
let (c, d) = apply_merge(&c, &d, &first, Follow::Average).unwrap();
let second = ends_at(&c, &d, pt(97.0, 89.0), 10.0).unwrap();
let (c, d) = apply_merge(&c, &d, &second, Follow::Average).unwrap();
assert!(stretches_at(&c, &d, pt(97.5, 50.0), 10.0, COINCIDENCE).is_some());
}
#[test]
fn a_smooth_end_whose_handles_part_turns_into_a_corner() {
let a = single(SubPath::new(
vec![Anchor::smooth(pt(0.0, 0.0), pt(30.0, 10.0)), Anchor::with_handles(pt(100.0, 0.0), pt(70.0, 10.0), pt(100.0, 0.0))],
true,
));
let b = single(SubPath::polyline(&[pt(0.0, 0.0), pt(100.0, 0.0)], false));
let plan = plan(&a, &b, pt(50.0, 3.0));
let (na, _) = apply_merge(&a, &b, &plan, Follow::Second).unwrap();
assert_eq!(na.subpaths[0].anchors[0].kind, AnchorKind::Corner);
}
#[test]
fn follow_names_round_trip() {
for f in Follow::ALL {
assert_eq!(Follow::parse(f.id()), Some(f));
}
assert_eq!(Follow::parse("up"), None);
}
@@ -0,0 +1,107 @@
//! Sliding an anchor along its path: the anchor moves to a point on one of its two segments and
//! the segments beside it are refitted, so the outline stays where it was. It is a new anchor at
//! that point (an exact split) with the old one removed by the shared keep-shape refit.
use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, Point};
use vectorcraft_geom::SubPath;
use super::{ACCURACY, TINY, insert_at, neighbours};
use crate::addons::keep_shape::remove_anchor_keep_shape;
use crate::fit::is_straight;
/// How far along a neighbouring segment an anchor can slide: stopping short of the next anchor
/// keeps a segment between them.
pub const MAX_SLIDE: f64 = 0.98;
/// Steps of the search for the places on a curve where the tangent is at a snapping angle.
const STOP_SAMPLES: usize = 64;
/// Bisection steps that pin one of those places down.
const STOP_STEPS: usize = 40;
/// A stop this close to the anchor is the anchor itself.
const MIN_STOP: f64 = 1e-6;
/// The indices of the anchors beside anchor `i`; `None` for an end of an open subpath.
fn both_neighbours(sp: &SubPath, i: usize) -> Option<(usize, usize)> {
if i >= sp.anchors.len() {
return None;
}
match neighbours(sp, i) {
(Some(prev), Some(next)) => Some((prev, next)),
_ => None,
}
}
/// Anchor `index` of `sp` moved along the path by `t` → (the new subpath, how far its outline
/// strays from the old one, in points). `t` says where: a positive one is the curve parameter on
/// the segment after the anchor, a negative one the parameter back from the end of the segment
/// before it (`-t` from 1). The subpath keeps its anchor count and the anchor its index. `None` when the anchor can't slide: an end of
/// an open subpath, out of range, `t` not a number or past [`MAX_SLIDE`], non-finite coordinates,
/// or a closed subpath of two anchors.
pub fn slide_anchor(sp: &SubPath, index: usize, t: f64) -> Option<(SubPath, f64)> {
if t.is_nan() || t.abs() > MAX_SLIDE {
return None;
}
let (prev, _) = both_neighbours(sp, index)?;
let forward = t > 0.0;
let (split, _) = if forward { insert_at(sp, &[(index, t)]) } else { insert_at(sp, &[(prev, 1.0 + t)]) };
// Too small a move to split a segment: the anchor stays.
if split.anchors.len() == sp.anchors.len() {
return Some((sp.clone(), 0.0));
}
// Backward the new anchor comes just before the old one, or last on a closed subpath's first.
let old = if !forward && index > 0 { index + 1 } else { index };
let (mut out, strayed) = remove_anchor_keep_shape(&split, old)?;
if !forward && index == 0 {
out.anchors.rotate_right(1);
}
Some((out, strayed))
}
/// The slide (see [`slide_anchor`]) that brings anchor `index` nearest to `p`, held to
/// [`MAX_SLIDE`]; `None` when the anchor can't slide.
pub fn slide_t_at(sp: &SubPath, index: usize, p: Point) -> Option<f64> {
let (prev, _) = both_neighbours(sp, index)?;
let (before, after) = (sp.segment(prev).nearest(p, ACCURACY), sp.segment(index).nearest(p, ACCURACY));
let t = if before.distance_sq < after.distance_sq { before.t - 1.0 } else { after.t };
Some(t.clamp(-MAX_SLIDE, MAX_SLIDE))
}
/// The slides of anchor `index` (see [`slide_anchor`]) that land where the path's tangent is at a
/// multiple of 45° from `base` degrees, in order.
pub fn slide_stops(sp: &SubPath, index: usize, base: f64) -> Vec<f64> {
let Some((prev, _)) = both_neighbours(sp, index) else { return vec![] };
let before = tangent_stops(&sp.segment(prev), base).into_iter().map(|t| t - 1.0);
before.chain(tangent_stops(&sp.segment(index), base)).filter(|t| (MIN_STOP..=MAX_SLIDE).contains(&t.abs())).collect()
}
/// The parameters of `c` inside 0..1 where its tangent is at a multiple of 45° from `base`
/// degrees, in order. A straight segment has none: its tangent never reaches one or never leaves.
fn tangent_stops(c: &CubicBez, base: f64) -> Vec<f64> {
if is_straight(c, TINY) {
return vec![];
}
let d = c.deriv();
let base = base.to_radians();
// Zero at each multiple, and it doesn't jump where the angle wraps round or the curve reverses.
let f = |t: f64| {
let v = d.eval(t).to_vec2();
(v.hypot() > TINY).then(|| ((v.y.atan2(v.x) - base) * 4.0).sin())
};
let mut out = vec![];
for k in 0..STOP_SAMPLES {
let (mut a, mut b) = (k as f64 / STOP_SAMPLES as f64, (k + 1) as f64 / STOP_SAMPLES as f64);
let (Some(fa), Some(fb)) = (f(a), f(b)) else { continue };
if (fa < 0.0) == (fb < 0.0) {
continue;
}
for _ in 0..STOP_STEPS {
let m = (a + b) / 2.0;
match f(m) {
Some(fm) if (fm < 0.0) == (fa < 0.0) => a = m,
_ => b = m,
}
}
out.push(b);
}
out
}
@@ -294,3 +294,143 @@ fn the_brush_kernel_removes_only_marked_anchors() {
assert_eq!(simplify_anchors_keep_shape(&bump, 0.1, &[true; 5]).anchors.len(), 4, "only the anchor on the straight run goes");
assert_eq!(simplify_anchors_keep_shape(&bump, f64::INFINITY, &[true; 5]).anchors.len(), 2, "unless tolerance is ignored");
}
/// A circle about (0, 0) of radius 100 with `n` smooth anchors, each arc a cubic.
fn circle(n: usize) -> SubPath {
let step = std::f64::consts::TAU / n as f64;
let k = 4.0 / 3.0 * (step / 4.0).tan() * 100.0;
let anchors = (0..n).map(|i| {
let a = i as f64 * step;
let (p, tan) = (pt(a.cos() * 100.0, a.sin() * 100.0), Vec2::new(-a.sin(), a.cos()));
Anchor { p, h_in: p - tan * k, h_out: p + tan * k, kind: AnchorKind::Smooth }
});
SubPath::new(anchors.collect(), true)
}
#[test]
fn a_slid_anchor_keeps_the_shape_its_count_and_its_index() {
let sp = circle(8);
for (index, t) in [(2, 0.5), (2, -0.5), (0, -0.25), (0, 0.25), (7, 0.9), (7, -0.9)] {
let (out, strayed) = slide_anchor(&sp, index, t).unwrap();
let seg = if t > 0.0 { sp.segment(index) } else { sp.segment((index + 7) % 8) };
let want = seg.eval(if t > 0.0 { t } else { 1.0 + t });
assert_eq!(out.anchors.len(), 8, "{index} {t}");
assert!(out.anchors[index].p.distance(want) < 1e-9, "{index} {t}: the anchor is where it was sent");
assert!(strayed < 0.05 && off_circle(&out, pt(0.0, 0.0), 100.0) < 0.05, "{index} {t}: {strayed}");
// The other anchors stay.
assert!((0..8).filter(|i| *i != index).all(|i| out.anchors[i].p == sp.anchors[i].p), "{index} {t}");
}
}
#[test]
fn sliding_along_straight_runs_stays_straight_and_ends_do_not_slide() {
let sp = line(&[(0.0, 0.0), (100.0, 0.0), (200.0, 0.0), (200.0, 100.0)], false);
let (out, strayed) = slide_anchor(&sp, 1, 0.5).unwrap();
assert_eq!(out.anchors[1].p, pt(150.0, 0.0));
assert!(strayed < 1e-9 && out.segment_is_line(0) && out.segment_is_line(1));
assert_eq!(slide_anchor(&sp, 1, 0.0).unwrap().0, sp, "no move");
assert_eq!(slide_anchor(&sp, 1, 1e-9).unwrap().0, sp, "too small a move");
for (i, t) in [(0, 0.5), (3, -0.5), (9, 0.5), (1, 0.99), (1, -1.0), (1, f64::NAN), (1, f64::INFINITY)] {
assert!(slide_anchor(&sp, i, t).is_none(), "{i} {t}");
}
let mut bad = sp.clone();
bad.anchors[1].h_out = pt(f64::NAN, 0.0);
assert!(slide_anchor(&bad, 1, 0.5).is_none());
}
#[test]
fn the_slide_a_pointer_asks_for_and_where_the_tangent_stops() {
let sp = line(&[(0.0, 0.0), (100.0, 0.0), (200.0, 0.0)], false);
assert!(near(slide_t_at(&sp, 1, pt(150.0, 30.0)).unwrap(), 0.5, 1e-6));
let back = slide_t_at(&sp, 1, pt(75.0, -30.0)).unwrap();
assert!(back < 0.0 && sp.segment(0).eval(1.0 + back).distance(pt(75.0, 0.0)) < 1e-3, "{back}");
assert!(near(slide_t_at(&sp, 1, pt(900.0, 0.0)).unwrap(), MAX_SLIDE, 1e-9), "held short of the next anchor");
assert!(slide_t_at(&sp, 0, pt(50.0, 0.0)).is_none());
assert!(slide_stops(&sp, 1, 0.0).is_empty(), "a straight run has no tangent to reach");
let slanted = line(&[(0.0, 0.0), (100.0, 100.0), (250.0, 250.0)], false);
assert!(slide_stops(&slanted, 1, 0.0).is_empty(), "nor one that lies on a multiple of 45°");
// Round a circle of 4 anchors the tangent is at a multiple of 45° at each anchor and half way.
let round = circle(4);
let stops = slide_stops(&round, 0, 0.0);
assert_eq!(stops.len(), 2, "{stops:?}");
assert!(near(stops[0], -0.5, 1e-6) && near(stops[1], 0.5, 1e-6), "{stops:?}");
// From a constrain angle of 22.5°, between those.
let stops = slide_stops(&round, 0, 22.5);
assert_eq!(stops.len(), 4, "{stops:?}");
assert!(stops.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn add_anchors_spaces_them_by_count_or_distance() {
let sq = line(&[(0.0, 0.0), (90.0, 0.0), (90.0, 90.0), (0.0, 90.0)], true);
let out = add_anchors(&sq, SegmentKind::All, AnchorSpacing::Count(2), 100, 100).unwrap();
assert_eq!(out.anchors.len(), 12);
assert!(near(out.anchors[1].p.x, 30.0, 1e-6) && near(out.anchors[2].p.x, 60.0, 1e-6));
assert!(out.closed);
let out = add_anchors(&sq, SegmentKind::All, AnchorSpacing::Distance(40.0), 100, 100).unwrap();
assert_eq!(out.anchors.len(), 12, "at 40 and 80, none past the segment");
assert!(near(out.anchors[2].p.x, 80.0, 1e-6));
assert_eq!(add_anchors(&sq, SegmentKind::All, AnchorSpacing::Distance(1.0), 3, 100).unwrap().anchors.len(), 16, "the cap");
assert_eq!(add_anchors(&sq, SegmentKind::All, AnchorSpacing::Distance(0.0), 3, 100).unwrap(), sq);
assert_eq!(add_anchors(&sq, SegmentKind::Curved, AnchorSpacing::Count(1), 3, 100).unwrap(), sq, "no curves");
assert_eq!(add_anchors(&sq, SegmentKind::All, AnchorSpacing::Count(3), 9, 12).unwrap().anchors.len(), 16, "room for all of them");
assert!(add_anchors(&sq, SegmentKind::All, AnchorSpacing::Count(3), 9, 11).is_none(), "no room");
// A curve keeps its shape, and a zero-length segment gets nothing.
let bent = SubPath::new(
vec![
Anchor { h_out: pt(0.0, 50.0), ..Anchor::corner(pt(0.0, 0.0)) },
Anchor { h_in: pt(100.0, 50.0), ..Anchor::corner(pt(100.0, 0.0)) },
Anchor::corner(pt(100.0, 0.0)),
],
false,
);
let out = add_anchors(&bent, SegmentKind::Curved, AnchorSpacing::Count(3), 9, 9).unwrap();
assert_eq!(out.anchors.len(), 6);
assert!(near(length(&out), length(&bent), 1e-4));
assert_eq!(add_anchors(&bent, SegmentKind::Straight, AnchorSpacing::Count(3), 9, 9).unwrap(), bent);
}
#[test]
fn smoothing_every_anchor_reads_the_same_either_way_along_the_path() {
let zig = line(&[(0.0, 0.0), (30.0, 40.0), (70.0, 0.0), (100.0, 50.0)], false);
let mut there = zig.clone();
smooth_anchors(&mut there, SMOOTH_RATIO);
let mut back = zig.clone();
back.reverse();
smooth_anchors(&mut back, SMOOTH_RATIO);
back.reverse();
for (a, b) in there.anchors.iter().zip(&back.anchors) {
assert!(a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}");
}
assert!(there.anchors[1].kind == AnchorKind::Smooth && there.anchors[0].has_out() && there.anchors[3].has_in());
// Nothing to smooth.
for mut sp in [SubPath::default(), line(&[(1.0, 1.0)], false), line(&[(1.0, 1.0)], true)] {
let before = sp.clone();
smooth_anchors(&mut sp, SMOOTH_RATIO);
assert_eq!(sp, before);
}
}
#[test]
fn splitting_reads_an_anchors_kind_from_its_handles() {
// Smooth by its handles though it is called a corner, as a path read back from an outline is.
let run = SubPath::new(
vec![
Anchor::corner(pt(0.0, 0.0)),
Anchor { h_in: pt(40.0, 0.0), h_out: pt(60.0, 0.0), ..Anchor::corner(pt(50.0, 0.0)) },
Anchor::corner(pt(100.0, 0.0)),
Anchor::corner(pt(100.0, 50.0)),
],
false,
);
assert_eq!(split_at_anchors(&run, false, true).len(), 2);
assert_eq!(split_at_anchors(&run, true, false).len(), 2);
assert_eq!(split_at_anchors(&run, true, true).len(), 3);
assert_eq!(split_at_anchors(&run, false, false), std::slice::from_ref(&run));
let pieces = split_at_anchors(&run, true, true);
assert!(near(pieces.iter().map(length).sum::<f64>(), length(&run), 1e-6), "the shape stays");
// A closed subpath opens at its first cut.
let sq = line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], true);
assert_eq!(split_at_anchors(&sq, true, false).len(), 3);
assert!(split_at_anchors(&sq, true, false).iter().all(|p| !p.closed));
}
+2
View File
@@ -55,6 +55,8 @@ pub(crate) struct Exporter<'a> {
symbols: SymbolBoxes<'a>,
warnings: Vec<String>,
images: HashMap<String, Option<Image>>,
/// `Some` while opacity mask art is written: whether an image in it was left out.
image_left_out: Option<bool>,
/// The brush library, parsed when the first brushed stroke is written.
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// Whether the group being written is a knockout group (what its neutral children inherit).
+4
View File
@@ -14,6 +14,9 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4;
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture";
/// The warning for an image whose placement cannot be written.
pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture";
impl<'a> Exporter<'a> {
/// An exporter of `doc` writing images as `set` says; layers whose Print option is off are
/// left out.
@@ -23,6 +26,7 @@ impl<'a> Exporter<'a> {
symbols: doc.symbol_boxes().quick().with_brush_art(),
warnings: vec![],
images: HashMap::new(),
image_left_out: None,
brushes: None,
knockout: doc.page_knockout,
lab_spots: vec![],
+55 -11
View File
@@ -1,4 +1,4 @@
use super::exporter::{UNDECODED, q, writable, xf};
use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf};
use super::{Arc, BlendMode, Color, Exporter, Image, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla};
use krilla::color::device_n::{Colorant, DeviceNSpace, Process};
use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace};
@@ -57,10 +57,10 @@ impl Exporter<'_> {
/// that ink (a DeviceN space of the one ink, which lists its Separation space), Registration in
/// every process ink and every spot ink of the document, other colors in gray, RGB or CMYK as
/// the Output settings write them. The coverage is resampled as the Compression settings ask
/// ([`crate::images::coverage_sized`]). `None` when the paint isn't a solid color or the pixels
/// can't be decoded or its color channel exceeds [`vectorcraft_doc::MAX_RASTER_ALLOC`]; cached
/// like [`Self::load_image`]. With `interpolate` (and the export's own setting), viewers may
/// smooth it.
/// ([`crate::images::coverage_sized`]). `None` when the paint isn't a solid color, the image is
/// missing or left out, its pixels can't be decoded, or its color channel exceeds
/// [`vectorcraft_doc::MAX_RASTER_ALLOC`]; image rejections are cached like [`Self::load_image`].
/// With `interpolate` (and the export's own setting), viewers may smooth it.
pub(super) fn colorized_image(&mut self, im: &vectorcraft_doc::ImageObject, paint: &Paint, interpolate: bool) -> Option<Image> {
let Paint::Solid { color, swatch, tint } = paint else { return None };
let size = placed_size(im);
@@ -73,11 +73,15 @@ impl Exporter<'_> {
return i.clone();
}
let doc = self.doc;
let (width, height, alpha) = doc
let Some((width, height, alpha)) = doc
.image_blob(im)
.filter(|_| !self.left_out.contains(&im.key))
.and_then(|b| b.coverage())
.and_then(|(w, h, cover)| crate::images::coverage_sized(w, h, cover, size, self.compression))?;
.and_then(|(w, h, cover)| crate::images::coverage_sized(w, h, cover, size, self.compression))
else {
self.images.insert(cache, None);
return None;
};
let n = alpha.len();
let registration = swatch.as_deref() == Some(vectorcraft_color::swatch::REGISTRATION);
let inks: Vec<(String, [f32; 4])> = if registration {
@@ -103,7 +107,10 @@ impl Exporter<'_> {
other => (other.to_rgb().map(q).to_vec(), ImageColorspace::Rgb),
},
};
tinted_color_len(samples.len(), n)?;
if tinted_color_len(samples.len(), n).is_none() {
self.images.insert(cache, None);
return None;
}
let color = Arc::new(samples.repeat(n));
let img = Image::from_custom(Tinted { color, alpha: Arc::new(alpha), width, height, space, device_n }, interpolate).ok();
self.images.insert(cache, img.clone());
@@ -190,10 +197,23 @@ impl Exporter<'_> {
pub(super) fn image(&mut self, s: &mut Surface, im: &vectorcraft_doc::ImageObject, img: Option<Image>, pixelated: bool) {
// An image placed or sized beyond [`MAX_COORD`] is left out.
if !writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) {
if self.image_left_out.is_some() {
self.image_left_out = Some(true);
self.warn(UNWRITABLE_IMAGE);
}
return;
}
let Some(img) = img.or_else(|| self.load_image(im, placed_size(im), !pixelated)) else { return };
let Some(size) = Size::from_wh(im.width.max(1) as f32, im.height.max(1) as f32) else { return };
let Some(img) = img.or_else(|| self.load_image(im, placed_size(im), !pixelated)) else {
self.image_left_out = self.image_left_out.map(|_| true);
return;
};
let Some(size) = Size::from_wh(im.width.max(1) as f32, im.height.max(1) as f32) else {
if self.image_left_out.is_some() {
self.image_left_out = Some(true);
self.warn(UNWRITABLE_IMAGE);
}
return;
};
s.push_transform(&xf(im.xf));
s.draw_image(img, size);
s.pop();
@@ -256,7 +276,31 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee
#[cfg(test)]
mod tests {
use super::tinted_color_len;
use super::{Exporter, tinted_color_len};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Document, ImageBlob, ImageObject};
use vectorcraft_geom::Affine;
#[test]
fn colorized_image_caches_rejected_images() {
let mut doc = Document::new(10.0, 10.0);
doc.images.insert("bad".into(), ImageBlob::png(vec![1, 2, 3]));
doc.images.insert("left-out".into(), ImageBlob::png(vec![1, 2, 3]));
let settings = crate::PdfSettings::default();
let mut exporter = Exporter::new(&doc, &settings);
exporter.left_out.insert("left-out".into());
let paint = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
for key in ["missing", "bad", "left-out"] {
let image =
ImageObject { key: key.into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
assert!(exporter.colorized_image(&image, &paint, true).is_none(), "{key}");
let cache = format!("{key}\u{0}{paint:?}\u{0}1.000x1.000");
assert!(matches!(exporter.images.get(&cache), Some(None)), "rejection for {key} was not cached");
assert!(exporter.colorized_image(&image, &paint, true).is_none(), "second call for {key}");
}
assert_eq!(exporter.images.len(), 3);
}
#[test]
fn tinted_color_rejects_oversized_and_overflowing_buffers() {
+19 -3
View File
@@ -7,7 +7,7 @@ use super::{
impl Exporter<'_> {
/// Opacity mask → luminosity soft mask. Outside the art the backdrop is black (clip) or white;
/// invert is a white Difference rect on top (luminance is linear, so luma(1 − c) = 1 − luma(c)).
fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> krilla::mask::Mask {
fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> Option<krilla::mask::Mask> {
let mut sb = s.stream_builder();
let mut ms = sb.surface();
// An opaque backdrop when it matters: white outside the art (no clip), or black for the
@@ -19,15 +19,21 @@ impl Exporter<'_> {
// and has no inks to overprint.
let knockout = std::mem::take(&mut self.knockout);
let overprint = std::mem::take(&mut self.overprint);
let image_left_out = self.image_left_out.replace(false);
self.node(&mut ms, &m.art, page, true);
let incomplete = self.image_left_out.unwrap_or(false);
self.image_left_out = image_left_out.map(|outer| outer || incomplete);
(self.knockout, self.overprint) = (knockout, overprint);
if incomplete {
return None;
}
if m.invert {
ms.push_blend_mode(krilla::blend::BlendMode::Difference);
cover(&mut ms, page, 255, 1.0);
ms.pop();
}
ms.finish();
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)
Some(krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity))
}
/// The children of a group, as the elements of a knockout group when it is one.
@@ -143,7 +149,13 @@ impl Exporter<'_> {
if let Some(m) = mask
&& alpha.is_none()
{
let mask = self.soft_mask(s, m, page);
let Some(mask) = self.soft_mask(s, m, page) else {
self.knockout = enclosing;
for _ in 0..pushes {
s.pop();
}
return;
};
s.push_mask(mask);
pushes += 1;
}
@@ -188,8 +200,12 @@ impl Exporter<'_> {
if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) {
self.image(s, im, Some(colorized), n.extras().pixelated);
} else {
self.image_left_out = self.image_left_out.map(|_| true);
self.warn(UNDECODED);
}
} else if self.image_left_out.is_some() {
self.image_left_out = Some(true);
self.warn(super::exporter::UNWRITABLE_IMAGE);
}
}
_ => self.image(s, im, alpha, n.extras().pixelated),
+2 -7
View File
@@ -48,13 +48,11 @@ impl<'p> Builder<'p> {
taken: vec![],
scan: Scan::default(),
tag_at: 0,
group_at: 0,
paint_at: 0,
aligned: true,
route,
unsure: false,
marked: vec![],
pending: false,
nested: 0,
white_images: false,
last_fill: None,
@@ -103,8 +101,7 @@ impl<'p> Builder<'p> {
self.mask = None;
self.masked.clear();
self.marked.clear();
self.pending = false;
(self.scan, self.tag_at, self.group_at, self.aligned, self.paint_at) = (scan, 0, 0, true, 0);
(self.scan, self.tag_at, self.aligned, self.paint_at) = (scan, 0, true, 0);
if self.scan.overprints && self.scan.zero_mode {
self.warn(OVERPRINT_ZERO_MODE);
}
@@ -478,14 +475,12 @@ impl<'p> Builder<'p> {
blend: std::mem::replace(&mut self.blend, BlendMode::Normal),
mask: self.mask.take(),
page: std::mem::replace(&mut self.page, page),
pending: std::mem::take(&mut self.pending),
};
self.nested += 1;
read(self);
let art = self.close_frames();
self.nested -= 1;
(self.stack, self.root_groups, self.blend, self.mask, self.page, self.pending) =
(saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page, saved.pending);
(self.stack, self.root_groups, self.blend, self.mask, self.page) = (saved.stack, saved.root_groups, saved.blend, saved.mask, saved.page);
Some(art)
}
+14 -18
View File
@@ -35,11 +35,9 @@ impl<'a> Device<'a> for Builder<'_> {
self.flush_glyphs();
let walked = self.walked(false);
if self.hold_glyph_stroke(path, transform, paint, draw_mode, walked) {
self.pending = false;
return;
}
self.flush_text();
self.pending = false;
let overprint = self.path_overprint();
let mut bp = path.clone();
bp.apply_affine(transform);
@@ -140,17 +138,6 @@ impl<'a> Device<'a> for Builder<'_> {
fn push_clip_path(&mut self, clip_path: &ClipPath) {
self.flush();
// A form's box right after its transparency group: the group's isolate and knockout
// flags are the next ones read from the file.
if std::mem::take(&mut self.pending) {
let flags = self.scan.groups.get(self.group_at).copied();
self.group_at += 1;
if let Some((i, k)) = flags
&& let Some(Frame { kind: FrameKind::Group { isolate, knockout, .. }, .. }) = self.stack.last_mut()
{
(*isolate, *knockout) = (i, k);
}
}
// Clips that contain the whole page do nothing visible; don't create groups for them. Only
// a polygon that really covers it counts: a diamond touching the page edges has the page
// as its bounding box but cuts its corners away (#1542).
@@ -165,7 +152,6 @@ impl<'a> Device<'a> for Builder<'_> {
self.flush();
let mask = mask.map(|m| self.soft_mask(&m));
self.stack.push(Frame::new(FrameKind::Group { opacity, blend: blend(blend_mode), mask, isolate: false, knockout: false }));
self.pending = self.nested == 0;
// Blend mode applies to the group as a whole, not to its children.
self.blend = BlendMode::Normal;
}
@@ -182,7 +168,6 @@ impl<'a> Device<'a> for Builder<'_> {
if matches!(draw_mode, GlyphDrawMode::Clip) {
return;
}
self.pending = false;
let stroke = match draw_mode {
// Invisible text (a scanned page's recognized text, over the scan) draws nothing but
// is still text: type with neither fill nor stroke, so it stays searchable.
@@ -241,7 +226,6 @@ impl<'a> Device<'a> for Builder<'_> {
fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) {
self.flush_glyphs();
self.flush_text();
self.pending = false;
match image {
Image::Raster(r) => {
let white = self.white_images;
@@ -328,13 +312,25 @@ impl<'a> Device<'a> for Builder<'_> {
fn pop_clip_path(&mut self) {
self.flush();
self.pending = false;
self.pop_frame();
}
// The interpreter tells the flags of a form's group right after pushing it. (It draws a group
// that adds nothing straight onto its parent, without pushing it.)
fn set_knockout(&mut self) {
if let Some(Frame { kind: FrameKind::Group { knockout, .. }, .. }) = self.stack.last_mut() {
*knockout = true;
}
}
fn set_isolated(&mut self) {
if let Some(Frame { kind: FrameKind::Group { isolate, .. }, .. }) = self.stack.last_mut() {
*isolate = true;
}
}
fn pop_transparency_group(&mut self) {
self.flush();
self.pending = false;
self.pop_frame();
}
-4
View File
@@ -69,7 +69,6 @@ pub(super) struct Saved {
pub(super) blend: BlendMode,
pub(super) mask: Option<Arc<MaskSpec>>,
pub(super) page: Rect,
pub(super) pending: bool,
}
pub(super) struct Builder<'p> {
@@ -129,7 +128,6 @@ pub(super) struct Builder<'p> {
/// The page as walked by [`scan_page`], and how far the interpreter is through it.
pub(super) scan: Scan,
pub(super) tag_at: usize,
pub(super) group_at: usize,
/// The fills and strokes of paths drawn so far ([`Scan::paints`]).
pub(super) paint_at: usize,
pub(super) aligned: bool,
@@ -140,8 +138,6 @@ pub(super) struct Builder<'p> {
pub(super) unsure: bool,
/// The marked-content sequences open: the group each marks.
pub(super) marked: Vec<Option<usize>>,
/// A transparency group was just pushed: a form's (whose flags come next) or an image's.
pub(super) pending: bool,
pub(super) nested: u32,
/// Reading an alpha soft mask's art: images are read white with their own alpha, so the
/// mask's luminance is their alpha, as whitened vector art's is (cairo, and so Inkscape,
+9 -20
View File
@@ -1,17 +1,15 @@
//! What the interpreter doesn't tell the import, read from the file itself: the optional content
//! groups (layers) with their states and nesting, which group each marked-content sequence belongs
//! to, the isolate and knockout flags of transparency groups, the overprint parameters each path
//! and each stretch of text is painted with, the Separation and DeviceN inks they are painted in
//! (by their colorant names, which the interpreter drops), and the names of the fonts.
//! to, the overprint parameters each path and each stretch of text is painted with, the Separation
//! and DeviceN inks they are painted in (by their colorant names, which the interpreter drops), and
//! the names of the fonts.
//!
//! hayro-interpret reports a marked-content sequence by its tag alone and a transparency group
//! without its flags, and skips the content of groups that are off. So each page's content is
//! walked here in the interpreter's order (page content, then form XObjects as they are drawn,
//! skipping what it skips): the k-th `BDC`/`BMC` it reports is the k-th one found here (its tag
//! checks that), the k-th form transparency group is the k-th group found here, and the k-th
//! path it fills or strokes is the k-th one painted here (the page's count checks that). To import
//! content that is off as hidden layers, [`all_on`] gives the file an update that turns every
//! group on.
//! hayro-interpret reports a marked-content sequence by its tag alone and skips the content of
//! groups that are off. So each page's content is walked here in the interpreter's order (page
//! content, then form XObjects as they are drawn, skipping what it skips): the k-th `BDC`/`BMC` it
//! reports is the k-th one found here (its tag checks that), and the k-th path it fills or strokes
//! is the k-th one painted here (the page's count checks that). To import content that is off as
//! hidden layers, [`all_on`] gives the file an update that turns every group on.
use std::collections::{HashMap, HashSet};
@@ -258,8 +256,6 @@ pub(crate) struct Scan {
/// Each marked-content sequence: its tag ([`tag_key`]) and the group (index into
/// [`Ocgs::list`]) it marks.
pub tags: Vec<(u64, Option<usize>)>,
/// Each form transparency group: isolated, knockout.
pub groups: Vec<(bool, bool)>,
/// Content was incomplete or a scan limit was reached. No document may be returned from
/// this scan, since its routing no longer describes every object the interpreter draws.
pub cut: bool,
@@ -846,13 +842,6 @@ impl Walker<'_, '_> {
self.hidden_form |= !self.is_visible();
}
if self.is_visible() {
if let Some(g) = d.get::<Dict<'_>>(b"Group") {
if self.out.groups.len() >= MAX_GROUPS {
self.out.cut = true;
return;
}
self.out.groups.push((g.get::<bool>(b"I").unwrap_or(false), g.get::<bool>(b"K").unwrap_or(false)));
}
// (Its own resources, or without any those of what draws it: as the interpreter reads them.)
let inner = Resources::from_scope(d.get::<Dict<'_>>(b"Resources"), res.clone());
self.save();
+71
View File
@@ -973,6 +973,77 @@ fn opacity_mask_exports_as_luminosity_soft_mask() {
assert!(text.contains("/Luminosity"));
}
/// The warnings and path count after exporting an image mask and a separate rectangle.
fn image_mask_report(colorized: bool, available: bool, nested: bool, unwritable: bool) -> (Vec<String>, usize) {
let mut d = doc(100.0, 100.0);
if available {
d.images.insert("mask-image".into(), ImageBlob::png(tiny_png()));
}
let im = ImageObject {
key: "mask-image".into(),
width: 4,
height: 2,
xf: Affine::translate(if unwritable { (1e10, 1e10) } else { (10.0, 10.0) }) * Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut art = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
if colorized {
art.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))));
}
if nested {
let mut outer_art = rect_node(Rect::new(10.0, 10.0, 50.0, 30.0), Color::WHITE);
outer_art.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false)));
art = outer_art;
}
let mut masked = rect_node(Rect::new(10.0, 10.0, 50.0, 30.0), Color::rgb(1.0, 0.0, 0.0));
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false)));
add(&mut d, masked);
add(&mut d, rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::BLACK));
let report = export_with_report(&d, &PdfOptions::uncompressed()).expect("export");
let imported = import(&report.bytes).expect("import");
let paths = leaves(&imported).into_iter().filter(|n| n.path_data().is_some()).count();
(report.warnings, paths)
}
#[test]
fn missing_colorized_image_in_unclipped_mask_omits_masked_object() {
let (warnings, paths) = image_mask_report(true, false, false, false);
assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{warnings:?}");
assert_eq!(paths, 1);
}
#[test]
fn missing_plain_image_in_unclipped_mask_omits_masked_object() {
let (warnings, paths) = image_mask_report(false, false, false, false);
assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{warnings:?}");
assert_eq!(paths, 1);
}
#[test]
fn missing_image_in_nested_mask_omits_outer_masked_object() {
let (warnings, paths) = image_mask_report(false, false, true, false);
assert!(warnings.iter().any(|w| w == "an image couldn't be decoded and is missing from the picture"), "{warnings:?}");
assert_eq!(paths, 1);
}
#[test]
fn writable_colorized_image_in_unclipped_mask_keeps_masked_object() {
let (warnings, paths) = image_mask_report(true, true, false, false);
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(paths, 2);
}
#[test]
fn unwritable_images_in_unclipped_masks_omit_masked_objects() {
for colorized in [false, true] {
let (warnings, paths) = image_mask_report(colorized, true, false, true);
assert!(warnings.iter().any(|w| w == "an image couldn't be written and is missing from the picture"), "{warnings:?}");
assert_eq!(paths, 1, "colorized: {colorized}");
}
}
#[test]
fn empty_and_populated_file_info_preserve_key_presence() {
let mut d = doc(100.0, 100.0);
+35
View File
@@ -241,6 +241,41 @@ fn isolate_and_knockout_flags_of_a_group_are_kept() {
assert!(all(&d).iter().all(|n| !matches!(n.kind, NodeKind::Group { .. })));
}
#[test]
fn knockout_groups_after_a_group_drawn_straight_keep_their_flag() {
// Two knockout groups (ISO 32000-1, 11.4.6.3), each of a full-opacity element and a 50% one,
// both elements groups of their own. A full-opacity element adds nothing as a group and is
// drawn straight onto its parent; the knockout group after it still knocks out.
let x = first_extra(1);
let ring = |at: usize| {
let res = format!("/ExtGState << /A << /ca 1 >> /B << /ca 0.5 >> >> /XObject << /E {} 0 R /F {} 0 R >>", at, at + 1);
stream(
&format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /K true >> /Resources << {res} >>"),
"q /A gs /E Do Q q /B gs /F Do Q",
)
};
let element = |art: &str| stream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >>", art);
let d = open(&one_page(
"/X0 Do /X1 Do",
&format!("/XObject << /X0 {x} 0 R /X1 {} 0 R >>", x + 1),
&[
&ring(x + 2),
&ring(x + 4),
&element("0 0 1 rg 10 10 40 40 re f"),
&element("0 0 1 rg 20 20 20 20 re f"),
&element("0 0 1 rg 50 50 40 40 re f"),
&element("0 0 1 rg 60 60 20 20 re f"),
],
));
let groups: Vec<Node> = all(&d).into_iter().filter(|n| matches!(n.kind, NodeKind::Group { .. })).collect();
assert_eq!(groups.len(), 2, "{groups:?}");
for g in &groups {
assert_eq!(g.knockout, Knockout::On, "{g:?}");
let opacities: Vec<f32> = g.children().unwrap().iter().map(|c| c.opacity).collect();
assert_eq!(opacities, [1.0, 0.5]);
}
}
// ---------- tiling patterns ----------
#[test]
+2 -2
View File
@@ -63,9 +63,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.151"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
+10 -3
View File
@@ -43,11 +43,12 @@ pub(super) enum KeptImage {
/// The image on its own grid, as [`Renderer::rasterize_image`] makes it, and how many images
/// in the content failed to decode while it was made ([`crate::paint::decode_failures`]):
/// each draw of the image from here counts them again ([`crate::paint::add_decode_failures`]).
Grid(std::rc::Rc<(Vec<u8>, usize, usize)>, u64),
/// The last value records whether an image was left out while making the grid.
Grid(std::rc::Rc<(Vec<u8>, usize, usize)>, u64, bool),
/// An image over [`Renderer::rasterize_image`]'s limits: the content's raster with the
/// Rasterize applied, as the first draw made it, and the transform from its pixels to
/// document space.
Raster(Arc<vello_cpu::Pixmap>, Affine),
/// document space. The remaining values record decode failures and whether an image was left out.
Raster(Arc<vello_cpu::Pixmap>, Affine, u64, bool),
}
/// A cached shadow / glow raster: premultiplied, already tinted and faded, positioned relative to
@@ -71,6 +72,12 @@ pub(crate) struct ShadowEntry {
/// Made for the object before it moved ([`Renderer::move_shadow`]), or made over rasters
/// made before their objects moved: only a frame rendered while interacting draws it.
pub(super) moved: bool,
/// How many images in the silhouette failed to decode while the raster was made, as
/// [`PixelEntry::failed`].
pub(super) failed: u64,
/// Whether an image in the silhouette failed to draw while the raster was made, as
/// [`PixelEntry::image_left_out`].
pub(super) image_left_out: bool,
pub(crate) stamp: u64,
}
+24 -5
View File
@@ -40,7 +40,11 @@ impl Renderer {
) {
let chain: Vec<&RasterFx> = rfx.iter().filter(content_changing).collect();
// When the first draw of this content kept its raster, that raster is drawn.
if let Some(KeptImage::Raster(image, place)) = content.kept.and_then(|k| k.image.borrow().clone()) {
if let Some(KeptImage::Raster(image, place, failed, image_left_out)) = content.kept.and_then(|k| k.image.borrow().clone()) {
crate::paint::add_decode_failures(failed);
if image_left_out {
self.image_left_out = self.image_left_out.map(|_| true);
}
draw_placed(ctx, image, f.view * place);
return;
}
@@ -131,6 +135,9 @@ impl Renderer {
let p = f.view * e.anchor;
let (image, at, k) = (e.image.clone(), ((p.x + e.rel.0).round(), (p.y + e.rel.1).round()), e.k);
crate::paint::add_decode_failures(e.failed);
if e.image_left_out {
self.image_left_out = self.image_left_out.map(|_| true);
}
draw_scaled(ctx, image, at, k);
return;
}
@@ -151,23 +158,32 @@ impl Renderer {
let frame = Frame { mt: false, view, visible: to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), px, ..*f };
let line = 72.0 / ppi;
let (before, decoded) = (self.stats.moved, crate::paint::decode_failures());
let outer_image_left_out = self.image_left_out.replace(false);
let pattern_images_left_out = crate::pattern::images_left_out();
// A Rasterize first in the chain draws the content on its image's own grid instead, unless
// that image is too large: the content is drawn once.
let mut rasterized = match chain.first() {
Some(RasterFx::Rasterize(r)) => {
let rect = r.image(content.bounds.unwrap_or(content.reach), line);
let kept = content.kept.and_then(|k| match &*k.image.borrow() {
Some(KeptImage::Grid(image, failed)) => {
Some(KeptImage::Grid(image, failed, image_left_out)) => {
crate::paint::add_decode_failures(*failed);
if *image_left_out {
self.image_left_out = self.image_left_out.map(|_| true);
}
Some(image.clone())
}
_ => None,
});
let image = kept.or_else(|| {
let failures = crate::paint::decode_failures();
let outer_image_left_out = self.image_left_out.replace(false);
let pattern_images_left_out = crate::pattern::images_left_out();
let image = self.rasterize_image(f, r, rect, paint).map(std::rc::Rc::new);
let left_out = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out;
self.image_left_out = outer_image_left_out.map(|outer| outer || left_out);
if let (Some(k), Some(image)) = (content.kept, &image) {
*k.image.borrow_mut() = Some(KeptImage::Grid(image.clone(), crate::paint::decode_failures() - failures));
*k.image.borrow_mut() = Some(KeptImage::Grid(image.clone(), crate::paint::decode_failures() - failures, left_out));
}
image
});
@@ -190,6 +206,8 @@ impl Renderer {
off.render(&mut pm, &mut self.resources);
}
let failed = crate::paint::decode_failures() - decoded;
let image_left_out = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out;
self.image_left_out = outer_image_left_out.map(|outer| outer || image_left_out);
// Content drawn over moved rasters makes a moved raster.
let moved = self.stats.moved > before;
// What the raster is made from, for its object once it moves (`move_pixel_content`): a
@@ -258,7 +276,8 @@ impl Renderer {
let rel = (x0 - p.x, y0 - p.y);
let owner = content.owner.cloned().or_else(|| self.fx_owner.clone().filter(|o| std::ptr::eq(&**o, content.node)));
let node = Drawn::of(content.node, owner.as_ref());
let entry = PixelEntry { node, linear, anchor, rel, k, image: image.clone(), view: in_view, made, inputs, moved, failed, stamp };
let entry =
PixelEntry { node, linear, anchor, rel, k, image: image.clone(), view: in_view, made, inputs, moved, failed, image_left_out, stamp };
self.pixel_fx.insert(key, entry);
self.trim_fx_rasters(FX_RASTER_BUDGET);
}
@@ -266,7 +285,7 @@ impl Renderer {
match content.kept.filter(|kept| kept.image.borrow().is_none()) {
Some(kept) => {
let place = f.view.inverse() * Affine::translate((x0, y0)) * Affine::scale(1.0 / k);
*kept.image.borrow_mut() = Some(KeptImage::Raster(image.clone(), place));
*kept.image.borrow_mut() = Some(KeptImage::Raster(image.clone(), place, failed, image_left_out));
if f.view == call { draw_scaled(ctx, image, (x0, y0), k) } else { draw_placed(ctx, image, call * place) }
}
None => draw_scaled(ctx, image, (x0, y0), k),
+4 -1
View File
@@ -89,7 +89,7 @@ pub(crate) struct PixelEntry {
pub(super) anchor: vectorcraft_geom::Point,
pub(super) rel: (f64, f64),
pub(super) k: f64,
pub(super) image: std::sync::Arc<vello_cpu::Pixmap>,
pub(crate) image: std::sync::Arc<vello_cpu::Pixmap>,
/// For a raster of the content's whole reach at full size, `None`: it draws after a pan too.
/// For one cropped to the view, or made at a lower resolution, the view and the rect it was
/// made for: it draws only there, so dragging other art over the object keeps it (a wide blur,
@@ -107,6 +107,9 @@ pub(crate) struct PixelEntry {
/// ([`crate::paint::decode_failures`]): each frame that draws the raster counts them
/// again ([`crate::paint::add_decode_failures`]).
pub(super) failed: u64,
/// Whether an image in the content failed to draw while the raster was made: each frame that
/// draws the raster inside opacity-mask art notes it again.
pub(crate) image_left_out: bool,
pub(crate) stamp: u64,
}
+14 -1
View File
@@ -62,6 +62,10 @@ impl Renderer {
Some(e) => {
e.stamp = stamp;
self.stats.moved += usize::from(e.moved);
crate::paint::add_decode_failures(e.failed);
if e.image_left_out {
self.image_left_out = self.image_left_out.map(|_| true);
}
let p = f.view * e.anchor;
(e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.map(|v| v.served(f.view)))
}
@@ -118,7 +122,13 @@ impl Renderer {
let ink = darkness.map_or(f.ink, |d| f.ink.darkened(d));
let crop = Frame { mt: false, view, visible, ink, ..*f };
let before = self.stats.moved;
let decoded = crate::paint::decode_failures();
let outer_image_left_out = self.image_left_out.replace(false);
let pattern_images_left_out = crate::pattern::images_left_out();
self.inside_layer(|r| paint(r, &mut off, &shifted(&crop, dx, dy)));
let failed = crate::paint::decode_failures() - decoded;
let image_left_out = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out;
self.image_left_out = outer_image_left_out.map(|outer| outer || image_left_out);
// A silhouette drawn over moved rasters makes a moved shadow.
let moved = self.stats.moved > before;
off.flush();
@@ -165,7 +175,10 @@ impl Renderer {
let node = Drawn::of(n, owner);
let rel = (x0 - p.x, y0 - p.y);
let view = cropped.map(|room| ViewCrop::of(f.view, room));
self.shadows.insert(key, ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, view, made, inputs, moved, stamp });
self.shadows.insert(
key,
ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, view, made, inputs, moved, failed, image_left_out, stamp },
);
self.trim_fx_rasters(FX_RASTER_BUDGET);
(image, x0, y0, scale, moved, cropped)
}
+2
View File
@@ -151,6 +151,8 @@ pub struct Renderer {
/// The picture [`Self::flatten`] started the current context again from, with 8-bit
/// compositing: [`Self::finish`] renders the context over it.
picture: Option<Arc<Pixmap>>,
/// Whether an image failed to draw while opacity-mask art is being drawn.
image_left_out: Option<bool>,
/// Pixels of the groups being drawn offscreen (contexts and backdrop copies), and the most
/// they may hold (set from the frame when the first opens, see [`Self::group`]); both reset
/// at the start of every frame.
+17
View File
@@ -25,6 +25,23 @@ pub(crate) fn single_plain_fill(n: &Node) -> bool {
matches!((painted.next(), painted.next()), (Some(AppearanceItem::Fill(f)), None) if f.blend == vectorcraft_color::BlendMode::Normal && f.opacity >= 1.0 && !matches!(f.paint, vectorcraft_color::Paint::Pattern { .. }))
}
/// A knockout element whose opaque paint covers exactly its knockout shape. The caller limits
/// source-over substitution to binary coverage, retaining analytical AA's intermediate rounding.
pub(crate) fn opaque_knockout_fill(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
&& n.opacity >= 1.0
&& n.blend == vectorcraft_color::BlendMode::Normal
&& !n.isolate
&& n.extras().mask.is_none()
&& !crate::fx::has_fx(n)
&& !crate::fx::has_object_fx(n)
&& single_plain_fill(n)
&& n.appearance
.items
.iter()
.any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && matches!(f.paint, vectorcraft_color::Paint::Solid { .. })))
}
/// Number of visible painted fill/stroke items (opacity folding is exact only for one). A dashed
/// stroke is one paint: its dashes are outlined into one path and filled once, so overlapping
/// dashes don't darken where they overlap. A dashed brush stroke draws its pieces one by one, so
+26 -7
View File
@@ -93,6 +93,9 @@ struct TileEntry {
/// ([`crate::paint::decode_failures`]): each frame that draws from the tile counts them
/// again ([`crate::paint::add_decode_failures`]).
failed: u64,
/// Whether an image in the art failed to draw while the tile was drawn: each frame that draws
/// from the tile counts it again ([`images_left_out`]).
image_left_out: bool,
}
struct PatternCache {
@@ -129,6 +132,13 @@ impl PatternCache {
thread_local! {
static CACHE: RefCell<PatternCache> = RefCell::new(PatternCache::default());
static IMAGES_LEFT_OUT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many pattern tiles drawn on this thread so far left out an image of their art: opacity-mask
/// art compares the count before and after it draws ([`Renderer::mask_values`]).
pub(crate) fn images_left_out() -> u64 {
IMAGES_LEFT_OUT.with(std::cell::Cell::get)
}
fn same_art(a: &[Arc<Node>], b: &[Arc<Node>]) -> bool {
@@ -159,12 +169,14 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 {
/// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as
/// `ink` paints them.
fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w: u16, h: u16, ink: Ink) -> Pixmap {
fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w: u16, h: u16, ink: Ink) -> (Pixmap, bool) {
let (w, h) = (w.max(1), h.max(1));
let mut ctx = crate::single_threaded_context(w, h);
let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9))
* Affine::translate(-region.origin().to_vec2());
let opts = RenderOptions::default();
r.image_left_out = Some(false);
let pattern_images_left_out = images_left_out();
r.check_plugins();
r.check_symbols(doc);
let symbols = doc.symbol_boxes().quick();
@@ -188,7 +200,7 @@ fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, w
r.draw_arc(&mut ctx, &frame, a);
}
}
r.finish(&mut ctx, r.raster)
(r.finish(&mut ctx, r.raster), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
}
/// Run `f` with the shared off-screen renderer (None when nested too deep: a pattern whose art
@@ -258,22 +270,28 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
&& std::ptr::eq(e.cms.as_ptr(), Arc::as_ptr(&cms))
&& e.deps.as_ref().is_none_or(|d| d.current(doc))
})
.map(|e| (e.pixmap.clone(), e.sx, e.sy, e.failed))
.map(|e| (e.pixmap.clone(), e.sx, e.sy, e.failed, e.image_left_out))
});
let (pm, sx, sy) = match hit {
Some((pm, sx, sy, failed)) => {
Some((pm, sx, sy, failed, image_left_out)) => {
crate::paint::add_decode_failures(failed);
if image_left_out {
IMAGES_LEFT_OUT.with(|n| n.set(n.get().saturating_add(1)));
}
(pm, sx, sy)
}
None => {
let w = (pw * scale).ceil().clamp(1.0, 4096.0) as u16;
let h = (ph * scale).ceil().clamp(1.0, 4096.0) as u16;
let before = crate::paint::decode_failures();
let Some(pm) = with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), w, h, ink)) else {
let Some((pm, image_left_out)) = with_tile_renderer(|r| rasterize(r, doc, def, Rect::new(0.0, 0.0, pw, ph), w, h, ink)) else {
ctx.set_paint(missing());
return true;
};
let failed = crate::paint::decode_failures() - before;
if image_left_out {
IMAGES_LEFT_OUT.with(|n| n.set(n.get().saturating_add(1)));
}
let pm = Arc::new(pm);
let (sx, sy) = (w as f64 / pw, h as f64 / ph);
let deps = crate::fx::Reads::of_all(def.art.iter().map(|a| &**a)).any().then(|| Deps::of(doc));
@@ -285,7 +303,8 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
let mut c = c.borrow_mut();
let tiles = &mut c.tiles[ink.index()];
let (t, bytes) = (tiles.tick(), size_of::<TileEntry>() + w as usize * h as usize * 4);
let entry = TileEntry { art: def.art.clone(), deps, cms: Arc::downgrade(&cms), params, sx, sy, pixmap: pm.clone(), failed };
let entry =
TileEntry { art: def.art.clone(), deps, cms: Arc::downgrade(&cms), params, sx, sy, pixmap: pm.clone(), failed, image_left_out };
tiles.insert(key, entry, bytes, t);
});
(pm, sx, sy)
@@ -304,7 +323,7 @@ pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Re
let side = w.max(h);
let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side));
let px = size.clamp(1, 1024) as u16;
let pm = with_tile_renderer(|r| rasterize(r, doc, def, region, px, px, Ink::Display))?;
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, px, px, Ink::Display))?;
Some(Rendered { width: px as u32, height: px as u32, pixels: pm.data_as_u8_slice().to_vec() })
}
+7 -1
View File
@@ -65,6 +65,7 @@ impl Renderer {
blends: PtrMap::default(),
clip_paths: vec![],
picture: None,
image_left_out: None,
offscreen_live: 0,
offscreen_budget: 0,
symbol_nodes: 0,
@@ -128,7 +129,12 @@ impl Renderer {
self.begin_frame();
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
let pixels = self.mask_values(&frame, m, w, h).into_iter().flat_map(|v| [v, v, v, 255]).collect();
let pixels = self
.mask_values(&frame, m, w, h)
.unwrap_or_else(|| vec![0; w as usize * h as usize])
.into_iter()
.flat_map(|v| [v, v, v, 255])
.collect();
self.end_frame();
self.stats.symbol_art = symbols.art_measured();
self.stats.micros = now().saturating_sub(start);
+2
View File
@@ -121,6 +121,8 @@ impl Renderer {
}
} else if f.opts.mark_undecoded_images && !pending && (!outline || f.doc.setup.outline_images) {
self.draw_undecoded_mark(ctx, f, im, area);
} else if !pending && !outline {
self.image_left_out = self.image_left_out.map(|_| true);
}
if outline {
let mut p = rect.to_path(0.1);
+23 -4
View File
@@ -166,9 +166,9 @@ impl Renderer {
// mask is rendered over those only.
let bounds = self.bounds_of(f.symbols, a);
let Some((r, sub)) = group::area(ctx, f, bounds) else { return };
let mask = Some(self.mask_values(&sub, m, r.w, r.h));
let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return };
let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a));
self.group(ctx, f, Composite { mask, blends, bounds, ..Default::default() }, &mut |r, c, fr| r.draw_arc_body(c, fr, a));
self.group(ctx, f, Composite { mask: Some(mask), blends, bounds, ..Default::default() }, &mut |r, c, fr| r.draw_arc_body(c, fr, a));
return;
}
self.draw_arc_body(ctx, f, a);
@@ -176,7 +176,7 @@ impl Renderer {
/// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen,
/// as luminance ([`mask_value`]).
pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Vec<u8> {
pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option<Vec<u8>> {
let mut mctx = f.offscreen_context(w, h);
// Mask art is a picture of its own: it takes no part in a knockout group around the object,
// and its luminance is that of its screen colours.
@@ -187,10 +187,22 @@ impl Renderer {
std::mem::take(&mut self.clip_paths),
self.picture.take(),
);
let image_left_out = self.image_left_out.replace(false);
let failures = crate::paint::decode_failures();
let pattern_images_left_out = crate::pattern::images_left_out();
self.draw_kept_node(&mut mctx, &Frame { mt: false, ink: Ink::Display, ..*f }, &m.art);
// Pattern tiles are drawn without undecoded-image marks, so an image a tile left out counts
// with the marks on too.
let incomplete = self.image_left_out.unwrap_or(false)
|| crate::pattern::images_left_out() > pattern_images_left_out
|| (!f.opts.mark_undecoded_images && crate::paint::decode_failures() > failures);
self.image_left_out = image_left_out.map(|outer| outer || incomplete);
let pm = self.finish(&mut mctx, self.raster);
(self.knockout, self.nested, self.backdrop, self.clip_paths, self.picture) = outer;
pm.data().iter().map(|p| mask_value(p.r, p.g, p.b, p.a, m.clip, m.invert)).collect()
if incomplete {
return None;
}
Some(pm.data().iter().map(|p| mask_value(p.r, p.g, p.b, p.a, m.clip, m.invert)).collect())
}
/// Everything [`Self::draw_arc`] does after culling.
@@ -593,6 +605,13 @@ impl Renderer {
if self.skipped(f, c) {
continue;
}
// Hard-edge coverage is binary, so an opaque fill replaces its knockout shape exactly.
// This also serves supersampled exports. Analytical AA keeps the erase/add passes:
// their intermediate rounding can differ from source-over at partially covered edges.
if f.opts.anti_alias == crate::AntiAlias::None && crate::node_checks::opaque_knockout_fill(c) {
self.draw_arc(ctx, f, c);
continue;
}
self.knockout_pass(ctx, f, c, Compose::DestOut);
match &backdrop {
Some(b) => self.knockout_over(ctx, f, c, b),
+223
View File
@@ -748,6 +748,229 @@ fn opacity_mask_without_clip_and_inverted() {
assert_eq!(img.pixel(80, 50), [255, 0, 0, 255], "inverted clip background → visible");
}
#[test]
fn opacity_mask_with_undecodable_image_leaves_out_object() {
use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask};
let mut d = Document::new(100.0, 100.0);
d.images.insert("broken-mask-image".into(), ImageBlob::new("image/png", b"not a PNG".to_vec()));
let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let image = ImageObject {
key: "broken-mask-image".into(),
width: 20,
height: 20,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let mut image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
image.appearance.effects.push(Effect { id: "blur.gaussian".into(), params: serde_json::json!({"radius": 4.0}), visible: true });
let white = rect_node(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), Paint::solid(Color::WHITE), Paint::None, 0.0);
let art = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(image)]);
object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
let object_id = object.id;
d.insert(Some(d.layers[0].id), 0, object).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let pending = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { kept_images_only: true, ..opts.clone() });
assert_eq!(pending.pixel(70, 70), [255, 0, 0, 255], "an image awaiting decoding does not invalidate the mask");
let mut renderer = Renderer::new();
let img = renderer.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(img.pixel(70, 70), [255, 255, 255, 255], "missing mask image leaves out the object");
let again = renderer.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(again.pixel(70, 70), [255, 255, 255, 255], "the cached raster keeps the mask incomplete");
let mask_view = renderer.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mask_view: Some(object_id), ..opts.clone() });
assert_eq!(mask_view.pixel(70, 70), [0, 0, 0, 255], "an incomplete mask view has no coverage");
let marked = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mark_undecoded_images: true, ..opts.clone() });
assert_eq!(marked.pixel(70, 70), [255, 0, 0, 255], "the undecoded-image mark remains part of the mask");
let kept = RenderOptions { kept_images_only: true, ..opts.clone() };
for frame in 0..2 {
let img = renderer.render(&d, 100, 100, Affine::IDENTITY, &kept);
assert_eq!(img.pixel(70, 70), [255, 255, 255, 255], "an image already known undecodable leaves out the object on frame {frame}");
}
let working = Renderer::new().render(&masked_doc(false, false), 100, 100, Affine::IDENTITY, &opts);
assert_eq!(working.pixel(80, 50), [255, 0, 0, 255], "a complete mask still draws the object");
}
#[test]
fn opacity_mask_with_missing_image_in_pattern_leaves_out_object() {
use vectorcraft_doc::pattern::{PatternDef, pattern_paint};
use vectorcraft_doc::{ImageObject, NodeKind, OpacityMask};
let mut d = Document::new(100.0, 100.0);
let image = ImageObject {
key: "missing-pattern-image".into(),
width: 20,
height: 20,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
let mut pattern = PatternDef::new("Missing image", vec![Arc::new(image)]);
pattern.tile = Rect::new(0.0, 0.0, 20.0, 20.0);
d.patterns.push(pattern);
let art = rect_node(&mut d, Rect::new(10.0, 10.0, 50.0, 90.0), pattern_paint("Missing image"), Paint::None, 0.0);
let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
d.insert(Some(d.layers[0].id), 0, object).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let mut r = Renderer::new();
for frame in 0..2 {
let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(img.pixel(70, 50), [255, 255, 255, 255], "frame {frame}: incomplete pattern mask leaves out the object");
}
// Pattern tiles draw no undecoded-image mark, so the object stays out with the marks on too.
let marked = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { mark_undecoded_images: true, ..opts.clone() });
assert_eq!(marked.pixel(70, 50), [255, 255, 255, 255], "a tile without the mark leaves out the object");
}
#[test]
fn complete_image_mask_with_blur_reuses_cached_raster() {
use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask};
let mut png = Vec::new();
image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(20, 20, image::Rgba([255, 255, 255, 255])))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let mut d = Document::new(100.0, 100.0);
d.images.insert("complete-mask-image".into(), ImageBlob::new("image/png", png));
let image = ImageObject {
key: "complete-mask-image".into(),
width: 20,
height: 20,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let mut image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
image.appearance.effects.push(Effect { id: "blur.gaussian".into(), params: serde_json::json!({"radius": 4.0}), visible: true });
let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let white = rect_node(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), Paint::solid(Color::WHITE), Paint::None, 0.0);
let art = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(image)]);
object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
d.insert(Some(d.layers[0].id), 0, object).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let mut r = Renderer::new();
let first = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(first.pixel(70, 70), [255, 0, 0, 255]);
let raster = r.pixel_fx.values().next().unwrap().image.clone();
let second = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(second.pixels, first.pixels);
assert!(Arc::ptr_eq(&raster, &r.pixel_fx.values().next().unwrap().image), "the second frame draws the image mask from its cached effect raster");
}
#[test]
fn missing_image_mask_with_blur_stays_incomplete_from_cached_raster() {
use vectorcraft_doc::{Effect, ImageObject, NodeKind, OpacityMask};
let mut d = Document::new(100.0, 100.0);
let image = ImageObject {
key: "missing-blurred-mask-image".into(),
width: 20,
height: 20,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let mut image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
image.appearance.effects.push(Effect { id: "blur.gaussian".into(), params: serde_json::json!({"radius": 4.0}), visible: true });
let white = rect_node(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), Paint::solid(Color::WHITE), Paint::None, 0.0);
let art = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(image)]);
let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
d.insert(Some(d.layers[0].id), 0, object).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let mut r = Renderer::new();
let first = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(first.pixel(70, 70), [255, 255, 255, 255]);
let raster = r.pixel_fx.values().next().unwrap().image.clone();
let second = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(second.pixel(70, 70), [255, 255, 255, 255]);
assert!(Arc::ptr_eq(&raster, &r.pixel_fx.values().next().unwrap().image), "the incomplete raster is reused");
}
#[test]
fn missing_image_mask_with_rasterize_and_shadow_keeps_incomplete_content_raster() {
use vectorcraft_doc::{Effect, ImageObject, NodeKind, OpacityMask};
let mut d = Document::new(100.0, 100.0);
let image = ImageObject {
key: "missing-rasterized-mask-image".into(),
width: 20,
height: 20,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let mut image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
image.appearance.effects = [
("rasterize", serde_json::json!({"background": "white"})),
("stylize.dropShadow", serde_json::json!({"mode": "normal", "opacity": 100, "x": 2, "y": 2, "blur": 1, "color": "#0000ff"})),
("blur.gaussian", serde_json::json!({"radius": 4.0})),
]
.into_iter()
.map(|(id, params)| Effect { id: id.into(), params, visible: true })
.collect();
let white = rect_node(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), Paint::solid(Color::WHITE), Paint::None, 0.0);
let art = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(image)]);
let mut object = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
object.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
d.insert(Some(d.layers[0].id), 0, object).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let mut r = Renderer::new();
let mut first_raster = None;
for frame in 0..2 {
let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(img.pixel(70, 70), [255, 255, 255, 255], "frame {frame}: the incomplete mask leaves out the object");
let raster = r.pixel_fx.values().next().unwrap();
assert!(raster.image_left_out, "frame {frame}: the content raster records the missing image");
if let Some(first) = &first_raster {
assert!(Arc::ptr_eq(first, &raster.image), "the second frame reuses the incomplete content raster");
} else {
first_raster = Some(raster.image.clone());
}
}
}
#[test]
fn undecodable_image_in_nested_opacity_mask_leaves_out_outer_object() {
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind, OpacityMask};
let mut d = Document::new(100.0, 100.0);
d.images.insert("broken-nested-mask-image".into(), ImageBlob::new("image/png", b"not a nested PNG".to_vec()));
let mut outer = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let mut inner = rect_node(&mut d, Rect::new(20.0, 20.0, 80.0, 80.0), Paint::solid(Color::WHITE), Paint::None, 0.0);
let image = ImageObject {
key: "broken-nested-mask-image".into(),
width: 20,
height: 20,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
inner.extras_mut().mask = Some(Box::new(OpacityMask::new(image, false)));
let art = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
outer.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
d.insert(Some(d.layers[0].id), 0, outer).unwrap();
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts);
assert_eq!(img.pixel(70, 70), [255, 255, 255, 255], "the incomplete inner mask invalidates the outer mask");
}
/// #3580: each opacity mask is rendered over its object's pixels, not over the whole frame. 300
/// masked 4 × 4 pt squares on a 1000 × 1000 page draw offscreen in proportion to their bounds, and
/// still draw where their masks show them.
+35 -1
View File
@@ -118,7 +118,9 @@ fn arabic_joining_forms_are_not_alternates() {
assert_eq!(alternates(&t), 0);
}
/// #394: the lam-alef ligature is required (`rlig`), so it isn't highlighted either.
/// #394: the lam-alef ligature is required (`rlig`), so it isn't highlighted either. With an
/// older font that files it under `liga` (as the legacy Arial of Microsoft's core fonts does) it
/// is still required: [`lam_alef_in_liga_is_not_an_alternate`] checks that without an OS font.
#[test]
fn lam_alef_is_not_an_alternate() {
// Looking up an installed font loads it, which changes the fonts.
@@ -129,6 +131,38 @@ fn lam_alef_is_not_an_alternate() {
}
}
/// #394: a font whose lam-alef ligature is in `liga` (older Arabic fonts) or `rlig` gets no
/// highlight on it: the ligature is required by the characters, not chosen by an optional
/// feature. Built in code, so it runs whatever fonts the machine has.
#[test]
fn lam_alef_in_liga_is_not_an_alternate() {
use vectorcraft_text::test_fonts::{lam_alef_family, lam_alef_font};
let _adding = crate::tests_fontchange::adding_fonts();
let db = vectorcraft_text::FontDb::global();
for feature in [b"liga", b"rlig"] {
db.add_font(lam_alef_font(feature).unwrap());
let style = vectorcraft_doc::text::CharStyle { size: 36.0, font_family: lam_alef_family(feature).into(), ..Default::default() };
for s in ["\u{0644}\u{0627}", "\u{0644}\u{0623}", "\u{0628}\u{0644}\u{0627}", "\u{0644}\u{064E}\u{0627}"] {
let t = text(s, style.clone());
// The font's ligature glyph stands for the pair.
assert!(glyphs(&t).iter().any(|g| g.1 > 2), "{}: {s} is shaped to one ligature glyph", lam_alef_family(feature));
assert_eq!(alternates(&t), 0, "{}: {s}", lam_alef_family(feature));
}
}
}
/// Only a lam followed by an alef (marks between or after allowed) is the required lam-alef.
#[test]
fn only_lam_alef_clusters_are_the_required_ligature() {
for s in ["\u{0644}\u{0627}", "\u{0644}\u{0622}", "\u{0644}\u{0623}", "\u{0644}\u{0625}", "\u{0644}\u{064E}\u{0627}", "\u{0644}\u{0627}\u{064B}"]
{
assert!(crate::text_geom::is_lam_alef(s), "{s:?}");
}
for s in ["", "\u{0644}", "\u{0627}\u{0644}", "\u{0644}\u{0628}", "\u{0628}\u{0644}\u{0627}", "\u{0644}\u{0627}\u{0627}", "fi", "\u{064E}"] {
assert!(!crate::text_geom::is_lam_alef(s), "{s:?}");
}
}
/// #394: an optional feature the characters turn on (a stylistic set, swash, stylistic or
/// discretionary alternate…) is highlighted on the glyphs it changes, and only on those.
#[test]
+94
View File
@@ -184,3 +184,97 @@ fn page_knockout_looks_the_same_when_another_object_blends() {
assert!(close(a, b), "the group's middle over {below:?}: {a:?} alone, {b:?} with the Multiply square");
}
}
#[test]
fn opaque_knockout_fills_keep_pixels_without_per_element_backdrop_rasters() {
// Fractional curved edges and holes exercise coverage, not just opaque interiors. A disabled
// mask is visually neutral and keeps the general knockout path as an oracle, without adding
// another compositing layer or rounding step to each fill.
for precise in [false, true] {
for (anti_alias, supersample) in [(AntiAlias::Art, false), (AntiAlias::Art, true), (AntiAlias::None, false)] {
for copy_backdrop in [false, true] {
let make = |reference: bool| {
let mut d = Document::new(80.0, 60.0);
let mut members = Vec::new();
for i in 0..12 {
let outer = shapes::ellipse(Rect::new(2.3 + f64::from(i), 3.7, 65.4, 53.2));
let inner = shapes::ellipse(Rect::new(20.2, 20.8, 40.6, 38.1));
let child = Node::path(d.alloc_id(), inner, Appearance::default());
let first = Node::path(d.alloc_id(), outer, Appearance::default());
let mut n = if i % 2 == 0 {
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(first), Arc::new(child)], rule: FillRule::EvenOdd })
} else {
first
};
n.appearance = Appearance::basic(Paint::solid(Color::rgb(i as f32 / 12.0, 0.3, 0.7)), Paint::None, 0.0).into();
if reference {
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 60.0)), Appearance::default());
let mut mask = vectorcraft_doc::OpacityMask::new(art, false);
mask.disabled = true;
n.extras_mut().mask = Some(Box::new(mask));
}
members.push(Arc::new(n));
}
if copy_backdrop {
let mut blend = half(&mut d, 70.0, (0.5, 0.5, 0.5));
blend.blend = Blend::Multiply;
members.push(Arc::new(blend));
}
let mut g = Node::group(d.alloc_id(), members);
g.knockout = Knockout::On;
g.opacity = 0.5;
d.insert(Some(d.layers[0].id), 0, g).unwrap();
d
};
let opts = RenderOptions { background: Some([190, 210, 230, 255]), precise, anti_alias, supersample, ..Default::default() };
let draw = |reference| {
crate::group::PIXELS_DRAWN.with(|n| n.set(0));
let mut r = Renderer::new();
r.threads = 0;
let img = r.render(&make(reference), 80, 60, Affine::IDENTITY, &opts);
let pixels = crate::group::PIXELS_DRAWN.with(|n| n.get());
(img, pixels, r.stats.drawn)
};
let (fast, fast_pixels, fast_draws) = draw(false);
let (reference, reference_pixels, reference_draws) = draw(true);
assert!(fast.pixels == reference.pixels, "precise={precise}, aa={anti_alias:?}, supersample={supersample}, backdrop={copy_backdrop}");
if anti_alias == AntiAlias::None || supersample {
assert!(fast_draws < reference_draws, "opaque elements should draw once");
if copy_backdrop {
assert!(fast_pixels < reference_pixels, "opaque elements should not rasterize a backdrop per element");
}
} else {
assert_eq!(fast_draws, reference_draws, "analytical AA must keep its rounding");
assert_eq!(fast_pixels, reference_pixels);
}
}
}
}
}
#[test]
fn translucent_knockout_objects_and_fills_keep_their_compositing() {
for fill_opacity in [false, true] {
let d = doc(Knockout::On, |_, g| {
if fill_opacity {
for n in g.children_mut().unwrap() {
let n = Arc::make_mut(n);
n.opacity = 1.0;
for item in &mut n.appearance.items {
if let vectorcraft_doc::AppearanceItem::Fill(fill) = item {
fill.opacity = 0.5;
}
}
}
}
});
let opts = RenderOptions { anti_alias: AntiAlias::None, background: Some([255; 4]), ..Default::default() };
let mut renderer = Renderer::new();
let r = renderer.render(&d, 100, 100, Affine::IDENTITY, &opts);
// Object opacity is ignored by its knockout shape; a fill's own opacity is retained.
let want = if fill_opacity { BLUE_OVER_RED } else { BLUE_OVER_WHITE };
assert!(close(r.pixel(50, 50), want), "fill opacity={fill_opacity}: {:?}", r.pixel(50, 50));
let nodes = d.layers.iter().map(|n| n.count()).sum::<usize>();
assert!(renderer.stats.drawn > nodes, "translucent elements keep the separate knockout passes");
}
}
+14 -2
View File
@@ -48,7 +48,8 @@ impl TextGeom {
/// The boxes of the glyphs of `t` (the text this geometry is of) that optional OpenType features
/// chose (Preferences › Highlight Alternate Glyphs): candidates the text's required shaping
/// alone doesn't give ([`required_shaping`]). Arabic letters joining, Indic conjuncts and the
/// lam-alef ligature are what the script needs, not alternates. Measured once.
/// lam-alef ligature are what the script needs, not alternates (the lam-alef ligature also when
/// a font files it under `liga`: [`is_lam_alef`]). Measured once.
pub(crate) fn alternate_glyphs(&self, t: &TextObject) -> &BezPath {
self.alternate_glyphs.get_or_init(|| {
let mut out = BezPath::new();
@@ -84,6 +85,17 @@ pub(crate) fn is_opentype_alternate(nominal_gid: u32, shaped_gid: u32, cluster_c
shaped_gid != 0 && (cluster_chars > 1 || shaped_gid != nominal_gid)
}
/// Whether `cluster` is a lam followed by an alef (plain, with madda, or with hamza above or below),
/// with any Arabic marks between or after them: the lam-alef ligature, which the Unicode
/// Standard's Arabic chapter treats as obligatory, not a stylistic choice. Fonts made before
/// `rlig` was common put it in `liga`, which [`required_shaping`] turns off, so it is required
/// by its characters whatever feature the font files it under.
pub(crate) fn is_lam_alef(cluster: &str) -> bool {
let is_mark = |c: &char| matches!(c, '\u{0610}'..='\u{061A}' | '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{06D6}'..='\u{06DC}' | '\u{06DF}'..='\u{06E4}' | '\u{06E7}' | '\u{06E8}' | '\u{06EA}'..='\u{06ED}');
let mut letters = cluster.chars().filter(|c| !is_mark(c));
matches!((letters.next(), letters.next(), letters.next()), (Some('\u{0644}'), Some('\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}'), None))
}
/// A glyph [`is_opentype_alternate`] marks, in its cluster of the text (`byte`, `len`), with its
/// box.
#[derive(Debug)]
@@ -181,7 +193,7 @@ pub(crate) fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeo
let cluster_chars = cluster.chars().count();
let Some(first) = cluster.chars().next() else { continue };
let nominal = db.face_by_id(g.font_id).map(|f| f.glyph_for(first)).unwrap_or(0);
if is_opentype_alternate(nominal, g.gid, cluster_chars) {
if is_opentype_alternate(nominal, g.gid, cluster_chars) && !is_lam_alef(cluster) {
alternate_candidates.push(AlternateCandidate { byte: g.byte, len: g.len, font_id: g.font_id, gid: g.gid, cell });
}
}
+7 -1
View File
@@ -111,7 +111,13 @@ mod tests {
fn a_temp_dir_starts_empty_in_a_process_and_stays_for_later_calls() {
let tag = "fresh-temp-dir";
let left = std::env::temp_dir().join(format!("vectorcraft-testkit-{tag}-{}", std::process::id()));
std::fs::create_dir_all(left.join("nested")).unwrap();
// Made private, as `temp_dir` makes it: a directory others can reach is refused, not reused.
#[cfg_attr(not(unix), allow(unused_mut))]
let mut b = std::fs::DirBuilder::new();
b.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
b.create(left.join("nested")).unwrap();
std::fs::write(left.join("left.txt"), b"an earlier process").unwrap();
let dir = super::temp_dir(tag);
assert_eq!(dir, left);
+50
View File
@@ -343,6 +343,56 @@ pub fn half_form_font(half: bool) -> Option<Vec<u8>> {
Some(builder.build())
}
/// The family of [`lam_alef_font`] whose lam-alef ligature is in `feature`.
pub fn lam_alef_family(feature: &[u8; 4]) -> &'static str {
match feature {
b"liga" => "Lamtest Liga",
b"rlig" => "Lamtest Rlig",
_ => "Lamtest Other",
}
}
/// A test-only Arabic cmap over bundled Source Sans 3: lam uses l, alef I, alef with hamza above
/// J and beh b. The `GSUB` table's `arab` script has one ligature lookup, under `feature`, that
/// joins lam + alef into H and lam + alef with hamza above into K. Older fonts put the mandatory
/// lam-alef ligature in `liga` rather than `rlig`; this builds either, without an OS font. `None`
/// when it can't be built.
pub fn lam_alef_font(feature: &[u8; 4]) -> Option<Vec<u8>> {
use write_fonts::tables::cmap::Cmap;
use write_fonts::tables::gsub::{Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList};
use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord};
use write_fonts::types::GlyphId16;
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let charmap = font.charmap();
let mapping = [('\u{0644}', 'l'), ('\u{0627}', 'I'), ('\u{0623}', 'J'), ('\u{0628}', 'b')];
let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32()))));
let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?;
let family = lam_alef_family(feature);
let full = format!("{family} Regular");
let postscript = format!("{}-Regular", family.replace(' ', ""));
let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?;
let mut builder = FontBuilder::new();
builder.add_table(&cmap).ok()?;
builder.add_raw(Tag::new(b"name"), name);
let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?));
let coverage = CoverageFormat1::new(vec![gid('l')?]);
let ligatures = vec![Ligature::new(gid('H')?, vec![gid('I')?]), Ligature::new(gid('K')?, vec![gid('J')?])];
let subst = LigatureSubstFormat1::new(coverage.into(), vec![LigatureSet::new(ligatures)]);
let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(feature), Feature::new(None, vec![0]))]);
let lookups = SubstitutionLookupList::new(vec![SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![subst]))]);
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"arab"), Script::new(Some(LangSys::new(vec![0])), vec![]))]);
builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?;
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
if !builder.contains(tag) {
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
}
}
Some(builder.build())
}
/// The family of [`pair_kerning_font`].
pub const PAIR_KERNING_FAMILY: &str = "Pairtest Sans";
+9
View File
@@ -3,9 +3,12 @@
//! submenu selects them. Like every tool they only emit commands (`addon.<name>.*`).
pub mod anchor_eraser;
pub mod corner_tool;
pub mod extend_path;
pub mod measure_inspect;
pub mod parametric_shape;
pub mod shared_edge;
pub mod slide_anchor;
pub mod smart_pen;
use crate::{Tool, ToolInfo};
@@ -16,6 +19,9 @@ pub const PATH_TOOLS: &[ToolInfo] = &[
ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" },
ToolInfo { id: measure_inspect::ID, label: "Measure & Inspect Tool", shortcut: None, icon: "ruler" },
ToolInfo { id: parametric_shape::ID, label: "Parametric Shape Tool", shortcut: None, icon: "hexagon" },
ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" },
ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" },
ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" },
];
/// Smart Pen's tool, a flyout group of its own.
@@ -37,9 +43,12 @@ pub fn heading(id: &str) -> Option<&'static str> {
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
Some(match id {
anchor_eraser::ID => Box::new(anchor_eraser::AnchorEraserTool::default()),
corner_tool::ID => Box::new(corner_tool::CornerTool::default()),
extend_path::ID => Box::new(extend_path::ExtendPathTool::default()),
measure_inspect::ID => Box::new(measure_inspect::MeasureInspectTool::default()),
parametric_shape::ID => Box::new(parametric_shape::ParametricShapeTool::default()),
shared_edge::ID => Box::new(shared_edge::SharedEdgeTool::default()),
slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()),
smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()),
_ => return None,
})
+387
View File
@@ -0,0 +1,387 @@
//! Corner Tool (Path Precision Tools): editable corners on any path, selected or not, through the
//! app's Live Corners (`addon.pathtools.cornerSet` / `cornerRemove`). Over an anchor that can take
//! a corner, the anchor shows; a click cuts one with the tool's radius and kind, a drag sizes it
//! (Shift: whole values of the ruler's unit). A cut corner shows a marker at the centre of its cut:
//! a click selects the corner and loads its radius and kind into the tool, a drag resizes it (to 0
//! it goes), a double-click removes it. A corner can't grow past what fits. Alt-marquee cuts
//! corners on every anchor inside; a plain marquee selects them, and a click away deselects.
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, LiveCorners, NodeId, NodeKind};
use vectorcraft_geom::corners::Corner;
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{Affine, Point, Rect};
use crate::builder::HIGHLIGHT_RED;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// The tool's id.
pub const ID: &str = "cornerTool";
/// The radius a click cuts by default (pt).
pub const RADIUS: f64 = 10.0;
/// The largest radius asked for (pt).
pub const MAX_RADIUS: f64 = 1e6;
/// The undo step of a drag.
const LABEL: &str = "Corner Radius";
const SET: &str = "addon.pathtools.cornerSet";
const REMOVE: &str = "addon.pathtools.cornerRemove";
/// How far (px) the pointer travels before a press is a drag.
const DRAG_PX: f64 = 3.0;
/// Most markers drawn at once.
const MAX_MARKERS: usize = 2000;
const MARKER_PX: f32 = 7.0;
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
/// A corner the tool can act on.
#[derive(Clone, Debug, PartialEq)]
struct Spot {
id: NodeId,
corner: Corner,
/// Maps the corner's space into the document.
xf: Affine,
/// The radius it is drawn with: 0 for a sharp corner.
drawn: f64,
kind: CornerKind,
}
impl Spot {
fn of(lc: &LiveCorners, id: NodeId, corner: &Corner) -> Self {
Self { id, corner: *corner, xf: lc.xf, drawn: lc.drawn_radius(corner.index), kind: lc.kind(corner.index) }
}
/// Where it shows: a cut corner's marker, the centre of a round cut, or a sharp corner's anchor.
fn at(&self) -> Point {
self.xf * self.corner.on_bisector(self.drawn / self.corner.sin())
}
/// The params naming it.
fn items(&self) -> Value {
json!([{ "id": self.id.0, "anchors": [self.corner.index] }])
}
}
/// Every cut corner of the editable paths.
fn cut_corners(doc: &Document) -> Vec<Spot> {
let editable = doc.editable();
let mut out = vec![];
doc.walk(|n| {
if matches!(n.kind, NodeKind::Path { live: Some(_), guide: false, .. })
&& editable(n.id)
&& let Some(lc) = LiveCorners::of(n)
{
out.extend(lc.corners.iter().filter(|c| lc.drawn_radius(c.index) > 0.0).map(|c| Spot::of(&lc, n.id, c)));
}
});
out
}
/// The sharp corner of an editable path nearest `p` within the point tolerance.
fn sharp_corner_at(cx: &ToolContext, p: Point) -> Option<Spot> {
let (tol, editable) = (cx.point_tol(), cx.doc.editable());
let mut best: Option<(f64, Spot)> = None;
cx.doc.walk(|n| {
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
if !path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol) || !editable(n.id) {
return;
}
let Some(lc) = LiveCorners::of(n) else { return };
for c in lc.corners.iter().filter(|c| lc.drawn_radius(c.index) <= 0.0) {
let s = Spot::of(&lc, n.id, c);
let d = s.at().distance(p);
if d <= tol && best.as_ref().is_none_or(|b| d < b.0) {
best = Some((d, s));
}
}
});
best.map(|(_, s)| s)
}
/// The corners of the editable paths inside `r`, by path: anchor indices of each uncut outline.
fn corners_inside(cx: &ToolContext, r: Rect) -> BTreeMap<NodeId, Vec<usize>> {
let editable = cx.doc.editable();
let mut out = BTreeMap::new();
cx.doc.walk(|n| {
if !matches!(n.kind, NodeKind::Path { guide: false, .. }) || !editable(n.id) {
return;
}
let Some(lc) = LiveCorners::of(n) else { return };
let inside: Vec<usize> = lc.corners.iter().filter(|c| r.contains(lc.xf * c.at)).map(|c| c.index).collect();
if !inside.is_empty() {
out.insert(n.id, inside);
}
});
out
}
/// The largest radius `spot` draws with the corners around it as they are.
fn max_radius(doc: &Document, spot: &Spot) -> f64 {
let Some(lc) = doc.node(spot.id).and_then(LiveCorners::of) else { return 0.0 };
let radii: Vec<f64> = (0..lc.base.anchor_count()).map(|k| lc.drawn_radius(k)).collect();
spot.corner.max_shared_radius(&lc.corners, &radii, |k| k == spot.corner.index)
}
/// `select.anchors` params selecting `corners` of path `id`.
fn select_params(cx: &ToolContext, id: NodeId, corners: &[usize], mode: &str) -> Option<Value> {
let lc = cx.doc.node(id).and_then(LiveCorners::of)?;
let anchors: Vec<_> = lc.anchors_of(&corners.iter().copied().collect()).into_iter().collect();
Some(json!({ "id": id.0, "anchors": anchors, "mode": mode }))
}
/// A document revision and the cut corners it has.
type Marks = ((u64, u64), Arc<Vec<Spot>>);
#[derive(Clone, Debug, Default)]
enum State {
#[default]
Idle,
/// Pressed on a corner: a drag sizes it.
Corner {
spot: Box<Spot>,
start: Point,
/// The largest radius that fits.
max: f64,
/// The drag has left the click.
began: bool,
/// The radius the drag asks for.
radius: f64,
/// Where the pointer is.
at: Point,
},
/// `cut`: an Alt-marquee, which cuts corners; else it selects them.
Marquee { start: Point, cur: Point, cut: bool, toggle: bool },
}
pub struct CornerTool {
radius: f64,
kind: CornerKind,
state: State,
hover: Option<Spot>,
/// The cut corners of the document as it was at a revision, for hovering and the markers.
cache: Cell<Option<Marks>>,
}
impl Default for CornerTool {
fn default() -> Self {
Self { radius: RADIUS, kind: CornerKind::Round, state: State::Idle, hover: None, cache: Cell::new(None) }
}
}
impl CornerTool {
fn markers(&self, cx: &ToolContext) -> Arc<Vec<Spot>> {
let kept = self.cache.take().filter(|(rev, _)| *rev == cx.revision);
let list = kept.map_or_else(|| Arc::new(cut_corners(cx.doc)), |(_, list)| list);
self.cache.set(Some((cx.revision, list.clone())));
list
}
/// The corner at `p`: a cut corner's marker, else a sharp corner's anchor.
fn spot_at(&self, cx: &ToolContext, p: Point) -> Option<Spot> {
let (marks, tol) = (self.markers(cx), cx.point_tol());
let dist = |s: &&Spot| s.at().distance(p);
let mark = marks.iter().filter(|s| dist(s) <= tol).min_by(|a, b| dist(a).total_cmp(&dist(b)));
mark.cloned().or_else(|| sharp_corner_at(cx, p))
}
/// The command a drag of `spot` to `radius` stands for.
fn sized(&self, spot: &Spot, radius: f64) -> Action {
if radius > 0.0 {
let kind = if spot.drawn > 0.0 { spot.kind } else { self.kind };
Action::Preview(SET.into(), json!({ "items": spot.items(), "radius": radius, "kind": kind }))
} else {
Action::Preview(REMOVE.into(), json!({ "items": spot.items() }))
}
}
fn drag_corner(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
let State::Corner { spot, start, max, began, radius, at } = &mut self.state else { return vec![] };
*at = p;
let mut out = vec![];
if !*began {
if p.distance(*start) < cx.tol(DRAG_PX) {
return out;
}
*began = true;
out.push(Action::Begin(LABEL.into()));
}
let inv = spot.xf.inverse();
let change = spot.corner.radius_change(inv * p - inv * *start);
// From a sharp corner a drag either way sizes it; a cut one grows inward and shrinks back.
let asked = if spot.drawn > 0.0 { spot.drawn + change } else { change.abs() };
let asked = if mods.shift { cx.unit.to_pt(cx.unit.from_pt(asked).round()) } else { asked };
*radius = asked.min(*max).max(0.0);
let (spot, r) = (spot.clone(), *radius);
out.push(self.sized(&spot, r));
out
}
/// A press on a corner let go without a drag.
fn click_corner(&self, cx: &ToolContext, spot: &Spot, mods: Mods) -> Vec<Action> {
if spot.drawn <= 0.0 {
return vec![Action::Exec(SET.into(), json!({ "items": spot.items(), "radius": self.radius, "kind": self.kind }))];
}
let mode = if mods.shift { "toggle" } else { "set" };
select_params(cx, spot.id, &[spot.corner.index], mode).map_or_else(Vec::new, |p| vec![Action::Exec("select.anchors".into(), p)])
}
fn finish_marquee(&self, cx: &ToolContext, r: Rect, cut: bool, toggle: bool) -> Vec<Action> {
let inside = corners_inside(cx, r);
if cut {
if inside.is_empty() {
return vec![];
}
let items: Vec<Value> = inside.iter().map(|(id, corners)| json!({ "id": id.0, "anchors": corners })).collect();
return vec![Action::Exec(SET.into(), json!({ "items": items, "radius": self.radius, "kind": self.kind }))];
}
if inside.is_empty() && !toggle {
return vec![Action::Exec("select.none".into(), json!({}))];
}
let modes = std::iter::once(if toggle { "toggle" } else { "set" }).chain(std::iter::repeat(if toggle { "toggle" } else { "add" }));
inside
.iter()
.zip(modes)
.filter_map(|((id, corners), mode)| Some(Action::Exec("select.anchors".into(), select_params(cx, *id, corners, mode)?)))
.collect()
}
}
impl Tool for CornerTool {
fn id(&self) -> &'static str {
ID
}
fn busy(&self) -> bool {
!matches!(self.state, State::Idle)
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
match ev.kind {
PointerKind::Move => {
self.hover = self.spot_at(cx, p);
vec![]
}
PointerKind::Down => {
self.hover = None;
let spot = if ev.mods.alt { None } else { self.spot_at(cx, p) };
self.state = match spot {
Some(spot) => {
// A cut corner's values are the tool's from now on, as the panel shows.
if spot.drawn > 0.0 {
(self.radius, self.kind) = (spot.drawn, spot.kind);
}
let max = max_radius(cx.doc, &spot);
State::Corner { radius: spot.drawn, spot: Box::new(spot), start: p, max, began: false, at: p }
}
None => State::Marquee { start: p, cur: p, cut: ev.mods.alt, toggle: ev.mods.shift },
};
vec![]
}
PointerKind::Drag => {
if let State::Marquee { cur, .. } = &mut self.state {
*cur = p;
return vec![];
}
self.drag_corner(cx, p, ev.mods)
}
PointerKind::Up => match std::mem::take(&mut self.state) {
State::Idle => vec![],
State::Marquee { start, cut, toggle, .. } => self.finish_marquee(cx, Rect::from_points(start, p), cut, toggle),
state @ State::Corner { began: true, .. } => {
self.state = state;
let mut out = self.drag_corner(cx, p, ev.mods);
if let State::Corner { spot, radius, .. } = std::mem::take(&mut self.state) {
// Back where it started: nothing to keep.
if spot.drawn <= 0.0 && radius <= 0.0 {
return vec![Action::Cancel];
}
}
out.push(Action::Commit);
out
}
State::Corner { spot, .. } => self.click_corner(cx, &spot, ev.mods),
},
PointerKind::DoubleClick => {
self.state = State::Idle;
match self.spot_at(cx, p).filter(|s| s.drawn > 0.0) {
Some(s) => vec![Action::Exec(REMOVE.into(), json!({ "items": s.items() }))],
None => vec![],
}
}
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape {
return vec![];
}
match std::mem::take(&mut self.state) {
State::Corner { began: true, .. } => vec![Action::Cancel],
_ => vec![],
}
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
self.busy() && key == ToolKey::Escape
}
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let ring = |p, color, filled| Overlay::CurvePoint { p, color, filled, size: MARKER_PX };
match &self.state {
State::Marquee { start, cur, .. } => return vec![Overlay::Marquee(Rect::from_points(*start, *cur))],
State::Corner { began: true, radius, max, at, .. } => {
let mut out = vec![];
if cx.measurement_labels {
out.push(Overlay::Measure { p: *at, text: format!("Radius: {}", cx.len(*radius)) });
}
// At the limit of what fits.
if *max > 0.0 && *radius >= *max {
out.push(ring(*at, HIGHLIGHT_RED, false));
}
return out;
}
_ => {}
}
let mut out: Vec<Overlay> = self.markers(cx).iter().take(MAX_MARKERS).map(|s| ring(s.at(), BLUE, false)).collect();
match &self.hover {
Some(s) if s.drawn > 0.0 => out.push(ring(s.at(), BLUE, true)),
Some(s) => out.push(Overlay::Anchor { p: s.at(), color: BLUE, filled: true, size: MARKER_PX }),
None => {}
}
out
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::CornerTool
}
fn options(&self) -> Value {
json!({ "radius": self.radius, "kind": self.kind })
}
fn set_option(&mut self, key: &str, v: &Value) {
match key {
"radius" => {
if let Some(r) = v.as_f64().filter(|r| (0.0..=MAX_RADIUS).contains(r)) {
self.radius = r;
}
}
"kind" => {
if let Ok(k) = serde_json::from_value(v.clone()) {
self.kind = k;
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,161 @@
use vectorcraft_doc::corners::set_corners;
use vectorcraft_doc::{Appearance, Node, Selection};
use vectorcraft_geom::{PathData, SubPath};
use super::*;
use crate::testutil::*;
/// A square (100, 100)–(300, 300), plain: anchors from the top left, clockwise.
fn doc_with_square() -> (Document, NodeId) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let pts = [(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)].map(|(x, y)| Point::new(x, y));
d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, true)), Appearance::default_art())).unwrap();
(d, id)
}
/// [`doc_with_square`] with a chamfer of radius 20 on corner 1, whose marker is at (280, 120).
fn doc_with_corner() -> (Document, NodeId) {
let (mut d, id) = doc_with_square();
let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { panic!() };
set_corners(path, live, &[1].into(), Some(20.0), Some(CornerKind::Chamfer));
(d, id)
}
fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent {
PointerEvent::new(kind, x, y)
}
fn with(mut e: PointerEvent, f: impl Fn(&mut Mods)) -> PointerEvent {
f(&mut e.mods);
e
}
fn radius_of(a: Option<&Action>) -> f64 {
let Some(Action::Preview(_, p)) = a else { panic!("{a:?}") };
p["radius"].as_f64().unwrap()
}
#[test]
fn hover_shows_the_anchor_and_a_click_cuts_with_the_tools_values() {
let (d, id) = doc_with_square();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = CornerTool::default();
t.set_option("radius", &json!(15));
t.set_option("kind", &json!("invertedRound"));
assert!(t.pointer(&cx, &ev(PointerKind::Move, 301.0, 101.0)).is_empty());
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Anchor { filled: true, .. }]), "{:?}", t.overlays(&cx));
t.pointer(&cx, &ev(PointerKind::Move, 200.0, 200.0));
assert!(t.overlays(&cx).is_empty(), "nothing there");
assert!(t.pointer(&cx, &ev(PointerKind::Down, 300.0, 100.0)).is_empty());
assert!(t.busy());
let up = t.pointer(&cx, &ev(PointerKind::Up, 300.0, 100.0));
assert_eq!(up, vec![Action::Exec(SET.into(), json!({"items": [{"id": id.0, "anchors": [1]}], "radius": 15.0, "kind": "invertedRound"}))]);
assert!(!t.busy());
}
#[test]
fn a_drag_from_an_anchor_sizes_the_corner_and_stops_at_what_fits() {
let (d, id) = doc_with_square();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = CornerTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 100.0));
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 280.0, 120.0));
assert_eq!(drag.first(), Some(&Action::Begin(LABEL.into())));
assert!((radius_of(drag.get(1)) - 20.0).abs() < 1e-9, "{drag:?}");
let Some(Action::Preview(cmd, params)) = drag.get(1) else { panic!() };
assert_eq!((cmd.as_str(), params["items"][0]["id"].clone(), params["kind"].clone()), (SET, json!(id.0), json!("round")));
// Shift: whole values.
let shifted = t.pointer(&cx, &with(ev(PointerKind::Drag, 276.6, 123.4), |m| m.shift = true));
assert_eq!(radius_of(shifted.first()), 23.0);
// Past what fits: as far as the sharp corners next to it, marked at the limit.
let far = t.pointer(&cx, &ev(PointerKind::Drag, 0.0, 400.0));
assert!((radius_of(far.first()) - 200.0).abs() < 1e-9, "{far:?}");
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { color, .. } if *color == HIGHLIGHT_RED)));
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.contains("Radius: 200"))));
let up = t.pointer(&cx, &ev(PointerKind::Up, 280.0, 120.0));
assert!(matches!(up.as_slice(), [Action::Preview(..), Action::Commit]), "{up:?}");
// Back on the anchor: nothing to keep. Escape cancels.
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Drag, 280.0, 120.0));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 100.0)), vec![Action::Cancel]);
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Drag, 280.0, 120.0));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
assert!(!t.busy());
}
#[test]
fn a_cut_corners_marker_selects_loads_resizes_and_removes() {
let (d, id) = doc_with_corner();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = CornerTool::default();
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::CurvePoint { filled: false, .. }]), "the marker shows");
t.pointer(&cx, &ev(PointerKind::Move, 281.0, 119.0));
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, .. })), "hovered");
// A click selects the corner's anchors and loads its values.
t.pointer(&cx, &ev(PointerKind::Down, 280.0, 120.0));
let up = t.pointer(&cx, &ev(PointerKind::Up, 280.0, 120.0));
let Some(Action::Exec(cmd, params)) = up.first() else { panic!("{up:?}") };
assert_eq!((cmd.as_str(), params["id"].clone(), params["mode"].clone()), ("select.anchors", json!(id.0), json!("set")));
assert_eq!(params["anchors"], json!([[0, 1], [0, 2]]));
assert_eq!(t.options(), json!({"radius": 20.0, "kind": "chamfer"}));
// A drag resizes it, its kind kept; to nothing it goes.
t.pointer(&cx, &ev(PointerKind::Down, 280.0, 120.0));
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 270.0, 130.0));
assert!((radius_of(drag.get(1)) - 30.0).abs() < 1e-9, "{drag:?}");
assert!(matches!(drag.get(1), Some(Action::Preview(_, p)) if p["kind"] == json!("chamfer")));
let gone = t.pointer(&cx, &ev(PointerKind::Up, 310.0, 90.0));
assert!(matches!(gone.as_slice(), [Action::Preview(c, _), Action::Commit] if c == REMOVE), "{gone:?}");
// A double-click removes it.
let dbl = t.pointer(&cx, &ev(PointerKind::DoubleClick, 280.0, 120.0));
assert_eq!(dbl, vec![Action::Exec(REMOVE.into(), json!({"items": [{"id": id.0, "anchors": [1]}]}))]);
assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 300.0, 300.0)).is_empty(), "a sharp corner has nothing to remove");
}
#[test]
fn an_alt_marquee_cuts_every_corner_inside_and_a_plain_one_selects() {
let (d, id) = doc_with_corner();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = CornerTool::default();
// Alt over an anchor starts a marquee too; the chamfered corner counts, the far side doesn't.
let alt = |e| with(e, |m| m.alt = true);
t.pointer(&cx, &alt(ev(PointerKind::Down, 50.0, 50.0)));
t.pointer(&cx, &alt(ev(PointerKind::Drag, 350.0, 200.0)));
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Marquee(_)]));
let up = t.pointer(&cx, &alt(ev(PointerKind::Up, 350.0, 200.0)));
assert_eq!(up, vec![Action::Exec(SET.into(), json!({"items": [{"id": id.0, "anchors": [0, 1]}], "radius": RADIUS, "kind": "round"}))]);
t.pointer(&cx, &alt(ev(PointerKind::Down, 400.0, 400.0)));
assert!(t.pointer(&cx, &alt(ev(PointerKind::Up, 450.0, 450.0))).is_empty(), "nothing inside");
// Without Alt the corners inside are selected; a click away deselects.
t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0));
let up = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 200.0));
let Some(Action::Exec(cmd, params)) = up.first() else { panic!("{up:?}") };
assert_eq!((cmd.as_str(), params["anchors"].clone(), params["mode"].clone()), ("select.anchors", json!([[0, 0]]), json!("set")));
t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 400.0, 400.0)), vec![Action::Exec("select.none".into(), json!({}))]);
}
#[test]
fn locked_paths_are_left_alone_and_options_are_checked() {
let (mut d, id) = doc_with_corner();
d.node_mut(id).unwrap().locked = true;
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = CornerTool::default();
assert!(t.overlays(&cx).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 100.0, 100.0));
assert!(t.overlays(&cx).is_empty());
for bad in [json!(-1), json!(1e308), json!("x")] {
t.set_option("radius", &bad);
}
t.set_option("kind", &json!("spiky"));
assert_eq!(t.options(), json!({"radius": RADIUS, "kind": "round"}));
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::CornerTool);
}
+349
View File
@@ -0,0 +1,349 @@
//! Shared Edge Merge Tool (Path Precision Tools): where two paths, selected or not, touch at two
//! coincident anchors, hovering with the round brush shows the two stretches between them (dashed)
//! and the edge merging them (solid, green when they are merged already), and a click replaces both
//! with that edge, half way between them (`addon.pathtools.mergeEdge`, one undo step). Shift follows
//! the upper path, Alt the lower one. Where the anchors aren't there yet, a click makes one end:
//! near anchors meet half way, and an anchor one path lacks is added to match. Shift+Alt asks for
//! an end inside a stretch that could merge.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{BezPath, Point};
use vectorcraft_pathops::addons::pathtools::{Follow, MergePlan, MergePreview, ends_at, merge_preview, stretches_at};
use crate::builder::HIGHLIGHT_RED;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
pub use vectorcraft_pathops::addons::pathtools::{COINCIDENCE, MAX_COINCIDENCE};
/// The tool's id.
pub const ID: &str = "sharedEdge";
/// The brush's diameter by default and its range (pt).
pub const DIAMETER: f64 = 20.0;
pub const DIAMETER_RANGE: (f64, f64) = (0.25, 200.0);
/// Most paths under the brush compared with one another.
const MAX_PATHS: usize = 6;
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
const GREEN: [u8; 3] = [0x2e, 0xb8, 0x6a];
const GREY: [u8; 3] = [0x80, 0x80, 0x80];
const EDGE_PX: f32 = 2.0;
const ANCHOR_PX: f32 = 7.0;
/// What the brush is over.
#[derive(Clone, Debug, PartialEq)]
struct Target {
/// The upper path.
a: NodeId,
/// The lower path.
b: NodeId,
at: Point,
follow: Follow,
/// Shift+Alt: an end, even where the stretch could merge.
ends: bool,
preview: MergePreview,
/// The document it was found in.
revision: (u64, u64),
}
pub struct SharedEdgeTool {
diameter: f64,
tolerance: f64,
together: bool,
at: Option<Point>,
target: Option<Target>,
pressed: bool,
}
impl Default for SharedEdgeTool {
fn default() -> Self {
Self { diameter: DIAMETER, tolerance: COINCIDENCE, together: false, at: None, target: None, pressed: false }
}
}
/// The editable paths the brush touches, nearest first: (paint order, id).
fn paths_under(cx: &ToolContext, at: Point, radius: f64) -> Vec<(usize, NodeId)> {
let editable = cx.doc.editable();
let mut order = 0;
let mut out: Vec<(f64, usize, NodeId)> = vec![];
cx.doc.walk(|n| {
order += 1;
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
if path.control_bounds().is_none_or(|r| !r.inflate(radius, radius).contains(at)) {
return;
}
let d = path.nearest(at).map_or(f64::INFINITY, |(.., q, _)| q.distance(at));
if d <= radius && editable(n.id) {
out.push((d, order, n.id));
}
});
out.sort_by(|x, y| x.0.total_cmp(&y.0));
out.truncate(MAX_PATHS);
out.into_iter().map(|(_, order, id)| (order, id)).collect()
}
impl SharedEdgeTool {
/// What a click at `at` with `mods` would do, on the nearest paths that it can.
fn look(&self, cx: &ToolContext, at: Point, mods: Mods) -> Option<Target> {
let radius = self.diameter / 2.0;
let path = |id: NodeId| cx.doc.node(id).and_then(|n| n.path_data());
let under = paths_under(cx, at, radius);
let mut pairs: Vec<(NodeId, NodeId)> = vec![];
for (i, x) in under.iter().enumerate() {
pairs.extend(under.iter().skip(i + 1).map(|y| if x.0 > y.0 { (x.1, y.1) } else { (y.1, x.1) }));
}
let find = |f: &dyn Fn(NodeId, NodeId) -> Option<MergePlan>| pairs.iter().find_map(|&(a, b)| Some((a, b, f(a, b)?)));
let ends = mods.shift && mods.alt;
let edge = if ends { None } else { find(&|a, b| stretches_at(path(a)?, path(b)?, at, radius, self.tolerance)) };
let (a, b, plan) = edge.or_else(|| find(&|a, b| ends_at(path(a)?, path(b)?, at, radius)))?;
let follow = match (mods.shift, mods.alt) {
(true, false) => Follow::First,
(false, true) => Follow::Second,
_ => Follow::Average,
};
let preview = merge_preview(path(a)?, path(b)?, &plan, follow)?;
Some(Target { a, b, at, follow, ends, preview, revision: cx.revision })
}
fn params(&self, t: &Target) -> Value {
json!({
"a": t.a.0,
"b": t.b.0,
"at": [t.at.x, t.at.y],
"diameter": self.diameter,
"tolerance": self.tolerance,
"follow": t.follow.id(),
"ends": t.ends,
})
}
}
fn outline(chain: &[kurbo::CubicBez]) -> BezPath {
let mut path = BezPath::new();
if let Some(c) = chain.first() {
path.move_to(c.p0);
}
for c in chain {
path.curve_to(c.p1, c.p2, c.p3);
}
path
}
impl Tool for SharedEdgeTool {
fn id(&self) -> &'static str {
ID
}
fn busy(&self) -> bool {
self.pressed
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.at = Some(ev.pos);
self.target = self.look(cx, ev.pos, ev.mods);
match ev.kind {
PointerKind::Down => self.pressed = true,
PointerKind::Up if std::mem::take(&mut self.pressed) => {
let target = self.target.take();
let todo = target.filter(|t| !matches!(t.preview, MergePreview::Edge { done: true, .. }));
return todo.map_or_else(Vec::new, |t| vec![Action::Exec("addon.pathtools.mergeEdge".into(), self.params(&t))]);
}
_ => {}
}
vec![]
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape {
self.pressed = false;
}
vec![]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
self.pressed && key == ToolKey::Escape
}
fn hover_ended(&mut self, _cx: &ToolContext) {
self.at = None;
self.target = None;
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some(at) = self.at else { return vec![] };
let r = self.diameter / 2.0;
let ring = kurbo::Shape::to_path(&kurbo::Circle::new(at, r), 0.1 * r);
let mut out = vec![Overlay::Path { path: ring, color: GREY, width: 1.0, dashed: false }];
let curve = |chain: &[kurbo::CubicBez], color, dashed| Overlay::Path { path: outline(chain), color, width: EDGE_PX, dashed };
let anchor = |p, color, filled| Overlay::Anchor { p, color, filled, size: ANCHOR_PX };
match self.target.as_ref().filter(|t| t.revision == cx.revision).map(|t| &t.preview) {
Some(MergePreview::Edge { merged, done: true, .. }) => out.push(curve(merged, GREEN, false)),
Some(MergePreview::Edge { a, b, merged, .. }) => {
out.extend([curve(a, BLUE, true), curve(b, BLUE, true), curve(merged, HIGHLIGHT_RED, false)])
}
Some(MergePreview::Ends { a, b, to }) => out.extend([anchor(*a, BLUE, false), anchor(*b, BLUE, false), anchor(*to, HIGHLIGHT_RED, true)]),
None => {}
}
out
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::SharedEdge
}
fn options(&self) -> Value {
json!({ "diameter": self.diameter, "tolerance": self.tolerance, "together": self.together })
}
fn set_option(&mut self, key: &str, v: &Value) {
match key {
"diameter" => {
if let Some(d) = v.as_f64().filter(|d| (DIAMETER_RANGE.0..=DIAMETER_RANGE.1).contains(d)) {
self.diameter = d;
}
}
"tolerance" => {
if let Some(t) = v.as_f64().filter(|t| (0.0..=MAX_COINCIDENCE).contains(t)) {
self.tolerance = t;
}
}
"together" => {
if let Some(on) = v.as_bool() {
self.together = on;
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::*;
use vectorcraft_doc::{Appearance, Document, Node, Selection};
use vectorcraft_geom::{PathData, SubPath};
/// A lower and an upper square sharing the edge x = 100 from y = 0 to y = 100; `gap` pushes the
/// upper one right. → (the document, the lower one, the upper one).
fn doc_with_squares(gap: f64) -> (Document, NodeId, NodeId) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let (lower, upper) = (d.alloc_id(), d.alloc_id());
let square = |x: f64| [(x, 0.0), (x + 100.0, 0.0), (x + 100.0, 100.0), (x, 100.0)].map(|(x, y)| Point::new(x, y));
for (i, (id, x)) in [(lower, 0.0), (upper, 100.0 + gap)].into_iter().enumerate() {
d.insert(Some(l), i, Node::path(id, PathData::single(SubPath::polyline(&square(x), true)), Appearance::default_art())).unwrap();
}
(d, lower, upper)
}
fn ev(kind: PointerKind, x: f64, y: f64, shift: bool, alt: bool) -> PointerEvent {
let mut e = PointerEvent::new(kind, x, y);
(e.mods.shift, e.mods.alt) = (shift, alt);
e
}
/// The params of a click at (x, y).
fn click(t: &mut SharedEdgeTool, cx: &ToolContext, x: f64, y: f64, shift: bool, alt: bool) -> Option<Value> {
t.pointer(cx, &ev(PointerKind::Down, x, y, shift, alt));
match t.pointer(cx, &ev(PointerKind::Up, x, y, shift, alt)).as_slice() {
[Action::Exec(cmd, p)] => {
assert_eq!(cmd, "addon.pathtools.mergeEdge");
Some(p.clone())
}
[] => None,
other => panic!("{other:?}"),
}
}
#[test]
fn an_edge_merged_already_shows_green_and_a_click_leaves_it() {
let (d, ..) = doc_with_squares(0.0);
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SharedEdgeTool::default();
assert!(t.pointer(&cx, &ev(PointerKind::Move, 100.0, 50.0, false, false)).is_empty());
// They are one edge already: it shows green and a click has nothing to do.
let shows = t.overlays(&cx);
assert!(matches!(shows.as_slice(), [Overlay::Path { color: GREY, .. }, Overlay::Path { color: GREEN, dashed: false, .. }]), "{shows:?}");
assert_eq!(click(&mut t, &cx, 100.0, 50.0, false, false), None);
assert!(!t.busy());
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::SharedEdge);
}
#[test]
fn a_click_averages_the_stretches_and_shift_and_alt_follow_a_path() {
// The stretches differ, their ends coincident within the tolerance set.
let (d, lower, upper) = doc_with_squares(1.0);
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SharedEdgeTool::default();
t.set_option("tolerance", &json!(3));
t.pointer(&cx, &ev(PointerKind::Move, 100.5, 50.0, false, false));
let shows = t.overlays(&cx);
assert!(
matches!(
shows.as_slice(),
[
_,
Overlay::Path { color: BLUE, dashed: true, .. },
Overlay::Path { color: BLUE, dashed: true, .. },
Overlay::Path { dashed: false, .. }
]
),
"{shows:?}"
);
let plain = click(&mut t, &cx, 100.5, 50.0, false, false).expect("a merge");
assert_eq!((plain["a"].clone(), plain["b"].clone(), plain["follow"].clone()), (json!(upper.0), json!(lower.0), json!("average")));
assert_eq!((plain["at"].clone(), plain["ends"].clone(), plain["tolerance"].clone()), (json!([100.5, 50.0]), json!(false), json!(3.0)));
assert_eq!(click(&mut t, &cx, 100.5, 50.0, true, false).expect("a merge")["follow"], json!("a"));
assert_eq!(click(&mut t, &cx, 100.5, 50.0, false, true).expect("a merge")["follow"], json!("b"));
// Shift+Alt: an end, inside the stretch.
let end = click(&mut t, &cx, 100.5, 2.0, true, true).expect("an end");
assert_eq!((end["ends"].clone(), end["follow"].clone()), (json!(true), json!("average")));
}
#[test]
fn near_anchors_make_an_end_and_nothing_near_does_nothing() {
let (d, ..) = doc_with_squares(5.0);
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SharedEdgeTool::default();
t.pointer(&cx, &ev(PointerKind::Move, 102.0, 1.0, false, false));
let shows = t.overlays(&cx);
assert!(matches!(shows.as_slice(), [_, Overlay::Anchor { .. }, Overlay::Anchor { .. }, Overlay::Anchor { filled: true, .. }]), "{shows:?}");
assert_eq!(click(&mut t, &cx, 102.0, 1.0, false, false).expect("an end")["ends"], json!(false));
// One path alone, and empty canvas.
assert_eq!(click(&mut t, &cx, 0.0, 50.0, false, false), None);
assert_eq!(click(&mut t, &cx, 300.0, 300.0, false, false), None);
}
#[test]
fn locked_paths_are_left_alone_and_escape_drops_a_press() {
let (mut d, _, upper) = doc_with_squares(5.0);
d.node_mut(upper).unwrap().locked = true;
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SharedEdgeTool::default();
assert_eq!(click(&mut t, &cx, 102.0, 1.0, false, false), None);
t.pointer(&cx, &ev(PointerKind::Down, 102.0, 1.0, false, false));
assert!(t.busy() && t.claims_key(&cx, ToolKey::Escape));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
assert!(!t.busy());
assert!(t.pointer(&cx, &ev(PointerKind::Up, 102.0, 1.0, false, false)).is_empty());
}
#[test]
fn options_stay_in_range() {
let mut t = SharedEdgeTool::default();
for (k, v) in
[("diameter", json!(1000)), ("diameter", json!(0.1)), ("tolerance", json!(4)), ("tolerance", json!("x")), ("together", json!(1))]
{
t.set_option(k, &v);
}
assert_eq!(t.options(), json!({ "diameter": DIAMETER, "tolerance": COINCIDENCE, "together": false }));
t.set_option("diameter", &json!(40));
t.set_option("tolerance", &json!(0));
t.set_option("together", &json!(true));
assert_eq!(t.options(), json!({ "diameter": 40.0, "tolerance": 0.0, "together": true }));
}
}
+231
View File
@@ -0,0 +1,231 @@
//! Slide Anchor Along Path (Path Precision Tools): drag an anchor, selected or not, and it runs
//! along the curve it sits on, the two segments beside it refitted so the outline stays
//! (`addon.pathtools.slideAnchor`, previewed while dragging, one undo step). Shift snaps to where
//! the path's tangent is at a multiple of 45° from the constrain angle. Ends of open paths don't
//! slide.
use serde_json::json;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Point, SubPath};
use vectorcraft_pathops::addons::pathtools::{slide_stops, slide_t_at};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// The tool's id.
pub const ID: &str = "slideAnchor";
/// The undo step's name.
const LABEL: &str = "Slide Anchor Along Path";
const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff];
const SIZE: f32 = 7.0;
/// An anchor that can slide.
#[derive(Clone, Debug, PartialEq)]
struct Grip {
id: NodeId,
subpath: usize,
anchor: usize,
p: Point,
/// The subpath as it was.
sp: SubPath,
}
#[derive(Default)]
pub struct SlideAnchorTool {
hover: Option<Grip>,
/// The anchor being dragged and how far along.
drag: Option<(Grip, f64)>,
}
/// The anchor of an editable path nearest `p` within the point tolerance that can slide.
fn grip_at(cx: &ToolContext, p: Point) -> Option<Grip> {
let (tol, editable) = (cx.point_tol(), cx.doc.editable());
let mut best: Option<(f64, NodeId, usize, usize, Point)> = None;
cx.doc.walk(|n| {
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
for (si, ai, a) in path.anchors() {
let d = a.p.distance(p);
let open_end = path.subpaths.get(si).is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()));
if d <= tol && !open_end && best.is_none_or(|b| d < b.0) && editable(n.id) {
best = Some((d, n.id, si, ai, a.p));
}
}
});
let (_, id, subpath, anchor, at) = best?;
let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?.clone();
Some(Grip { id, subpath, anchor, p: at, sp })
}
/// How far along a drag to `p` takes `g`: with Shift, to the nearest place where the tangent is at
/// a multiple of 45° from the constrain angle.
fn slide_to(cx: &ToolContext, g: &Grip, p: Point, mods: Mods) -> f64 {
let t = slide_t_at(&g.sp, g.anchor, p).unwrap_or(0.0);
let stops = if mods.shift { slide_stops(&g.sp, g.anchor, cx.constrain_angle) } else { vec![] };
stops.into_iter().min_by(|a, b| (a - t).abs().total_cmp(&(b - t).abs())).unwrap_or(t)
}
impl Tool for SlideAnchorTool {
fn id(&self) -> &'static str {
ID
}
fn busy(&self) -> bool {
self.drag.is_some()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
match ev.kind {
PointerKind::Move => {
self.hover = grip_at(cx, ev.pos);
vec![]
}
PointerKind::Down => {
let Some(g) = grip_at(cx, ev.pos) else { return vec![] };
self.hover = None;
self.drag = Some((g, 0.0));
vec![Action::Begin(LABEL.into())]
}
PointerKind::Drag | PointerKind::Up => {
let Some((g, _)) = self.drag.take() else { return vec![] };
let t = slide_to(cx, &g, ev.pos, ev.mods);
let params = json!({ "id": g.id.0, "subpath": g.subpath, "anchor": g.anchor, "t": t });
let preview = Action::Preview("addon.pathtools.slideAnchor".into(), params);
if ev.kind == PointerKind::Drag {
self.drag = Some((g, t));
return vec![preview];
}
// Back where it started: nothing to keep.
if t == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] }
}
PointerKind::DoubleClick => vec![],
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape && self.drag.take().is_some() { vec![Action::Cancel] } else { vec![] }
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
self.drag.is_some() && key == ToolKey::Escape
}
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
}
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
let anchor = |p, filled| Overlay::Anchor { p, color: BLUE, filled, size: SIZE };
match (&self.drag, &self.hover) {
(Some((g, _)), _) => vec![anchor(g.p, false)],
(None, Some(g)) => vec![anchor(g.p, true)],
(None, None) => vec![],
}
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::SlideAnchor
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::*;
use vectorcraft_doc::{Appearance, Document, Node, Selection};
use vectorcraft_geom::PathData;
/// A document with an open zigzag (100, 100), (200, 100), (300, 100) and a circle-ish curve.
fn doc_with_line() -> (Document, NodeId) {
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let pts = [Point::new(100.0, 100.0), Point::new(200.0, 100.0), Point::new(300.0, 100.0)];
d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, false)), Appearance::default_art())).unwrap();
(d, id)
}
fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent {
PointerEvent::new(kind, x, y)
}
#[test]
fn dragging_an_anchor_previews_the_slide_and_commits() {
let (d, id) = doc_with_line();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SlideAnchorTool::default();
assert!(t.pointer(&cx, &ev(PointerKind::Move, 201.0, 101.0)).is_empty());
assert!(matches!(t.overlays(&cx).as_slice(), [Overlay::Anchor { filled: true, .. }]));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 201.0, 101.0)), vec![Action::Begin(LABEL.into())]);
assert!(t.busy());
let drag = t.pointer(&cx, &ev(PointerKind::Drag, 250.0, 130.0));
let Some(Action::Preview(cmd, params)) = drag.first() else { panic!("{drag:?}") };
assert_eq!(cmd, "addon.pathtools.slideAnchor");
assert_eq!((params["id"].clone(), params["subpath"].clone(), params["anchor"].clone()), (json!(id.0), json!(0), json!(1)));
assert!((params["t"].as_f64().unwrap() - 0.5).abs() < 1e-6);
// The other way along the path.
let up = t.pointer(&cx, &ev(PointerKind::Up, 175.0, 90.0));
assert!(matches!(up.as_slice(), [Action::Preview(_, p), Action::Commit] if p["t"].as_f64().unwrap() < 0.0), "{up:?}");
assert!(!t.busy());
}
#[test]
fn back_where_it_started_nothing_is_kept_and_escape_cancels() {
let (d, _) = doc_with_line();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SlideAnchorTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 100.0));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 100.0)), vec![Action::Cancel]);
t.pointer(&cx, &ev(PointerKind::Down, 200.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Drag, 250.0, 100.0));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
assert!(!t.busy() && !t.claims_key(&cx, ToolKey::Escape));
}
#[test]
fn ends_and_empty_canvas_do_nothing() {
let (d, _) = doc_with_line();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SlideAnchorTool::default();
for (x, y) in [(100.0, 100.0), (300.0, 100.0), (150.0, 300.0)] {
assert!(t.pointer(&cx, &ev(PointerKind::Down, x, y)).is_empty(), "({x}, {y})");
assert!(t.pointer(&cx, &ev(PointerKind::Up, x, y)).is_empty());
}
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::SlideAnchor);
}
#[test]
fn shift_snaps_to_where_the_tangent_is_at_45_degrees() {
// A smooth anchor on a curve turning from east to south through south-east.
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let a = |x: f64, y: f64, h: (f64, f64), o: (f64, f64)| vectorcraft_geom::Anchor {
p: Point::new(x, y),
h_in: Point::new(h.0, h.1),
h_out: Point::new(o.0, o.1),
kind: vectorcraft_geom::AnchorKind::Smooth,
};
let sp = SubPath::new(
vec![
a(0.0, 100.0, (0.0, 100.0), (0.0, 100.0)),
a(100.0, 100.0, (100.0, 100.0), (155.0, 100.0)),
a(200.0, 200.0, (200.0, 145.0), (200.0, 200.0)),
],
false,
);
d.insert(Some(l), 0, Node::path(id, PathData::single(sp.clone()), Appearance::default_art())).unwrap();
let (sel, p) = (Selection::default(), paint());
let cx = cx(&d, &sel, &p);
let mut t = SlideAnchorTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 100.0, 100.0));
let mut shifted = ev(PointerKind::Drag, 140.0, 105.0);
shifted.mods.shift = true;
let drag = t.pointer(&cx, &shifted);
let Some(Action::Preview(_, params)) = drag.first() else { panic!("{drag:?}") };
let at = params["t"].as_f64().unwrap();
assert!((at - 0.5).abs() < 1e-6, "half way round a symmetric quarter turn: {at}");
}
}
+34 -10
View File
@@ -87,13 +87,14 @@ fn lp_overlays(h: &LpHover, cache: &RegionCache, color: [u8; 3], width: f32) ->
}
/// Live Paint Bucket: click fills the face under the cursor with the current fill; Shift-click
/// paints the nearest edge with the current stroke. Clicking selected ordinary paths makes them a
/// Live Paint group first.
/// paints the nearest edge with the current stroke. Alt-click samples a fill or stroke into the
/// paint defaults; Alt+Shift-click samples only the color under the pointer. Clicking selected
/// ordinary paths without Alt makes them a Live Paint group first.
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
/// Where the pointer last moved, and whether Shift was held.
at: Option<(Point, bool)>,
/// Where the pointer last moved, and whether Shift and Alt were held.
at: Option<(Point, bool, bool)>,
}
impl Default for LivePaintBucketTool {
@@ -111,12 +112,35 @@ impl Tool for LivePaintBucketTool {
let p = ev.pos;
match ev.kind {
PointerKind::Move => {
self.at = Some((p, ev.mods.shift));
self.hover = lp_hover(cx, Some(&mut self.cache), p, ev.mods.shift, &|id| lp_visible(cx, id));
self.at = Some((p, ev.mods.shift, ev.mods.alt));
self.hover =
if ev.mods.alt { LpHover::None } else { lp_hover(cx, Some(&mut self.cache), p, ev.mods.shift, &|id| lp_visible(cx, id)) };
vec![]
}
PointerKind::Down => {
self.hover = LpHover::None;
if ev.mods.alt {
if ev.mods.shift {
return crate::xform::eyedropper::sample_color_at(cx, p).map_or_else(Vec::new, |color| {
vec![Action::Exec("paint.sampleColor".into(), json!({ "color": crate::params::color_json(&color), "ids": [] }))]
});
}
return crate::xform::eyedropper::sample_source(cx, p).map_or_else(Vec::new, |(source, _)| {
if cx.doc.node(source).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Image(_))) {
return crate::xform::eyedropper::sample_color_at(cx, p).map_or_else(Vec::new, |color| {
vec![Action::Exec(
"paint.sampleColor".into(),
json!({ "color": crate::params::color_json(&color), "stroke": false, "ids": [], "clearStroke": true }),
)]
});
}
if crate::xform::eyedropper::has_sampleable_paint(cx, source) {
vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": source.0, "defaultsOnly": true }))]
} else {
vec![]
}
});
}
let point = json!([p.x, p.y]);
if ev.mods.shift {
return match lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) {
@@ -143,8 +167,8 @@ impl Tool for LivePaintBucketTool {
lp_overlays(&self.hover, &self.cache, HIGHLIGHT_RED, 4.0)
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
Cursor::LivePaintBucket
fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor {
if m.alt { Cursor::Eyedropper } else { Cursor::LivePaintBucket }
}
fn waiting(&self) -> bool {
@@ -159,8 +183,8 @@ impl Tool for LivePaintBucketTool {
// of a Live Paint group the hover takes no map.
loop {
self.cache.settle(wait);
if let Some((p, shift)) = self.at {
self.hover = lp_hover(cx, Some(&mut self.cache), p, shift, &|id| lp_visible(cx, id));
if let Some((p, shift, alt)) = self.at {
self.hover = if alt { LpHover::None } else { lp_hover(cx, Some(&mut self.cache), p, shift, &|id| lp_visible(cx, id)) };
}
if !wait || !self.cache.waiting() {
break;
+119
View File
@@ -765,6 +765,125 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
assert_eq!(id, "livePaint.strokeEdge");
}
#[test]
fn bucket_alt_samples_face_edge_and_selected_region_without_painting() {
let (mut d, _gid, face, edge) = live_group_doc();
d.node_mut(face).unwrap().appearance.set_fill(vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE));
d.node_mut(edge).unwrap().appearance.set_stroke(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK));
let s = Selection::default();
let p = paint();
let cx = crate::testutil::cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
let alt = Mods { alt: true, ..Default::default() };
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0).with_mods(alt)),
vec![Action::Exec("appearance.copyFrom".into(), json!({"source": face.0, "defaultsOnly": true}))]
);
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 50.0, 25.0).with_mods(alt)),
vec![Action::Exec("appearance.copyFrom".into(), json!({"source": edge.0, "defaultsOnly": true}))]
);
let (d, a, b) = two_rects();
let mut s = Selection::default();
s.set([a, b]);
let cx = crate::testutil::cx(&d, &s, &p);
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0).with_mods(alt)),
vec![Action::Exec("appearance.copyFrom".into(), json!({"source": b.0, "defaultsOnly": true}))]
);
assert!(t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0).with_mods(alt)).is_empty());
let (d, _, _, _) = live_group_doc();
assert!(t.pointer(&crate::testutil::cx(&d, &Selection::default(), &p), &ev(PointerKind::Down, 75.0, 25.0).with_mods(alt)).is_empty());
}
#[test]
fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() {
let (mut d, _gid, face, _edge) = live_group_doc();
d.node_mut(face).unwrap().appearance.set_fill(vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE));
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
let alt = Mods { alt: true, ..Default::default() };
let both = Mods { alt: true, shift: true, ..Default::default() };
let pos = Point::new(75.0, 25.0);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert!(!t.overlays(&cx).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0).with_mods(alt));
assert_eq!(t.cursor(&cx, pos, alt), Cursor::Eyedropper);
assert_eq!(t.id(), "livePaintBucket");
assert!(t.overlays(&cx).is_empty());
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0).with_mods(both)),
vec![Action::Exec("paint.sampleColor".into(), json!({"color": crate::params::color_json(&vectorcraft_color::Color::WHITE), "ids": []}))]
);
assert!(t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0).with_mods(both)).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
assert!(!t.overlays(&cx).is_empty());
}
#[test]
fn bucket_alt_shift_samples_gradient_image_and_stroke_color() {
let (mut d, _a, b) = two_rects();
let gradient = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default())));
d.node_mut(b).unwrap().appearance.set_fill(gradient.clone());
let s = Selection::default();
let p = paint();
let both = Mods { alt: true, shift: true, ..Default::default() };
let mut t = LivePaintBucketTool::default();
assert_eq!(
t.pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 100.0, 50.0).with_mods(both)),
vec![Action::Exec(
"paint.sampleColor".into(),
json!({"color": crate::params::color_json(&vectorcraft_color::Color::rgb(0.5, 0.5, 0.5)), "ids": []})
)]
);
let (mut d, _gid, _face, edge) = live_group_doc();
d.node_mut(edge).unwrap().appearance.set_stroke(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK));
assert_eq!(
t.pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 50.0, 25.0).with_mods(both)),
vec![Action::Exec("paint.sampleColor".into(), json!({"color": crate::params::color_json(&vectorcraft_color::Color::BLACK), "ids": []}))]
);
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let img = image::RgbaImage::from_raw(3, 1, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]].concat()).unwrap();
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
d.images.insert("px".into(), vectorcraft_doc::ImageBlob::png(png));
let im = vectorcraft_doc::ImageObject {
key: "px".into(),
width: 3,
height: 1,
xf: vectorcraft_geom::Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let id = d.alloc_id();
d.insert(Some(l), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im)))).unwrap();
let mut cx = cx(&d, &s, &p);
cx.raster_sample = 3;
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 15.0, 5.0).with_mods(Mods { alt: true, ..Default::default() })),
vec![Action::Exec(
"paint.sampleColor".into(),
json!({"color": crate::params::color_json(&vectorcraft_color::Color::rgb8(85, 85, 85)), "stroke": false, "ids": [], "clearStroke": true})
)]
);
assert_eq!(
t.pointer(&cx, &ev(PointerKind::Down, 15.0, 5.0).with_mods(both)),
vec![Action::Exec(
"paint.sampleColor".into(),
json!({"color": crate::params::color_json(&vectorcraft_color::Color::rgb8(85, 85, 85)), "ids": []})
)]
);
}
#[test]
fn bucket_on_plain_selection_makes_live_paint() {
let (d, a, b) = two_rects();
+16 -1
View File
@@ -180,6 +180,15 @@ pub enum Cursor {
/// The Parametric Shape Tool (Path Precision Tools add-on): a drag draws a shape out from its
/// centre; a selected shape's handles edit it.
ParametricShape,
/// The Corner Tool (Path Precision Tools add-on): a click or drag on an anchor cuts a corner;
/// a corner's marker resizes it.
CornerTool,
/// The Slide Anchor Along Path tool (Path Precision Tools add-on): a drag runs an anchor along
/// the path.
SlideAnchor,
/// The Shared Edge Merge Tool (Path Precision Tools add-on): a click merges the two paths'
/// touching edges under the brush, or makes an end there.
SharedEdge,
/// The Smart Pen Tool (Smart Pen add-on) away from paths, where a click starts a new path (over
/// a path or while drawing it shows the Pen's and Direct Selection's cursors).
SmartPen,
@@ -278,6 +287,9 @@ impl Cursor {
| Cursor::ExtendPath
| Cursor::MeasureInspect
| Cursor::ParametricShape
| Cursor::CornerTool
| Cursor::SlideAnchor
| Cursor::SharedEdge
| Cursor::SmartPen => Cursor::Crosshair,
c => c,
}
@@ -316,7 +328,10 @@ impl Cursor {
| Cursor::AnchorEraser
| Cursor::ExtendPath
| Cursor::MeasureInspect
| Cursor::ParametricShape => Some(Cursor::Crosshair),
| Cursor::ParametricShape
| Cursor::CornerTool
| Cursor::SlideAnchor
| Cursor::SharedEdge => Some(Cursor::Crosshair),
Cursor::TypeVertical => Some(Cursor::Text),
Cursor::MeshAdd | Cursor::PuppetPin => Some(Cursor::PenAdd),
Cursor::SmartPen => Some(Cursor::Pen),
+18
View File
@@ -702,6 +702,24 @@ group = "Drawing and editing tools"
shown_when = ["The Parametric Shape Tool (Path Precision Tools add-on): a drag draws a re-editable shape out from its centre; a click selects one and shows its handles."]
hotspot = "Exact: the centre of the shape being drawn."
[[cursor]]
id = "CornerTool"
group = "Drawing and editing tools"
shown_when = ["The Corner Tool (Path Precision Tools add-on): a click or drag on an anchor where two sides meet cuts a corner there; a drag on a corner's marker resizes it; an Alt-drag cuts corners on every anchor inside the marquee."]
hotspot = "Exact: the anchor or marker being picked."
[[cursor]]
id = "SlideAnchor"
group = "Drawing and editing tools"
shown_when = ["The Slide Anchor Along Path tool (Path Precision Tools add-on): a drag moves an anchor along the curve it sits on."]
hotspot = "Exact: the anchor being dragged follows it along the path."
[[cursor]]
id = "SharedEdge"
group = "Drawing and editing tools"
shown_when = ["The Shared Edge Merge Tool (Path Precision Tools add-on): a click merges the touching edges of two paths under the round brush, or brings their anchors together there."]
hotspot = "Exact: the centre of the brush, drawn by the app as a circle around the cursor."
# ── Symbolism tools ───────────────────────────────────────────────────────────────────────────────
# The brush size is drawn by the app as a circle around the cursor.
+1 -1
View File
@@ -261,7 +261,7 @@ fn anchor_point_shift_constrains_a_blend_spine_handle() {
let shift = Mods { shift: true, ..Mods::default() };
let mut tool = AnchorTool::new("anchorPoint");
tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 190.0, 330.0));
let drag = PointerEvent { kind: PointerKind::Drag, pos: Point::new(200.0, 340.0), mods: shift, pressure: 1.0 };
let drag = PointerEvent { kind: PointerKind::Drag, pos: Point::new(200.0, 340.0), mods: shift, backquote: false, pressure: 1.0 };
let actions = tool.pointer(&c, &drag);
// The pointer (40, 30) keeps its length of 50; Shift snaps it to 45 degrees.
assert!(matches!(actions.get(1), Some(Action::Preview(cmd, args))
+40 -14
View File
@@ -14,6 +14,8 @@
//! collect the drag polyline (shown as an overlay) and run one command on release. With Shift held, the Blob Brush's points stay on the horizontal or
//! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag
//! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths.
//! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke
//! begins closes the path on release.
//! Alt held at the Knife's press makes it cut along the straight line from the press point to the
//! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that
//! line to 45° steps from the canvas axes.
@@ -26,8 +28,8 @@ use super::{FEEDBACK, eraser_area, points_json, polyline};
use crate::guides::DrawSnap;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
/// How far from its drag the Smooth tool smooths, in screen pixels. The Pencil uses the same
/// radius while Alt switches it to the Smooth tool.
/// How far from its drag the Smooth tool smooths, in screen pixels. Alt smoothing with the
/// Pencil, Paintbrush or Blob Brush uses the same radius.
const SMOOTH_RADIUS: f64 = 12.0;
/// The finest Fidelity (screen pixels) a Pencil or Paintbrush stroke is fitted at while it is drawn:
@@ -79,7 +81,8 @@ pub struct GestureTool {
/// or merges into (on for the Pencil and Paintbrush, off for the Blob Brush).
pub keep_selected: bool,
/// "Alt key toggles to Smooth Tool": holding Alt with the Pencil tool smooths selected paths
/// instead of closing the path (Pencil only, off by default).
/// instead of closing the path (Pencil only, off by default). Paintbrush Alt smoothing with a
/// selected path and Blob Brush Alt smoothing do not use this toggle.
pub alt_smooth: bool,
/// "Live preview" (Pencil only, on by default): the stroke shows with its fill and stroke as it
/// is drawn. Off, only a thin line follows the pen while drawing, and the path takes its fill
@@ -89,10 +92,10 @@ pub struct GestureTool {
/// preview shows the points joined by straight segments and the release fits them (Pencil
/// only, on by default).
pub live_fit: bool,
/// The Smooth tool's Fidelity, used when Alt switches the Pencil or Blob Brush to Smooth.
/// The Smooth tool's Fidelity, used when Alt switches the Pencil, Paintbrush or Blob Brush to Smooth.
/// The engine sets it from Smooth Tool Options (`smoothFidelity`).
smooth_fidelity: f64,
/// Active drag is smoothing with the Pencil or the Blob Brush (Alt held).
/// Active drag is smoothing with the Pencil, Paintbrush or Blob Brush (Alt held).
smoothing: bool,
/// The pointer has moved from the press point, by any distance (a move too short to add a
/// point counts).
@@ -126,6 +129,22 @@ fn redraw_targets(cx: &ToolContext, id: NodeId) -> Vec<NodeId> {
}
}
/// Whether the selection contains a path the Smooth command can act on.
fn has_selected_smooth_path(cx: &ToolContext) -> bool {
let editable = cx.doc.editable();
cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)).any(|n| {
let mut found = false;
n.walk(&mut |child| {
if matches!(&child.kind, NodeKind::Path { guide: false, path, .. } if path.control_bounds().is_some() && path.subpaths.iter().any(|sp| sp.anchors.len() >= 3))
&& editable(child.id)
{
found = true;
}
});
found
})
}
impl GestureTool {
pub fn new(id: &str) -> Self {
let id: &'static str = match id {
@@ -402,7 +421,7 @@ impl GestureTool {
// Close Paths When Ends Are Within is off at 0 pixels.
let near = pts.last().is_some_and(|&end| self.ends_near_start(cx, end));
// A straight line has two points: closing it would draw it back over itself.
let closed = !self.straight && ((m.alt && !self.alt_smooth) || (self.extend.is_none() && near));
let closed = !self.straight && ((m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || (self.extend.is_none() && near));
let mut params = self.freehand_params(closed);
// A Pencil stroke that continues a selected path and ends on an open end of another
// path selected at the press connects the two.
@@ -464,9 +483,12 @@ impl Tool for GestureTool {
self.active = true;
self.began = false;
self.near_start = false;
// Alt switches the Pencil to the Smooth tool while Alt key toggles to Smooth Tool is on, and always
// switches the Blob Brush.
self.smoothing = ev.mods.alt && (self.id == "blobBrush" || (self.id == "pencil" && self.alt_smooth));
// Alt switches the Pencil when its toggle is on, the Blob Brush always, and the
// Paintbrush when the press has a selected path.
self.smoothing = ev.mods.alt
&& (self.id == "blobBrush"
|| (self.id == "pencil" && self.alt_smooth)
|| (self.id == "paintbrush" && has_selected_smooth_path(cx)));
// Alt draws a straight line only while it doesn't lend the Smooth tool; with Shift
// too, the line keeps Shift's 45° steps. Alt makes the Knife cut along a straight line.
self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt);
@@ -694,9 +716,13 @@ impl Tool for GestureTool {
o
}
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
// A drag that smooths, or Alt before a Pencil or Blob Brush stroke has begun to draw (a
// stroke that has begun keeps drawing with Alt).
if self.smoothing || (self.id == "pencil" && self.alt_smooth && m.alt && !self.began) || self.blob_alt_smooths(m) {
// An active smoothing drag, or Alt before a press that would switch the Pencil, Paintbrush
// or Blob Brush to Smooth. A Paintbrush stroke already drawing keeps drawing with Alt.
if self.smoothing
|| (self.id == "pencil" && self.alt_smooth && m.alt && !self.began)
|| (!self.active && self.id == "paintbrush" && m.alt && has_selected_smooth_path(cx))
|| self.blob_alt_smooths(m)
{
return Cursor::Smooth;
}
// Before a press that would draw a straight line: over an end of a selected open path,
@@ -707,7 +733,7 @@ impl Tool for GestureTool {
// Alt held at the release closes the path (`finish`).
// A straight line stays open, so its release has nothing to close, and before a press Alt
// gives the Pencil a straight line.
if self.draws_path() && !self.alt_smooth && m.alt && !self.straight && (self.active || self.id != "pencil") {
if self.draws_path() && (self.id == "paintbrush" || !self.alt_smooth) && m.alt && !self.straight && (self.active || self.id != "pencil") {
return if self.id == "paintbrush" { Cursor::PaintbrushClose } else { Cursor::PencilClose };
}
// A release near a freehand stroke's start closes it too (`finish`): the ring shows while
@@ -789,7 +815,7 @@ impl Tool for GestureTool {
"altSmooth" => self.alt_smooth = v.as_bool().unwrap_or(self.alt_smooth),
"livePreview" if self.id == "pencil" => self.live_preview = v.as_bool().unwrap_or(self.live_preview),
"liveFit" if self.id == "pencil" => self.live_fit = v.as_bool().unwrap_or(self.live_fit),
"smoothFidelity" if matches!(self.id, "pencil" | "blobBrush") => {
"smoothFidelity" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => {
self.smooth_fidelity = v.as_f64().unwrap_or(self.smooth_fidelity).clamp(super::min_fidelity("smooth"), 100.0)
}
"keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected),
+79 -7
View File
@@ -872,7 +872,7 @@ fn pencil_alt_smooths_within_the_smooth_tools_radius() {
}
}
/// An Alt smoothing drag uses the Smooth tool's Fidelity for both Pencil and Blob Brush.
/// An Alt smoothing drag uses the Smooth tool's Fidelity for Pencil, Paintbrush and Blob Brush.
#[test]
fn alt_smoothing_uses_the_smooth_tools_fidelity() {
let (d, id) = doc_with_rect();
@@ -888,21 +888,93 @@ fn alt_smoothing_uses_the_smooth_tools_fidelity() {
};
let alt = Mods { alt: true, ..Default::default() };
let want = fidelity(&drag(&mut GestureTool::new("smooth"), &cx, &pts, Mods::default()));
for id in ["pencil", "blobBrush"] {
for (id, alt_smooth) in [("pencil", true), ("blobBrush", false), ("paintbrush", false), ("paintbrush", true)] {
let mut t = GestureTool::new(id);
if id == "pencil" {
t.set_option("altSmooth", &json!(true));
}
t.set_option("altSmooth", &json!(alt_smooth));
t.set_option("fidelity", &json!(10.0));
assert_eq!(fidelity(&drag_held(&mut t, &cx, &pts, alt)), want, "{id}");
assert_eq!(fidelity(&drag_held(&mut t, &cx, &pts, alt)), want, "{id} altSmooth={alt_smooth}");
t.set_option("smoothFidelity", &json!(7.5));
assert_eq!(fidelity(&drag_held(&mut t, &cx, &pts, alt)), 7.5, "{id}");
assert_eq!(fidelity(&drag_held(&mut t, &cx, &pts, alt)), 7.5, "{id} altSmooth={alt_smooth}");
// Drawing keeps the tool's own Fidelity; Smooth's setting stays out of its options.
assert_eq!(t.options()["fidelity"], json!(10.0), "{id}");
assert!(t.options().get("smoothFidelity").is_none(), "{id}");
}
}
/// Alt pressed after a Paintbrush stroke begins closes it, and an empty selection still draws.
#[test]
fn paintbrush_alt_after_press_closes_without_smoothing_and_empty_selection_draws() {
let (d, id) = doc_with_rect();
let mut selected = Selection::default();
selected.set([id]);
let empty = Selection::default();
let p = paint();
let alt = Mods { alt: true, ..Default::default() };
let pts = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)];
let mut t = GestureTool::new("paintbrush");
let selected_cx = cx(&d, &selected, &p);
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1));
t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Drag, pts[1].0, pts[1].1).with_mods(alt));
let last = t.pointer(&selected_cx, &PointerEvent::new(PointerKind::Up, pts[2].0, pts[2].1).with_mods(alt));
assert!(matches!(last.first(), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}");
let cx = cx(&d, &empty, &p);
let last = drag_held(&mut t, &cx, &pts, alt);
assert!(matches!(last.last().and_then(|a| a.first()), Some(Action::Preview(c, v)) if c == "path.freehand" && v["closed"] == true), "{last:?}");
}
/// The Paintbrush shows Smooth before an Alt press only with a selected path.
#[test]
fn paintbrush_alt_cursor_matches_selection_at_press() {
let (d, id) = doc_with_rect();
let mut selected = Selection::default();
selected.set([id]);
let empty = Selection::default();
let p = paint();
let alt = Mods { alt: true, ..Default::default() };
let t = GestureTool::new("paintbrush");
assert_eq!(t.cursor(&cx(&d, &selected, &p), Point::new(50.0, 150.0), alt), Cursor::Smooth);
assert_eq!(t.cursor(&cx(&d, &empty, &p), Point::new(50.0, 150.0), alt), Cursor::PaintbrushClose);
}
/// A selected text object leaves Alt Paintbrush drawing a closed stroke with its close cursor.
#[test]
fn paintbrush_alt_with_only_text_selected_draws_a_closed_stroke() {
let (d, text_id) = doc_with_area_type();
let mut selected = Selection::default();
selected.set([text_id]);
let p = paint();
let cx = cx(&d, &selected, &p);
let alt = Mods { alt: true, ..Default::default() };
let mut t = GestureTool::new("paintbrush");
assert_eq!(t.cursor(&cx, Point::new(50.0, 150.0), alt), Cursor::PaintbrushClose);
let acts = drag_held(&mut t, &cx, &[(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)], alt);
assert!(acts.iter().flatten().any(|a| matches!(a, Action::Preview(c, v) if c == "path.freehand" && v["closed"] == true)), "{acts:?}");
assert!(matches!(acts.last().and_then(|a| a.get(1)), Some(Action::Commit)), "{acts:?}");
}
/// A selected two-anchor line leaves Alt Paintbrush drawing a closed stroke with its close cursor.
#[test]
fn paintbrush_alt_with_only_two_anchor_line_selected_draws_a_closed_stroke() {
let (mut d, _) = doc_with_rect();
let layer = d.layers[0].id;
let id = d.alloc_id();
let line = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![
vectorcraft_geom::PathEl::MoveTo(Point::new(300.0, 300.0)),
vectorcraft_geom::PathEl::LineTo(Point::new(400.0, 300.0)),
]));
d.insert(Some(layer), 1, vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art())).unwrap();
let mut selected = Selection::default();
selected.set([id]);
let p = paint();
let cx = cx(&d, &selected, &p);
let alt = Mods { alt: true, ..Default::default() };
let mut t = GestureTool::new("paintbrush");
assert_eq!(t.cursor(&cx, Point::new(50.0, 150.0), alt), Cursor::PaintbrushClose);
let acts = drag_held(&mut t, &cx, &[(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)], alt);
assert!(acts.iter().flatten().any(|a| matches!(a, Action::Preview(c, v) if c == "path.freehand" && v["closed"] == true)), "{acts:?}");
assert!(matches!(acts.last().and_then(|a| a.get(1)), Some(Action::Commit)), "{acts:?}");
}
/// #3799: Alt's line starts and ends on Smart Guides as a stroke does, and pressed on an end of
/// a selected open path it continues the path from that end to the pointer.
#[test]
+19 -1
View File
@@ -38,6 +38,9 @@ pub struct PointerEvent {
pub pos: Point,
#[serde(default)]
pub mods: Mods,
/// Whether backquote is held for this event.
#[serde(default)]
pub backquote: bool,
#[serde(default = "one")]
pub pressure: f32,
}
@@ -48,7 +51,7 @@ fn one() -> f32 {
impl PointerEvent {
pub fn new(kind: PointerKind, x: f64, y: f64) -> Self {
Self { kind, pos: Point::new(x, y), mods: Mods::default(), pressure: 1.0 }
Self { kind, pos: Point::new(x, y), mods: Mods::default(), backquote: false, pressure: 1.0 }
}
pub fn with_mods(mut self, m: Mods) -> Self {
self.mods = m;
@@ -65,6 +68,21 @@ impl PointerEvent {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backquote_json_defaults_false_and_decodes_true() {
let event = PointerEvent::new(PointerKind::Down, 10.0, 20.0);
let mut value = serde_json::to_value(event).unwrap();
value.as_object_mut().unwrap().remove("backquote");
assert!(!serde_json::from_value::<PointerEvent>(value.clone()).unwrap().backquote);
value["backquote"] = serde_json::json!(true);
assert!(serde_json::from_value::<PointerEvent>(value).unwrap().backquote);
}
}
/// Keys tools care about.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ToolKey {
+86 -29
View File
@@ -123,6 +123,10 @@ pub struct SelectionTool {
/// The params of the move's last preview: in Shaper's Construction mode the move ends with
/// them and `releaseOutside` ([`construction`]).
last_move: Option<Value>,
/// Held state used for the most recent bounding-box preview.
last_backquote: bool,
/// Pointer position used for the most recent bounding-box preview.
last_box_pos: Option<Point>,
/// The move snapped to a point or a guide at its last step: the arrow turns hollow.
snapped: bool,
guide: GuideEdit,
@@ -745,8 +749,12 @@ impl Tool for SelectionTool {
}
}
}
(PointerKind::Drag, State::Moving { start, press, hold, began, .. }) => self.drag_moving(cx, p, m, (start, press, hold, began)),
(PointerKind::Drag, State::Moving { start, press, hold, began, .. }) => {
self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, began))
}
(PointerKind::Drag, State::Scaling { handle, bx, areas }) => {
self.last_backquote = ev.backquote;
self.last_box_pos = Some(p);
// Scale in the box's own frame: along the objects' axes when it is rotated.
let mut a = scale_for_drag(bx.rect, handle, bx.to_local(p), m.shift, m.alt);
self.guides.clear();
@@ -760,7 +768,7 @@ impl Tool for SelectionTool {
// visual box the dragged size and keeps its opposite handle (with Alt, its center)
// where it is. A drag that flips the box scales by the matrix.
let [sx, _, _, sy, _, _] = a.as_coeffs();
let (cmd, mut params) = if cx.preview_bounds && cx.selection.anchors.is_empty() && sx > 0.0 && sy > 0.0 {
let (cmd, mut params) = if !ev.backquote && cx.preview_bounds && cx.selection.anchors.is_empty() && sx > 0.0 && sy > 0.0 {
let reference = if m.alt { 4 } else { handle.opposite().reference() };
("object.setBounds", json!({ "width": nr.width(), "height": nr.height(), "reference": reference, "copy": false }))
} else {
@@ -769,12 +777,23 @@ impl Tool for SelectionTool {
if areas {
params["typeAreas"] = json!(true);
}
if ev.backquote {
params["objects"] = json!(false);
params["patterns"] = json!(true);
}
vec![Action::Preview(cmd.into(), params)]
}
(PointerKind::Drag, State::Rotating { center, start, .. }) => {
self.last_backquote = ev.backquote;
self.last_box_pos = Some(p);
let (a, deg) = rotate_for_drag(center, start, p, m.shift);
self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg)));
vec![Action::Preview("object.transform".into(), json!({ "matrix": matrix_json(a), "copy": false }))]
let mut params = json!({ "matrix": matrix_json(a), "copy": false });
if ev.backquote {
params["objects"] = json!(false);
params["patterns"] = json!(true);
}
vec![Action::Preview("object.transform".into(), params)]
}
(PointerKind::Drag, State::Marquee { start, toggle, enclosed, .. }) => {
self.state = State::Marquee { start, cur: p, toggle, enclosed };
@@ -807,35 +826,21 @@ impl Tool for SelectionTool {
self.state = State::Idle;
b.finish()
}
(PointerKind::Up, State::Moving { began, deselect, key, .. }) => {
self.state = State::Idle;
self.measure = None;
self.guides.clear();
self.moving = None;
let last = self.last_move.take();
match (began, deselect, key) {
// In Construction mode, an original shape dropped wholly outside the group's
// bounds leaves the group, in the move's undo step (`releaseOutside`).
(true, ..) => match last.filter(|p| construction(cx) && p["copy"] != json!(true)) {
Some(mut params) => {
params["releaseOutside"] = json!(true);
vec![Action::Preview("object.transform".into(), params), Action::Commit]
}
None => vec![Action::Commit],
},
(false, Some(id), _) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))],
// A click on the key object again: no key.
(false, None, Some(id)) if cx.selection.key == Some(id) => vec![Action::Exec("select.key".into(), json!({}))],
(false, None, Some(id)) if can_be_key(cx, id) => vec![Action::Exec("select.key".into(), json!({ "id": id.0 }))],
(false, None, _) => vec![],
}
}
(PointerKind::Up, State::Moving { began, deselect, key, .. }) => self.release_move(cx, ev.backquote, began, deselect, key),
(PointerKind::Up, State::Scaling { .. } | State::Rotating { .. }) => {
let mut out = if ev.backquote || self.last_backquote {
self.last_box_pos.map_or_else(Vec::new, |pos| self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, pos, ..*ev }))
} else {
vec![]
};
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Idle;
self.measure = None;
self.guides.clear();
self.targets = None;
vec![Action::Commit]
out.push(Action::Commit);
out
}
(PointerKind::Up, State::Marquee { start, toggle, enclosed, .. }) => {
self.state = State::Idle;
@@ -1042,6 +1047,43 @@ pub(crate) fn handle_cursor(h: Handle, angle: f64) -> Cursor {
mod tests;
impl SelectionTool {
fn release_move(&mut self, cx: &ToolContext, backquote: bool, began: bool, deselect: Option<NodeId>, key: Option<NodeId>) -> Vec<Action> {
self.state = State::Idle;
self.measure = None;
self.guides.clear();
self.moving = None;
let changed_mode = self.last_move.as_ref().is_some_and(|params| params.get("objects").is_some()) != backquote;
let last = self.last_move.take().map(|mut params| {
if backquote {
params["objects"] = json!(false);
params["patterns"] = json!(true);
} else if let Some(map) = params.as_object_mut() {
map.remove("objects");
map.remove("patterns");
}
params
});
match (began, deselect, key) {
// In Construction mode, an original shape dropped wholly outside the group's
// bounds leaves the group, in the move's undo step (`releaseOutside`).
(true, ..) if backquote || changed_mode || (construction(cx) && last.as_ref().is_some_and(|p| p["copy"] != json!(true))) => match last {
Some(mut params) => {
if construction(cx) && params["copy"] != json!(true) && !backquote {
params["releaseOutside"] = json!(true);
}
vec![Action::Preview("object.transform".into(), params), Action::Commit]
}
None => vec![Action::Commit],
},
(true, ..) => vec![Action::Commit],
(false, Some(id), _) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))],
// A click on the key object again: no key.
(false, None, Some(id)) if cx.selection.key == Some(id) => vec![Action::Exec("select.key".into(), json!({}))],
(false, None, Some(id)) if can_be_key(cx, id) => vec![Action::Exec("select.key".into(), json!({ "id": id.0 }))],
(false, None, _) => vec![],
}
}
fn repeat_controls(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
if let State::Mirror(mut d) = self.state.clone() {
match ev.kind {
@@ -1176,10 +1218,14 @@ impl SelectionTool {
// grid, else with Smart Guides to the other objects, else with Snap to
// Point to their anchors; the ruler guides with Snap to Point.
self.targets = Some(PointSnap::new(cx, || Targets::for_scale(cx)));
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Scaling { handle, bx, areas };
return Some(vec![Action::Begin(label.into())]);
}
Some(BoxHit::Rotate) => {
self.last_backquote = false;
self.last_box_pos = None;
self.state = State::Rotating { center: bx.center(), start: p };
return Some(vec![Action::Begin("Rotate".into())]);
}
@@ -1202,7 +1248,14 @@ impl SelectionTool {
};
}
fn drag_moving(&mut self, cx: &ToolContext, p: Point, m: Mods, (start, press, hold, began): (Point, Point, Point, bool)) -> Vec<Action> {
fn drag_moving(
&mut self,
cx: &ToolContext,
p: Point,
m: Mods,
backquote: bool,
(start, press, hold, began): (Point, Point, Point, bool),
) -> Vec<Action> {
let mut out = vec![];
if !began {
if p.distance(press) < Self::drag_threshold(cx) {
@@ -1220,7 +1273,11 @@ impl SelectionTool {
self.snapped = (d - unsnapped).hypot() > 1e-9;
self.state = State::Moving { start, press, hold, began: true, deselect: None, key: None };
self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y)));
let params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt });
let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt });
if backquote {
params["objects"] = json!(false);
params["patterns"] = json!(true);
}
self.last_move = Some(params.clone());
out.push(Action::Preview("object.transform".into(), params));
out
+51
View File
@@ -1301,6 +1301,57 @@ fn handle_drag_scales() {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), vec![Action::Commit]);
}
#[test]
fn backquote_move_uses_release_state_and_one_commit() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0));
let drag = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, 170.0, 150.0) });
assert!(matches!(drag.as_slice(), [Action::Begin(_), Action::Preview(_, v)] if v["objects"] == false && v["patterns"] == true));
let up = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Up, 170.0, 150.0) });
assert!(matches!(up.as_slice(), [Action::Preview(_, v), Action::Commit] if v["objects"] == false && v["patterns"] == true));
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, 150.0, 150.0));
t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, 170.0, 150.0) });
let up = t.pointer(&cx, &ev(PointerKind::Up, 170.0, 150.0));
assert!(matches!(up.as_slice(), [Action::Preview(_, v), Action::Commit] if v.get("objects").is_none() && v.get("patterns").is_none()));
}
#[test]
fn backquote_box_scale_and_rotate_use_pattern_matrix_at_release() {
let (d, id) = doc_with_rect();
let mut s = Selection::default();
s.add(id);
let p = paint();
let cx = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
for (from, to) in [((200.0, 200.0), (300.0, 300.0)), ((210.0, 210.0), (150.0, 230.0))] {
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, from.0, from.1));
let drag = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, to.0, to.1) });
assert!(
matches!(drag.as_slice(), [Action::Preview(c, v)] if c == "object.transform" && v["objects"] == false && v["patterns"] == true),
"{drag:?}"
);
let up = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Up, to.0, to.1) });
assert!(
matches!(up.as_slice(), [Action::Preview(c, v), Action::Commit] if c == "object.transform" && v["objects"] == false && v["patterns"] == true),
"{up:?}"
);
let mut t = SelectionTool::default();
t.pointer(&cx, &ev(PointerKind::Down, from.0, from.1));
t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, to.0, to.1) });
let up = t.pointer(&cx, &ev(PointerKind::Up, to.0, to.1));
assert!(
matches!(up.as_slice(), [Action::Preview(_, v), Action::Commit] if v.get("objects").is_none() && v.get("patterns").is_none()),
"{up:?}"
);
}
}
/// Escape during a bounding-box scale or rotation cancels it, and the release after it commits
/// nothing.
#[test]
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more