Merge main into feat/app-bar-search-field

This commit is contained in:
dotCooCoo
2026-11-16 17:38:41 -08:00
155 changed files with 8218 additions and 756 deletions
Generated
+19 -9
View File
@@ -1206,7 +1206,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1239,6 +1239,15 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14"
dependencies = [
"flate2",
"kurbo 0.13.1",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
@@ -1253,7 +1262,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"fax",
"hayro-ccitt",
@@ -2507,7 +2516,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2516,7 +2525,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2534,7 +2543,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2552,12 +2561,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -3357,7 +3366,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3466,7 +3475,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6856,6 +6865,7 @@ dependencies = [
"craft-eps",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
"craft-pdf",
"craft-ps",
"craft-stream-codecs",
"encoding_rs",
"fax",
+10 -9
View File
@@ -11,7 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", default-features = false, features = ["interpret", "write"] }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] }
@@ -38,8 +38,9 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a93
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
# internal
@@ -181,13 +182,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+15 -6
View File
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
// are written mirrored about the seam instead.
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
let stop = |s: &crate::GradientStop| {
let at = if mirrored { 1.0 - s.offset } else { s.offset };
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
let stop = |&(t, c, o): &(f32, Color, f32)| {
let at = if mirrored { 1.0 - t } else { t };
format!("{} {}%", css_color(&c, o), at * 100.0)
};
// Stops that repeat or reflect run that many times across the box.
// Stops that repeat or reflect run that many times across the box. CSS mixes
// hex colors evenly in sRGB between two stops
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
// midpoint and the curve of a Perceptual or hue gradient are written as stops
// of their own, each with its color and opacity. A gradient that would need
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
let unrolled = g.gradient.unrolled();
let stops: Vec<String> =
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
unrolled.expanded_stops()
} else {
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
};
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+93
View File
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
}
}
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
/// last the end colors hold.
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
let stops: Vec<([f64; 3], f64, f64)> = list
.split(", ")
.map(|stop| {
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
let at: f64 = at.trim_end_matches('%').parse().unwrap();
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
})
.collect();
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
let a = a0 + (a1 - a0) * w;
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
(c, a)
}
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
/// own, also on a reflected and a mirrored conic swatch.
#[test]
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
for i in 0..64 {
let p = (f64::from(i) + 0.5) / 64.0;
let (css, css_alpha) = css_gradient_at(value, p);
let (color, opacity) = gp.gradient.sample(at(p) as f32);
let want = color.to_rgb();
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
}
};
let ramp = |method| Gradient {
method,
..Gradient::new(
GradientKind::Linear,
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
)
};
for method in crate::GradientMethod::ALL {
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
}
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
let fade = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
],
);
check("fade", GradientPaint::new(fade), &|p| p);
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
let spread = reflected.spreader();
check("reflect", GradientPaint::new(reflected), &spread);
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
check("mirrored conic", conic, &|p| 1.0 - p);
}
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
/// own stops.
#[test]
fn css_gradient_swatches_keep_their_stop_count_bounded() {
let n = 4000;
let stops = (0..n)
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
.collect();
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
}
#[test]
fn holds_counts_the_swatches_each_format_writes() {
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
+15 -1
View File
@@ -752,6 +752,18 @@ impl Document {
/// [`Document::locked_artboards`] leaving out artboard `index`.
pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> {
self.locks_except(index, false)
}
/// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept
/// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too
/// ([`crate::symbols::KeptBoxes::keeping`]).
pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> {
self.locks_except(usize::MAX, true)
}
/// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes.
fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> {
// Art flush with an edge from outside can overlap it by a rounding error, as in
// `art_bounds_on` (#1295).
let rects: Vec<Rect> =
@@ -770,7 +782,9 @@ impl Document {
if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) {
objects(layer, &mut pattern_art);
}
LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() }
// Nothing is measured without a locked artboard.
let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() };
LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() }
}
/// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none.
+20 -10
View File
@@ -451,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
/// outline, as a click there hits it.
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let locks = doc.locked_artboards();
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
selected.iter().rev().copied().find(|&id| {
let Some(chain) = doc.ancestry(id) else { return false };
let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect();
@@ -520,7 +521,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
}
let mut tops = Vec::new();
let mut seen = HashSet::new();
let symbols = doc.symbol_boxes();
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
@@ -535,7 +538,6 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
}
}
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
let locks = doc.locked_artboards();
if !locks.is_empty() {
tops.retain(|id| !doc.node(*id).is_some_and(|n| locks.holds(n)));
}
@@ -625,7 +627,7 @@ pub const MAX_LOCKED_AT: usize = 20;
/// (`opt.scope`) only what is inside the isolated group or object.
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let symbols = doc.kept_symbol_boxes();
let mut out = Vec::new();
if let Some(scope) = opt.scope
&& let Some(isolated) = doc.node(scope)
@@ -725,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
h
};
let locks = doc.locked_artboards();
let locks = doc.locked_artboards_kept();
let on_locked = |id: NodeId| {
editable_only
&& !locks.is_empty()
@@ -733,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
&& doc.node(id).is_some_and(|n| locks.holds(n))
};
let skip = &|id| skip(id) || on_locked(id);
let symbols = doc.symbol_boxes();
// `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
// Isolation mode: only what is inside the isolated container hits. The art around it is
// locked, and clicks pass through it (#833).
if editable_only
@@ -801,6 +804,12 @@ pub fn set_clip_region(f: ClipRegion) {
let _ = CLIP_REGION.set(f);
}
/// What the regions of clipping paths with live effects depend on outside the document: the
/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered.
pub(crate) fn clip_region_inputs() -> (u64, bool) {
(live_inputs(), CLIP_REGION.get().is_some())
}
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
/// then can the registered [`ClipRegion`] find a geometry effect in it.
fn has_effects(clip: &Node) -> bool {
@@ -1620,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
let _walk = ArtWalk::open();
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let symbols = doc.kept_symbol_boxes();
let mut path = vec![];
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
@@ -2042,7 +2051,9 @@ fn previews_off(n: &Node) -> bool {
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let mut out = Vec::new();
let symbols = doc.symbol_boxes();
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
// The objects the marquee may touch ([`Top`]).
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
@@ -2284,7 +2295,6 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}
}
}
let locks = doc.locked_artboards();
for (t, r, outline, edge, drawn) in tops {
if !t.visible || t.locked || locks.holds_id(t.id) {
continue;
+12
View File
@@ -608,6 +608,18 @@ impl Node {
}
}
/// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no
/// node after it is visited, and the break is returned.
pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow<B>) -> std::ops::ControlFlow<B> {
f(self)?;
if let Some(ch) = self.children() {
for c in ch {
c.try_walk(f)?;
}
}
std::ops::ControlFlow::Continue(())
}
/// Count of nodes in this subtree, ruler guides left out.
pub fn count(&self) -> usize {
let mut n = 0;
+28
View File
@@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its
/// children, its later siblings or its ancestors' later siblings.
#[test]
fn try_walk_ends_at_the_break() {
use std::ops::ControlFlow;
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]);
let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]);
let mut all = vec![];
root.walk(&mut |n| all.push(n.id));
let mut seen = vec![];
assert_eq!(
root.try_walk(&mut |n| {
seen.push(n.id);
ControlFlow::<()>::Continue(())
}),
ControlFlow::Continue(())
);
assert_eq!(seen, all, "without a break it visits what walk visits, in the same order");
seen.clear();
let flow = root.try_walk(&mut |n| {
seen.push(n.id);
if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) }
});
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
}
+26
View File
@@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() {
assert_eq!(none, s);
}
#[test]
fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() {
for kept in [false, true] {
let mut s = Selection::default();
for i in 1..=4 {
s.add(NodeId(i));
}
s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)]));
s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)]));
s.key_anchor = Some((NodeId(2), (0, 0)));
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
s.guides = vec![NodeId(10)];
s.key_guide = Some(NodeId(10));
let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] };
let mut one_by_one = s.clone();
for id in ids {
one_by_one.remove(id);
}
let mut all = s.clone();
all.remove_all(ids);
assert_eq!(all, one_by_one);
assert_eq!(all.key_anchor.is_some(), kept);
assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10))));
}
}
#[test]
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
+239 -5
View File
@@ -8,6 +8,7 @@
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::sync::Arc;
use vectorcraft_color::swatch::REGISTRATION;
@@ -340,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
/// and gradient stops (with their link), a dynamic symbol instance's own paints
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
let _ = try_node_colors::<()>(n, &mut |c, s| {
f(c, s);
ControlFlow::Continue(())
});
}
/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one.
pub fn node_has_colors(n: &Node) -> bool {
try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break()
}
/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no
/// paint or node after it is visited.
fn try_node_colors<B>(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow<B>) -> ControlFlow<B> {
n.try_walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?,
Paint::Gradient(g) => {
for s in &g.gradient.stops {
f(&s.color, s.swatch.as_deref())?;
}
}
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
for p in &mesh.points {
f(&p.color, None)?;
}
}
});
ControlFlow::Continue(())
})
}
fn item_paint(it: &AppearanceItem) -> &Paint {
@@ -821,4 +843,216 @@ mod tests {
node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string))));
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
}
});
}
/// Whether [`full_walk`] finds a color in `n`.
fn full_walk_has_colors(n: &Node) -> bool {
let mut found = false;
full_walk(n, &mut |_, _| found = true);
found
}
/// The colors of `n` by [`full_walk`], in order.
fn full_walk_colors(n: &Node) -> Vec<(Color, Option<String>)> {
let mut out = vec![];
full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string))));
out
}
fn square(id: u64, fill: Paint, stroke: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0))
}
fn holder(id: u64, kind: fn(Vec<Arc<Node>>) -> NodeKind, children: Vec<Node>) -> Node {
Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect()))
}
/// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color.
fn color_cases() -> Vec<(&'static str, Node, bool)> {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let gradient = |stops: usize| {
let mut g = vectorcraft_color::Gradient::default();
g.stops.truncate(stops);
Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g)))
};
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
let mut empty_mesh = mesh.clone();
empty_mesh.points.clear();
let text = |fill: Paint| {
let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() };
let mut n =
Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style))));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n
};
let image = |colorize: Option<Paint>| {
let im = crate::ImageObject {
key: "k".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im)));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n.extras_mut().colorize = colorize.map(Box::new);
n
};
let overridden = |fill: Option<Paint>| {
let mut n = square(22, Paint::None, Paint::None);
n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }];
n
};
let masked = {
let mut n = square(23, Paint::None, Paint::None);
n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true)));
n
};
let group = |children| NodeKind::Group { children, clip: false };
let clip = |children| NodeKind::Group { children, clip: true };
let compound = |children| NodeKind::Compound { children, rule: Default::default() };
let blend = |children| NodeKind::Blend { children, spec: Default::default() };
let blank = |id| square(id, Paint::None, Paint::None);
vec![
("no paint", blank(1), false),
("solid fill", square(2, red.clone(), Paint::None), true),
("solid stroke", square(3, Paint::None, red.clone()), true),
("pattern only", square(4, pattern.clone(), pattern.clone()), false),
("gradient without stops", square(5, gradient(0), Paint::None), false),
("gradient with stops", square(6, gradient(2), Paint::None), true),
("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true),
("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false),
("text run fill", text(red.clone()), true),
("text without paint", text(Paint::None), false),
("image colorize", image(Some(red.clone())), true),
("image without colorize", image(None), false),
("image with a pattern colorize", image(Some(pattern.clone())), false),
("symbol override fill", overridden(Some(red.clone())), true),
("symbol override without paint", overridden(None), false),
("color only in the opacity mask", masked, false),
("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true),
("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true),
("group without color", holder(38, group, vec![blank(39), blank(40)]), false),
("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true),
("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true),
("blend", holder(47, blend, vec![blank(48), blank(49)]), false),
(
"nested groups, color deepest",
holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]),
true,
),
]
}
#[test]
fn has_colors_matches_the_full_walk() {
for (label, n, expected) in color_cases() {
let all = full_walk_colors(&n);
assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}");
assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}");
assert_eq!(node_has_colors(&n), expected, "{label}");
let mut listed = vec![];
node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string))));
assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order");
}
}
#[test]
fn has_colors_stops_at_the_first_color() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let mut stops = vectorcraft_color::Gradient::default();
stops.stops.push(stops.stops[0].clone());
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops)));
let mut later = vec![square(2, gradient, red.clone())];
later.extend((3..100).map(|id| square(id, red.clone(), red.clone())));
let n = holder(1, |children| NodeKind::Group { children, clip: false }, later);
let (mut colors, mut nodes) = (0, 0);
let flow = try_node_colors(&n, &mut |_, _| {
colors += 1;
ControlFlow::Break(())
});
assert!(flow.is_break());
assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read");
let flow = n.try_walk(&mut |m| {
nodes += 1;
if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});
assert!(flow.is_break());
assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it");
}
/// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in
/// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn has_colors_timing() {
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
fn clock(start: std::time::Instant) -> u128 {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
}
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let count = 100_000u64;
let group = |colored: &dyn Fn(u64) -> bool| {
let children =
(0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) });
holder(0, |children| NodeKind::Group { children, clip: false }, children.collect())
};
let cases = [
("every path filled", group(&|_| true)),
("only the last path filled", group(&|i| i == count - 1)),
("no path filled", group(&|_| false)),
];
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
// The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms.
let per_call = |f: fn(&Node) -> bool, n: &Node| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(std::hint::black_box(n)));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 30 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
for (label, n) in &cases {
assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}");
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(full_walk_has_colors, n));
new.push(per_call(node_has_colors, n));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, nw) = (old[3], new[3]);
println!(
"{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs",
o.0, o.1, nw.0, nw.1
);
}
}
}
+372 -2
View File
@@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> {
consulted: RefCell<Option<HashSet<String>>>,
}
/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and
/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and
/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]).
/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's
/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else
/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art
/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`.
struct KeptKey {
symbols: Vec<(String, std::sync::Weak<Node>)>,
guides: Option<serde_json::Value>,
inputs: (u64, bool),
}
impl KeptKey {
/// The key of the document's 9-slice guides.
const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE;
fn of(doc: &Document, inputs: (u64, bool)) -> Self {
KeptKey {
symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(),
guides: doc.unknown.get(Self::GUIDES).cloned(),
inputs,
}
}
/// Does this describe `doc`'s symbols as they are now, with inputs `inputs`?
fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool {
self.inputs == inputs
&& self.symbols.len() == doc.symbols.len()
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name)
&& self.guides.as_ref() == doc.unknown.get(Self::GUIDES)
}
fn same(&self, other: &KeptKey) -> bool {
self.inputs == other.inputs
&& self.symbols.len() == other.symbols.len()
&& self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m)
&& self.guides == other.guides
}
}
/// Art boxes, nesting depths and the name index measured by boxes made by
/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols.
struct Kept {
key: KeptKey,
names: Option<Arc<SymbolNames>>,
measured: HashMap<String, Option<ArtBox>>,
depths: HashMap<String, Option<usize>>,
}
/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread:
/// clicks can alternate between two open documents.
const KEPT_SETS: usize = 2;
thread_local! {
/// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first.
static KEPT: RefCell<Vec<Kept>> = const { RefCell::new(Vec::new()) };
}
/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the
/// next ones when dropped.
pub(crate) struct KeptBoxes<'a> {
boxes: SymbolBoxes<'a>,
/// What the measurements depend on, under which they are kept.
key: Option<KeptKey>,
/// Other boxes of the same document whose measurements are kept with these
/// ([`Self::keeping`]).
also: Option<&'a SymbolBoxes<'a>>,
}
impl<'a> std::ops::Deref for KeptBoxes<'a> {
type Target = SymbolBoxes<'a>;
fn deref(&self) -> &SymbolBoxes<'a> {
&self.boxes
}
}
impl<'a> KeptBoxes<'a> {
/// These boxes, which also keep the art boxes and nesting depths `other` has measured when
/// dropped. `other` measures the same document, as the boxes of
/// [`Document::locked_artboards_kept`] do.
pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self {
self.also = Some(other);
self
}
}
impl Drop for KeptBoxes<'_> {
/// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive
/// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice
/// guides are left out: measuring them places art within a budget the boxes share
/// ([`SymbolBoxes::sliced_visual`]).
fn drop(&mut self) {
let Some(key) = self.key.take() else { return };
let b = &self.boxes;
let mut measured = b.measured.take();
let mut depths = b.depths.take();
if let Some(other) = self.also {
for (name, a) in other.measured.borrow().iter() {
measured.entry(name.clone()).or_insert(*a);
}
for (name, d) in other.depths.borrow().iter() {
depths.entry(name.clone()).or_insert(*d);
}
}
measured.retain(|_, a| a.is_none_or(|a| !a.sliced));
let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths };
// Nothing is kept while the thread ends or the list is in use.
let _ = KEPT.try_with(|k| {
if let Ok(mut k) = k.try_borrow_mut() {
if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) {
let other = k.remove(i);
kept.names = kept.names.or(other.names);
for (name, a) in other.measured {
kept.measured.entry(name).or_insert(a);
}
for (name, d) in other.depths {
kept.depths.entry(name).or_insert(d);
}
}
k.insert(0, kept);
k.truncate(KEPT_SETS);
}
});
}
}
impl Document {
/// [`SymbolBoxes`] for this document's symbols, none measured yet.
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
@@ -131,6 +259,56 @@ impl Document {
}
}
/// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured
/// by the last such boxes made on this thread for the same symbols, and keep theirs for the next
/// ones when dropped. The measurements are made again when a symbol's name or art, the symbols'
/// 9-slice guides, or the inputs of the live geometry effects of clipping paths have
/// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept.
pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> {
self.kept_boxes(false)
}
/// [`Self::symbol_boxes`] that start with a copy of the measurements
/// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves.
pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> {
let mut kept = self.kept_boxes(true);
kept.key = None;
std::mem::replace(&mut kept.boxes, self.symbol_boxes())
}
/// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them.
fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> {
let mut boxes = self.symbol_boxes();
let inputs = crate::hit::clip_region_inputs();
let found = KEPT
.try_with(|k| {
let mut k = k.try_borrow_mut().ok()?;
let i = k.iter().position(|e| e.key.is_of(self, inputs))?;
if copy {
let e = k.get(i)?;
let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs };
Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() })
} else {
Some(k.remove(i))
}
})
.ok()
.flatten();
let key = match found {
Some(e) => {
if let Some(names) = e.names {
// The boxes were just made, so no index is set yet.
let _ = boxes.names.set(names);
}
*boxes.measured.get_mut() = e.measured;
*boxes.depths.get_mut() = e.depths;
e.key
}
None => KeptKey::of(self, inputs),
};
KeptBoxes { boxes, key: Some(key), also: None }
}
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
@@ -148,6 +326,8 @@ impl Document {
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
/// How many art boxes [`SymbolBoxes::art`] has measured on this thread.
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
}
impl<'a> SymbolBoxes<'a> {
@@ -218,6 +398,8 @@ impl<'a> SymbolBoxes<'a> {
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
let cached = self.measured.borrow().get(name).copied();
let b = cached.unwrap_or_else(|| {
#[cfg(test)]
ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1));
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
@@ -584,10 +766,10 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
use vectorcraft_geom::shapes;
use vectorcraft_geom::{Point, shapes};
use super::*;
use crate::{Appearance, Symbol};
use crate::{Appearance, NodeId, Symbol};
/// A rectangle filled black, with a `stroke` pt black stroke (0: none).
fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node {
@@ -911,4 +1093,192 @@ mod tests {
assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0);
assert_eq!(runs.get(), MAX_REACHES + 2);
}
/// How many art boxes `f` measures on this thread.
fn art_boxes_measured(f: impl FnOnce()) -> usize {
let before = ART_BOXES_MEASURED.with(Cell::get);
f();
ART_BOXES_MEASURED.with(Cell::get) - before
}
/// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an
/// instance of each at (40 i + 20, 20).
fn ten_symbols() -> Document {
let mut d = Document::new(400.0, 100.0);
let layer = d.layers.first().map(|l| l.id);
for i in 0..10 {
let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0);
symbol(&mut d, &format!("S {i}"), vec![square]);
let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0)));
d.insert(layer, usize::MAX, at).unwrap();
}
d
}
#[test]
fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit");
assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1);
}
assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10);
};
let first = art_boxes_measured(clicks);
assert_eq!(first, 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
}
#[test]
fn hit_tests_measure_a_symbol_again_after_it_changes() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
// Past the square of "S 1" at (60, 20).
let past = Point::new(71.0, 20.0);
assert!(hit::hit_test(&d, past, HitOptions::default()).is_none());
// The art grows 3 times in place: no other copy of it is held in the document.
Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false);
let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit"));
assert!(measured > 0);
// New art for "S 2", 40 wide.
let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0);
d.symbols[2].art = Arc::new(wide);
assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit");
// "S 3" renamed: its instance now shows the 20 × 20 square.
d.symbols[3].name = "Renamed".into();
assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit");
assert_eq!(hits(&d), fresh_hits(&d));
}
/// What clicks on a grid over `d` hit, and what a marquee over it selects.
fn hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
use crate::hit::{self, HitOptions};
let mut clicks = Vec::new();
for y in (0..400).step_by(5) {
for x in (0..400).step_by(5) {
let p = Point::new(f64::from(x), f64::from(y));
clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry));
}
}
(clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false))
}
/// [`hits`] with no measurements kept from earlier hit tests.
fn fresh_hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
KEPT.with_borrow_mut(Vec::clear);
hits(d)
}
/// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is
/// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without
/// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150.
fn sliced_holder(guides: bool) -> Document {
let mut d = Document::new(400.0, 400.0);
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
symbol(&mut d, "Bar", vec![bar]);
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
symbol(&mut d, "Panel", vec![frame, inner]);
if guides {
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
}
let panel = instance(&mut d, "Panel", Affine::IDENTITY);
symbol(&mut d, "Holder", vec![panel]);
let layer = d.layers.first().map(|l| l.id);
let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0));
d.insert(layer, usize::MAX, holder).unwrap();
d
}
#[test]
fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() {
use crate::hit::{self, HitOptions};
let mut d = sliced_holder(false);
// Left of the frame, where only the bar placed through the guides draws.
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_none());
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit");
assert_eq!(hits(&d), fresh_hits(&d));
let before = hits(&d);
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] }));
let after = hits(&d);
assert_ne!(after, before, "the size moves the guides");
assert_eq!(after, fresh_hits(&d));
}
#[test]
fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() {
use crate::hit::{self, HitOptions};
let d = sliced_holder(true);
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some());
// The holder's art holds an instance of a symbol with guides; the panel's art holds none.
KEPT.with_borrow(|k| {
let measured = &k[0].measured;
assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys());
});
let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()));
assert!(again > 0, "the holder's art box measured again");
}
#[test]
fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() {
let d = ten_symbols();
let key = KeptKey::of(&d, (0, false));
assert!(key.is_of(&d, (0, false)));
assert!(!key.is_of(&d, (1, false)), "live inputs changed");
assert!(!key.is_of(&d, (0, true)), "a clip region registered");
}
#[test]
fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
d.artboards[0].locked = true;
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard");
assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty());
}
};
assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
// A marquee passes over the objects on a locked artboard without measuring them itself: only
// its locks measure their art.
let mut d = ten_symbols();
d.artboards[0].locked = true;
let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty());
assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again");
}
#[test]
fn hit_tests_hold_no_symbol_art() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default()));
assert!(KEPT.with_borrow(|k| !k.is_empty()));
assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art");
}
#[test]
fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() {
use crate::hit::{self, HitOptions};
let docs = [ten_symbols(), ten_symbols(), ten_symbols()];
let p = Point::new(20.0, 20.0);
for d in &docs {
drop(hit::hit_test(d, p, HitOptions::default()));
}
assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS);
// The last two are kept, the first is measured again.
let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default()))));
assert_eq!(kept, 0);
let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default())));
assert!(first > 0);
}
}
+8 -2
View File
@@ -720,7 +720,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
/// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live
/// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
/// them. `None` when no type stays type.
/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster
/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the
/// canvas draws it ([`evaluate_container`]).
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
if !clipping {
@@ -756,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
}
}
}
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) {
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|| has_pathfinder(n)
|| has_own_paint(n)
|| crate::reshape::copied_container_raster_at(n).is_some()
{
return None;
}
let fx = geometry_effects(n);
+62 -1
View File
@@ -832,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`.
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let pathfinder = has_pathfinder(n);
let fx = crate::reshape::geometry_effects(n);
let paint = has_own_paint(n);
@@ -901,6 +905,63 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
Some(m)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let mut m = n.clone();
let mut guides = vec![];
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
let mut source = m.clone();
source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec();
// With no geometry effect before the Transform effect, `evaluate_container` leaves the members'
// own effects live (it only paints the group's own fills and strokes): the members are drawn
// first, so their effects apply before the copies are made.
if crate::reshape::geometry_effects(&source).is_empty() {
source = crate::reshape::outlined_members(doc, &source);
// The members' raster effects follow the group's own Transform effects as well.
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut source);
}
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
let mut p = source.clone();
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
p
});
// The piece is one copy: the transparency, opacity mask and guides stay on the art.
piece.name = None;
piece.visible = true;
piece.locked = false;
(piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false);
piece.extras_mut().mask = None;
// The copies are made about the piece's bounds, measured first: a layer leaves its hidden
// members out of them, and a group does not.
let bounds = piece.geometric_bounds();
// A layer's copies are groups in it.
if let NodeKind::Layer { children, clip, .. } = &mut piece.kind {
piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip };
}
let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds);
let copies = art.children().cloned().unwrap_or_default();
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind {
*children = copies;
*clip = false;
}
m.appearance.items.clear();
m.appearance.contents_index = None;
m.appearance.effects = effects;
if let Some(ch) = m.children_mut() {
ch.extend(guides);
}
m
}
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
+61 -23
View File
@@ -1,4 +1,4 @@
//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects.
//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects.
//!
//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path
//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects
@@ -11,12 +11,15 @@
//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or
//! layer whose clipping path has strokes with geometry effects is given as that path's geometry
//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and
//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`],
//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve,
//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with
//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and
//! marquees use, leaves 3D effects unprojected. [`bounds_of`],
//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes
//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
//! with its geometry effects, and the other instances in it are measured without them.
//! with its geometry and 3D effects, and the other instances in it are measured without them.
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
@@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
use crate::group::has_own_paint;
use crate::reshape::{geometry_effects, leaf_geometry};
use crate::{
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
needs_outline, outline_art, paints, reshape,
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve,
has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in,
};
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
/// past it, the other instances in the object are measured without geometry effects.
/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects:
/// past it, the other instances in the object are measured without those effects.
const MAX_INSTANCES: usize = 4096;
/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else
@@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
}
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
/// [`Node::visual_bounds_with`].
/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected,
/// else [`Node::visual_bounds_with`].
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
Drawn::new(symbols).visual_bounds(n)
}
@@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option<Rect> {
}
/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances
/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a
/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a
/// group of its clipping path without strokes and the drawn art of the path's strokes, when they
/// have one. `None` when no geometry effect in `n` changes what it draws.
/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or
/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group
/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's
/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps
/// its own id. `None` when no geometry effect in `n` changes what it draws.
pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
Drawn::new(symbols).drawn_art(n)
Drawn::without_3d(symbols).drawn_art(n)
}
/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol
/// instance in `n` counts when its symbol's art has a geometry effect.
/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a
/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its
/// symbol's art has geometry or 3D effects.
pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool {
Drawn::new(symbols).draws_geometry(n)
}
/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name,
/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]).
/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name,
/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]).
/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]).
struct Drawn<'s, 'd> {
symbols: &'s SymbolBoxes<'d>,
draws: RefCell<HashMap<String, bool>>,
left: Cell<usize>,
three_d: bool,
}
impl<'s, 'd> Drawn<'s, 'd> {
fn new(symbols: &'s SymbolBoxes<'d>) -> Self {
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) }
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true }
}
/// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]).
fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self {
Drawn { three_d: false, ..Self::new(symbols) }
}
/// Whether `n` has a 3D effect of its own that this measurement projects.
fn projects(&self, n: &Node) -> bool {
self.three_d && (has_revolve(n) || has_solid(n))
}
/// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object.
@@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> {
let mut found = false;
n.walk(&mut |c| {
found = found
|| self.projects(c)
|| match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol),
_ => reshapes(c),
@@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> {
d
}
/// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the
/// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that
/// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from
/// those effects in its symbol's art, with the instance's appearance overrides applied.
/// A group or layer with fills or strokes of its own that
/// paint, around members with geometry effects, is evaluated too: its fills and strokes paint
/// the members' geometry before their effects. A blend, envelope or repeat whose objects have
/// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and
/// the objects in its evaluated art keep their geometry effects. `None` when it has none, and
/// for a symbol instance past [`MAX_INSTANCES`].
fn own_art(&self, n: &Node) -> Option<Node> {
let doc = Some(self.symbols.document());
// A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built.
let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n);
if counted {
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
}
if self.three_d
&& let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n))
{
// The builders retain later geometry on the projected group. Measure it after that
// geometry too; item-level effects are handled by the ordinary member traversal.
return Some(self.own_art(&art).unwrap_or(art));
}
let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c)));
let painted = || has_own_paint(n) && inner();
match &n.kind {
@@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> {
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
return None;
}
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
if !counted {
let left = self.left.get().checked_sub(1)?;
self.left.set(left);
}
let art = self.symbols.measure_art(symbol, Arc::clone)?;
// Paint overrides can remove a projected surface or change its stroke outline.
let art =
if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) };
// An instance in perspective is projected by `reshape`.
let doc = Some(self.symbols.document());
reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art)))
+107 -2
View File
@@ -208,6 +208,110 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
(carried && !excluded).then_some(t)
}
/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect
/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of
/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes
/// copies, when a visible raster effect that follows a Transform effect is listed before it and
/// every other visible effect before it is a geometry effect or such a raster effect. `None`
/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a
/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints
/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own.
pub(crate) fn copied_container_raster_at(n: &Node) -> Option<usize> {
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
return None;
}
let effects = &n.appearance.effects;
// Checked first: this runs for every group and layer drawn.
if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
return None;
}
let t = effects.iter().rposition(|e| {
e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0
})?;
let before = effects.get(..t)?;
let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id));
let excluded = n.is_compound_shape()
|| n.extras().shaper.is_some()
|| crate::has_pathfinder(n)
|| n.extras().mask.as_ref().is_some_and(|m| m.linked)
|| crate::has_solid(n)
|| crate::has_revolve(n)
|| crate::has_crop_marks(n)
|| crate::addons::halftone::has_halftone(n)
|| effects.iter().any(|e| painted_plugin(e).is_some())
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
|| n.projection().is_some();
(carried && !excluded).then_some(t)
}
/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`,
/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster
/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding
/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved,
/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale
/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect
/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as
/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies
/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have
/// their raster effects moved, turned, reflected and scaled with each copy in the same way
/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art
/// and the raster effects from `t` on, as they ran.
pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option<Rect>) -> (Node, Vec<Effect>) {
let rest = n.appearance.effects.get(t..).unwrap_or_default();
let own = piece.appearance.effects.clone();
let original = piece.clone();
let mut art = Node::group(n.id, vec![Arc::new(piece)]);
if let (Some(e), Some(bounds)) = (rest.first(), bounds) {
let params = merged_params(&e.id, &e.params);
let (m, copies) = crate::distort::transform_map(bounds, &params, n.id.0);
let max = Budget::EFFECTS.at_least(art_cost(&art));
copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(&params)), max);
if let Some(children) = art.children_mut() {
// The original is last, and each copy above it is mapped once more by `m`.
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
let mut a = Affine::IDENTITY;
for (k, c) in children.iter_mut().rev().enumerate() {
// Each copy is the piece in a group of its own: the piece takes its place.
if let Some([one]) = c.children().map(Vec::as_slice) {
*c = one.clone();
}
if k > 0 {
a *= step;
// Scale Strokes & Effects scaled the copy's own effects with it: they follow
// its map from their values on the original instead.
let copy = Arc::make_mut(c);
copy.appearance.effects = own.clone();
crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY);
follow_carried(copy, &original, n.id, a);
}
}
}
}
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc);
let mut ran = n.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
}
let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
(art, effects)
}
/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a
/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster
/// effects of the matching members of `original`, the piece `copy` was made from, made to follow
/// `a` ([`crate::raster::follow_contents`]).
fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) {
let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return };
for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) {
let c = Arc::make_mut(c);
c.appearance.effects = w.appearance.effects.clone();
crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY);
follow_carried(c, w, id, a);
}
}
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
/// else `None`.
fn painted_plugin(e: &Effect) -> Option<&str> {
@@ -1172,9 +1276,10 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster
/// effects listed before it ([`copied_raster_at`]).
/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do
/// ([`copied_container_raster_at`]).
pub fn outer_effects(n: &Node) -> &[Effect] {
match copied_raster_at(n) {
match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) {
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
None => &n.appearance.effects,
}
+199 -1
View File
@@ -781,7 +781,7 @@ fn a_groups_transform_moves_its_members_shadows() {
}
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
/// they are, as it leaves the shadows listed before it in its own effects.
/// they are.
#[test]
fn a_groups_copying_transform_leaves_its_members_shadows() {
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
@@ -792,6 +792,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() {
}
}
/// A layer of `members` with `effects` of its own.
fn layer(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = l.children_mut() {
*ch = members.into_iter().map(std::sync::Arc::new).collect();
}
l.appearance.effects = effects;
l
}
/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order.
fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> {
art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect()
}
fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y))
}
/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed
/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and
/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and
/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not
/// scaled a second time. A layer's art stays a layer.
#[test]
fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() {
let cases = [
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]),
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]),
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
];
for (params, want) in cases {
let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect();
for container in ["group", "layer"] {
let members = vec![square(101, vec![]), square(102, vec![])];
let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())];
let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) };
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}");
let art = crate::evaluate_container(None, &n).unwrap();
assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}");
assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects);
let drawn = copy_shadows(&art);
assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}");
assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none");
for c in art.children().into_iter().flatten() {
assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}");
}
let b = baked(n);
assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b));
}
}
}
/// A group's copying Transform effect leaves its members' own shadows on each copy as they are,
/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip
/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has
/// Transform Objects off, leaves the group's shadows on the group.
#[test]
fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() {
let g = group(
110,
vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])],
vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)],
);
assert_eq!(crate::outer_effects(&g).len(), 2);
let art = crate::evaluate_container(None, &g).unwrap();
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art));
let mut clip = square(121, vec![]);
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]);
if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
let art = crate::evaluate_container(None, &g).unwrap();
assert!(!art.clips());
assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}");
assert!(close_all(&copy_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art));
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
assert_eq!(crate::outer_effects(&g).len(), 2, "{params}");
let art = crate::evaluate_container(None, &g).unwrap();
assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow");
}
}
/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without
/// one, and no shadow is left without its copy.
#[test]
fn a_groups_copies_past_the_budget_each_keep_their_shadow() {
let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]);
let art = crate::evaluate_container(None, &g).unwrap();
let paths = paths_in(&art);
assert!(paths > 1 && paths < 1001, "{paths}");
assert_eq!(shadows_in(&art).len(), paths);
}
/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow.
#[test]
fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() {
let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None });
let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]);
let art = crate::evaluate_container(None, &l).unwrap();
let ch = art.children().unwrap();
assert_eq!(ch.len(), 4, "three copies, then the guide");
assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1);
assert_eq!(shadows_in(&art).len(), 3);
}
/// The bounds of every node with `id` under `art`, in order.
fn bounds_of(art: &Node, id: u64) -> Vec<Rect> {
let mut out = vec![];
art.walk(&mut |m| {
if m.id == NodeId(id)
&& let Some(b) = m.geometric_bounds()
{
out.push(b);
}
});
out
}
fn rects_near(a: &[Rect], b: &[Rect]) -> bool {
let near = |p: f64, q: f64| (p - q).abs() < 1e-6;
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1))
}
/// A group with a fill of its own and only a shadow before its copying Transform effect applies
/// its members' own effects before it copies them, as a group without a fill does: a member's own
/// move is turned with each copy.
#[test]
fn a_painted_groups_copies_take_their_members_own_effects_first() {
let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])];
let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))];
let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap();
let mut painted = group(170, members(), effects());
*painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
painted.appearance.effects = effects();
let art = crate::evaluate_container(None, &painted).unwrap();
let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171));
assert!(!want.is_empty());
assert!(rects_near(&got, &want), "{got:?} {want:?}");
}
/// A layer's copies are made about the bounds of its visible members, as the layer measures them:
/// a hidden member does not move the center that a reflected copy turns about.
#[test]
fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() {
let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]);
hidden.visible = false;
let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]);
let art = crate::evaluate_container(None, &l).unwrap();
let got = bounds_of(&art, 181);
assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}");
}
/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each
/// copy of a later one, drawn and baked.
#[test]
fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() {
let g = || {
group(
190,
vec![square(191, vec![])],
vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))],
)
};
let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)];
let art = crate::evaluate_container(None, &g()).unwrap();
assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art));
let b = baked(g());
assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b));
}
/// A group holding type whose Transform effect only moves its copies, baked for export, gives each
/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type
/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs
/// and the test is skipped.
#[test]
fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
use vectorcraft_doc::text::{CharStyle, TextObject};
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
let b = baked(g);
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
}
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
+92 -2
View File
@@ -5,15 +5,16 @@ use super::{
// ---------- brushes ----------
/// Brushable nodes (paths and compound paths) under `ids`.
/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached.
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
let mut seen = std::collections::HashSet::new();
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
if own && !in_compound && seen.insert(c.id) {
out.push(c.id);
}
});
@@ -748,3 +749,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
let checked = crate::schemas::check(spec, p, s.replaying())?;
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::Appearance;
use vectorcraft_geom::PathData;
/// The collector with a linear search of its output, kept to compare results with.
fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut out = vec![];
for id in ids {
let Some(n) = d.node(*id) else { continue };
n.walk(&mut |c| {
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
if own && !in_compound && !out.contains(&c.id) {
out.push(c.id);
}
});
}
out
}
fn path(d: &mut Document) -> Node {
Node::path(d.alloc_id(), PathData::default(), Appearance::default())
}
fn compound(d: &mut Document, children: Vec<Node>) -> Node {
Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() })
}
fn add(d: &mut Document, node: Node) -> NodeId {
let layer = d.layers.first().map(|l| l.id);
d.insert(layer, usize::MAX, node).unwrap()
}
#[test]
fn brush_targets_list_each_target_once_in_first_reached_order() {
let mut d = Document::new(400.0, 300.0);
let a = path(&mut d);
let a = add(&mut d, a);
let mut guide = path(&mut d);
if let NodeKind::Path { guide: g, .. } = &mut guide.kind {
*g = true;
}
let guide = add(&mut d, guide);
let mut clip = path(&mut d);
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let clip = add(&mut d, clip);
// A group holding a path and a compound path of two members.
let p1 = path(&mut d);
let p1_id = p1.id;
let (m1, m2) = (path(&mut d), path(&mut d));
let m1_id = m1.id;
let cp1 = compound(&mut d, vec![m1, m2]);
let cp1_id = cp1.id;
let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]);
let group = add(&mut d, group);
// A compound path holding a compound path.
let m3 = path(&mut d);
let cp3 = compound(&mut d, vec![m3]);
let cp3_id = cp3.id;
let cp2 = compound(&mut d, vec![cp3]);
let cp2 = add(&mut d, cp2);
let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)];
let got = brush_targets(&d, &ids);
assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out");
assert_eq!(got, listed_targets(&d, &ids));
assert!(brush_targets(&d, &[]).is_empty());
// Many paths in groups, each group listed with some of its members.
let mut ids = vec![];
for _ in 0..50 {
let members: Vec<Node> = (0..20).map(|_| path(&mut d)).collect();
let member_ids: Vec<NodeId> = members.iter().map(|m| m.id).collect();
let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect());
let g = add(&mut d, g);
ids.push(member_ids[7]);
ids.push(g);
ids.push(member_ids[3]);
}
let got = brush_targets(&d, &ids);
assert_eq!(got.len(), 50 * 20);
assert_eq!(got, listed_targets(&d, &ids));
}
}
+1 -3
View File
@@ -1189,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
if is_explicit {
for id in &ids {
sel.remove(*id);
}
sel.remove_all(ids.iter().copied());
sel.prune(d);
} else {
sel.clear();
+83 -10
View File
@@ -1238,6 +1238,69 @@ fn expand_node_except(
}
}
/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects
/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]):
/// the copies become groups of their own with those effects, and they and what they hold get ids
/// of their own, so they expand as its members do; the raster effects after the Transform effect
/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect
/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does,
/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of
/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there.
/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when
/// such a copy still holds a random Transform effect after the raster budget left part of it as
/// it is: its new ids would give that effect another seed.
fn copies_carrying_raster(
d: &mut Document,
n: &mut Node,
(brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]),
kept: &mut Vec<NodeId>,
members: &mut std::collections::HashMap<NodeId, Vec<Listed>>,
(out, listed): (&mut Vec<Listed>, &mut bool),
raster: &mut RasterBudget,
) -> std::result::Result<bool, OverBudget> {
if !carries_copies(n) {
return Ok(false);
}
let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) };
let mut seen = std::collections::HashSet::from([n.id]);
for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
let c = Arc::make_mut(c);
let left = raster.left;
let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster));
if expanded.is_some() && raster.left > left && has_seeded(c) {
return Err(OverBudget);
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default());
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
if let Some(expanded) = expanded {
members.insert(c.id, expanded);
}
}
if !*listed {
out.push((n.id, 0));
*listed = true;
}
*n = m;
Ok(true)
}
/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed
/// before it ([`copies_carrying_raster`])?
fn carries_copies(n: &Node) -> bool {
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
}
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
@@ -1267,10 +1330,13 @@ fn expanded_node(
}
_ => None,
};
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
// is: the recolored copies the adjustment adds then go again.
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
// The embedded images before the adjustment and the expansions of the copies
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
// recolored copies and the images those add then go again.
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
// What the raster budget had left before those expansions: it gets back what they took.
let budget_before = (raster.images, raster.pixels);
if effects::has_adjustment(&n)
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
{
@@ -1316,23 +1382,30 @@ fn expanded_node(
}
return Some(m);
}
// New ids of the copies of objects `skip` lists among the members.
let mut kept = vec![];
// Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id,
// with what their expansion lists.
let mut members = std::collections::HashMap::new();
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
// Raster effects whose image would go past the budget stay: so does the object, with what is
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
let Ok(image) = raster_image(d, &n, raster) else {
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
// so does a group or layer whose copies keep a random Transform effect the budget left.
let Ok(image) = copies.and_then(|copied| {
changed |= copied;
raster_image(d, &n, raster)
}) else {
out.truncate(listed_before);
if let Some(keys) = images_before {
d.images.retain(|k, _| keys.contains(k));
}
(raster.images, raster.pixels) = budget_before;
return None;
};
let mut v = n.clone();
rasterfx::strip_raster(&mut v, false);
let mut stroke_art =
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1344,7 +1417,7 @@ fn expanded_node(
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
+39
View File
@@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() {
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
}
/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a
/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it
/// is when the raster budget has no image left for a copy's shadow, with none left or with one for
/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as
/// before, and the document holds no image the first copy's expansion made, nor the budget its
/// charge.
#[test]
fn copies_the_raster_budget_leaves_keep_their_random_moves() {
let (mut s, id) = session_with_rect();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
let random = json!({"moveH": 40, "moveV": 40, "random": true});
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
let draw = |d: &vectorcraft_doc::Document| {
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
for images in [0, 1] {
let mut d = s.doc().unwrap().doc.as_ref().clone();
let before = d.node(g).cloned().unwrap();
assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow");
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
let mut out = vec![];
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
assert!(budget.left > 0, "{images}: a copy's shadow is left");
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
assert!(draw(&d) == drawn, "{images}: the group draws as before");
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
}
}
File diff suppressed because one or more lines are too long
+17 -9
View File
@@ -286,16 +286,24 @@ fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility
/// is read, its first note saying why: `None` when pages are picked, layers or the editing data
/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec<String>)> {
/// is read, its first note saying why. Else `e`: as it is when pages are picked, layers or the
/// editing data are off, or the file has no editing data, and followed by why when the file has
/// editing data that can't be read. Its type is outlines when `opts` asks.
fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<(Document, Vec<String>)> {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return None;
return Err(e);
}
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
match read {
Ok(Some((doc, warnings))) => {
let notes =
std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Ok(outlined_if_asked(doc, notes, opts))
}
Ok(None) => Err(e),
Err(why) => Err(err(format!("{e}; its editing data couldn't be read either ({why})"))),
}
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Some(outlined_if_asked(doc, notes, opts))
}
/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the
@@ -497,7 +505,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
.inspect(|_| editing_data = true),
// A PDF part that can't be read (a stream the import refuses): the editing copy
// alone where it reads, else the error.
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
Err(e) => without_pdf_part(bytes, opts, e).inspect(|_| editing_data = true),
}
})?;
// The File Info of a file read from its pages or its editing copy.
+63 -18
View File
@@ -209,6 +209,8 @@ struct Row {
options: Value,
/// What makes two rows the same file: format, size, suffix and options.
key: String,
/// The row or the format's settings set `bleed` (a PDF row's own bleed, zero included).
bleed_given: bool,
}
impl Row {
@@ -248,12 +250,19 @@ impl Row {
}
// A file per artboard is for viewing: it doesn't carry the whole document to edit.
options.entry("preserveEditing").or_insert(json!(false));
let bleed_given = options.get("bleed").is_some_and(|b| !b.is_null());
let options = Value::Object(options);
// A PDF preset (built-in or saved) becomes its settings.
let options = if format.id == "pdf" { super::pdf::expand_preset(s, C, &options)?.into_owned() } else { options };
// Two rows that would write the same bytes under the same name are one file.
let key = format!("{}|{}|{suffix}|{options}", format.id, size.label());
Ok(Self { format, size, suffix, folder, options, key })
let mut row = Self { format, size, suffix, folder, options, key: String::new(), bleed_given };
row.key = row.file_key();
Ok(row)
}
/// What makes two rows the same file: two rows that would write the same bytes under the same
/// name are one file.
fn file_key(&self) -> String {
format!("{}|{}|{}|{}", self.format.id, self.size.label(), self.suffix, self.options)
}
/// Formats that hold a whole document to edit (native, Illustrator, EPS): written from a
@@ -525,6 +534,8 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
if let Some(m) = r.options.as_object_mut() {
m.entry("antiAlias").or_insert_with(|| aa.clone());
}
// Two rows whose options are now the same are one file.
r.key = r.file_key();
}
}
Ok(rows)
@@ -1137,17 +1148,22 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
let doc = s.doc()?.doc.clone();
let original = s.doc()?.doc.clone();
// Include Bleed: each artboard grown by the document's bleed.
let doc = if o.include_bleed && doc.setup.has_bleed() {
let mut d = (*doc).clone();
let grown = o.include_bleed && original.setup.has_bleed();
let doc = if grown {
let mut d = (*original).clone();
for a in &mut d.artboards {
a.rect = doc.setup.bleed_rect(a.rect);
a.rect = original.setup.bleed_rect(a.rect);
}
Arc::new(d)
} else {
doc
original.clone()
};
// A PDF page of an artboard keeps the artboard as its TrimBox and puts its row's bleed around
// it once: it is written from the document with the artboards as they are. Assets, layers and
// a selection are written on a page of their own bounds, which Include Bleed doesn't grow.
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Before the folder is made or any row is written, with the artboards each file holds.
@@ -1164,8 +1180,26 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
// Appearance of Black › Printing / Exporting for RGB raster rows.
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
let rows = rows
.into_iter()
.map(|mut r| {
// Include Bleed: a PDF row that sets no bleed of its own, and whose preset gives none,
// puts the document's bleed around the artboard, and is the same file as a row that
// asks for the document's bleed. A saved preset's bleed values stay, as they do in
// that row.
if ungrown.is_some() && r.format.id == "pdf" && !r.bleed_given && !pdf_bleeds(&r.options) {
match r.options.get_mut("bleed").and_then(Value::as_object_mut) {
Some(b) => {
b.insert("useDocument".into(), json!(true));
}
None => r.options["bleed"] = json!({ "useDocument": true }),
}
r.key = r.file_key();
}
Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }
})
.collect();
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None, ungrown };
match &mut s.screens_hand_off {
Some(slot) => {
*slot = Some(export);
@@ -1175,6 +1209,14 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
}
}
/// Do the PDF `options` (a built-in preset's settings under them) give the pages a bleed: the
/// document's, or a value above 0 on some side? Options the PDF encoder refuses count as giving
/// one, so they are left as they are for the encoder to refuse.
fn pdf_bleeds(options: &Value) -> bool {
super::pdf::settings(C, options)
.map_or(true, |s| s.bleed.use_document || [s.bleed.top, s.bleed.bottom, s.bleed.left, s.bleed.right].iter().any(|b| *b > 0.0))
}
/// An export as `document.exportForScreens` and `assets.export` take it from the session: the
/// params, the format rows, the naming, and each item with the document it writes
/// ([`Session::prepare_screen_export`]). [`ScreenExport::write`] encodes and writes its files
@@ -1192,6 +1234,9 @@ pub struct ScreenExport {
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
hidden: Option<(String, String)>,
/// Include Bleed with artboards: the document with the artboards as they are, which PDF rows
/// write (the items hold the artboards grown by the bleed).
ungrown: Option<Arc<Document>>,
}
impl Session {
@@ -1252,7 +1297,7 @@ impl ScreenExport {
/// [`ScreenExport::write`].
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let ScreenExport { o, rows, naming, items, unused, .. } = export;
let ScreenExport { o, rows, naming, items, unused, ungrown, .. } = export;
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
if let Some(dir) = folder {
create_dir(dir)?;
@@ -1263,13 +1308,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
for text in unused {
add_note(&mut notes, Note::setting(text));
}
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
// The document a PDF row writes: with Include Bleed, the artboards as they are.
let pdf_doc = ungrown.as_deref();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
for n in given {
add_note(&mut notes, n);
}
Ok(bytes)
@@ -1306,12 +1350,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
let bytes = if let Some(boards) = single {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
write(&item.doc, "pdf", &options)?
write(pdf_doc.unwrap_or(&item.doc), "pdf", &options)?
} else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
// One page per artboard.
let mut options = r.options.clone();
options["range"] = json!("all");
write(all, "pdf", &options)?
write(pdf_doc.unwrap_or(all), "pdf", &options)?
} else if r.whole_document() && item.artboard.is_some() {
let b = item.artboard.unwrap_or(0);
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
@@ -1334,7 +1378,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
}
write(&d, r.format.id, &options)?
} else {
write(&item.doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
let doc = if r.format.id == "pdf" { pdf_doc.unwrap_or(&item.doc) } else { &item.doc };
write(doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
};
out.put(folder, o.zip, name, bytes, writer)?;
files += 1;
+17 -2
View File
@@ -799,7 +799,7 @@ fn unread_pdf_part(e: &str) -> String {
/// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from
/// its editing data, with a first note saying why. Pages picked, layers off or the editing data
/// off keep the error, and so does editing data that can't be read.
/// off keep the error. Editing data that can't be read keeps it too, followed by why.
#[test]
fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
let mut s = Session::new();
@@ -817,10 +817,25 @@ fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() {
}
for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) {
let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}");
let both = format!("{plain}; its editing data couldn't be read either (its zlib compression is damaged)");
assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), both, "{name}");
for p in [json!({"pages": "1"}), json!({"layers": false})] {
assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), plain, "{name}: {p}");
}
}
}
/// #4366: editing data stored in a form the reader doesn't take, beside a PDF part that can't be
/// read, is named in the error.
#[test]
fn the_error_says_why_the_editing_data_couldnt_be_read() {
let mut s = Session::new();
let file = ai::ai_with_private_streams(&compressed(&ai::sample_data()), ai::page_pdf(), REFUSED_CONTENT, "/Filter /Bogus ");
let plain = open(&mut s, "art.ai", &file, json!({"editingData": false})).unwrap_err().to_string();
let e = open(&mut s, "art.ai", &file, json!({})).unwrap_err().to_string();
assert_eq!(e, format!("{plain}; its editing data couldn't be read either (it is stored in a form that isn't read)"));
}
/// A file saved in units of 10 points (`/UserUnit 10`, as in
/// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens
/// from its editing data at its size in points.
+94 -1
View File
@@ -594,7 +594,8 @@ fn include_bleed_grows_each_artboard() {
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
}
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the
/// bleed out, unless the row sets a bleed of 0 itself.
#[test]
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let mut s = session(1);
@@ -603,11 +604,103 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
assert!(warned(&export(&mut s, json!({"formats": row}))));
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
let zero = json!([{"format": "pdf", "standard": "pdfX4", "bleed": {"top": 0, "bottom": 0, "left": 0, "right": 0}}]);
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": zero}))), "the row's own bleed of 0 leaves the bleed out");
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
}
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
let text = String::from_utf8_lossy(pdf);
text.match_indices(key)
.map(|(at, _)| {
let mut words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']')).filter(|w| !w.is_empty());
std::array::from_fn(|_| words.next().and_then(|w| w.parse().ok()).unwrap_or(f64::NAN))
})
.collect()
}
/// A page's MediaBox, BleedBox and TrimBox sizes `(width, height)` in points, and the trim's
/// distance from the bleed box's left and bottom edges.
type PageSizes = ((f64, f64), (f64, f64), (f64, f64), (f64, f64));
/// [`PageSizes`] of each page of `pdf`.
fn page_sizes(pdf: &[u8]) -> Vec<PageSizes> {
let size = |b: &[f64; 4]| (b[2] - b[0], b[3] - b[1]);
let (media, bleed, trim) = (raw_boxes(pdf, "/MediaBox"), raw_boxes(pdf, "/BleedBox"), raw_boxes(pdf, "/TrimBox"));
assert!(!trim.is_empty() && media.len() == trim.len() && bleed.len() == trim.len(), "a MediaBox, BleedBox and TrimBox per page");
(0..trim.len()).map(|i| (size(&media[i]), size(&bleed[i]), size(&trim[i]), (trim[i][0] - bleed[i][0], trim[i][1] - bleed[i][1]))).collect()
}
/// With Include Bleed, a PDF page keeps the artboard as its TrimBox and puts the bleed around it
/// once (PDF 32000-1:2008, 14.11.2: the trim box is the finished page, the bleed box holds it): the
/// document's bleed when the row asks for it or sets none, else the row's own values.
#[test]
fn include_bleed_pdf_pages_trim_at_the_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
s.execute("document.setup", &json!({"bleed": 9})).unwrap();
let pages = |s: &mut Session, p: Value| -> Vec<PageSizes> {
let r = export(s, p);
files(&r).iter().filter(|(n, _)| n.ends_with(".pdf")).flat_map(|(_, b)| page_sizes(b)).collect()
};
let one = |media: f64, bleed: f64, trim: f64| ((media, media), (bleed, bleed), (trim, trim), ((bleed - trim) / 2.0, (bleed - trim) / 2.0));
let document = json!({"format": "pdf", "bleed": {"useDocument": true}});
let sides = |b: f64| json!({"top": b, "bottom": b, "left": b, "right": b});
for (p, want) in [
(json!({"includeBleed": true, "artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "preset": "High Quality Print"}]}), one(118.0, 118.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(3.0)}]}), one(106.0, 106.0, 100.0)),
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(0.0)}]}), one(100.0, 100.0, 100.0)),
(json!({"artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
(json!({"artboard": 0, "formats": [{"format": "pdf"}]}), one(100.0, 100.0, 100.0)),
] {
assert_eq!(pages(&mut s, p.clone()), [want], "{p}");
}
// Every page of a single file and of the Full Document, each artboard its own trim.
for p in [
json!({"includeBleed": true, "pdfs": "single", "formats": [document]}),
json!({"includeBleed": true, "fullDocument": true, "formats": [document]}),
] {
assert_eq!(pages(&mut s, p.clone()), [one(118.0, 118.0, 100.0); 2], "{p}");
}
// A row with printer's marks: the sheet grows past the bleed box for them, around the same trim.
let marked = pages(
&mut s,
json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": {"useDocument": true}, "marks": {"trim": true}}]}),
);
let [(media, bleed, trim, at)] = marked[..] else { panic!("one page: {marked:?}") };
assert_eq!((bleed, trim, at), ((118.0, 118.0), (100.0, 100.0), (9.0, 9.0)));
assert!(media.0 > 118.0 && media.1 > 118.0, "{media:?}");
// A row that sets no bleed writes the same file as one that asks for the document's: one file.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// So does it with a top-level anti-aliasing mode, which both rows take.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "antiAlias": "art", "formats": [{"format": "pdf"}, document]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
// And with a saved PDF preset, which writes out every bleed value for both rows.
s.execute("pdf.preset.save", &json!({"name": "Saved Default"})).unwrap();
let saved = |bleed: Option<Value>| {
let mut row = json!({"format": "pdf", "preset": "Saved Default"});
if let Some(b) = bleed {
row["bleed"] = b;
}
row
};
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None), saved(Some(json!({"useDocument": true})))]}));
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
assert_eq!(pages(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None)]})), [one(118.0, 118.0, 100.0)]);
// A raster row of the same export still holds the bleed in its pixels.
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [document, {"format": "png"}]}));
let png = files(&r).into_iter().find(|(n, _)| n.ends_with(".png")).unwrap().1;
assert_eq!(size(&png), (118, 118));
}
#[test]
fn png_8_rows_write_indexed_colour() {
let mut s = session(1);
+91 -16
View File
@@ -26,7 +26,9 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
use vectorcraft_tools::intertwine::{
Face, drawn_order, face_at, faces_in, faces_of, in_intertwine, is_intertwine, nonempty, painted_areas, refused_member,
};
use super::edit::selected_roots;
use super::pathops::Beside;
@@ -106,17 +108,7 @@ fn refused(d: &Document, n: &Node) -> Option<&'static str> {
if around.iter().filter(|a| **a != n.id).filter_map(|a| d.node(*a)).any(is_intertwine) {
return Some("an object already in an Intertwine group");
}
let mut why = None;
n.walk(&mut |c| {
why = why.or(match &c.kind {
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
NodeKind::Repeat(_) => Some("a Repeat"),
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
NodeKind::Group { .. } if vectorcraft_tools::builder::is_live_paint(c) => Some("a Live Paint group"),
_ => None,
});
});
why
refused_member(n)
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -179,10 +171,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
.flatten()
.map(|c| {
let mut c = (**c).clone();
let mut e = c.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
drop(e);
without_areas(&mut c);
c
})
.collect();
@@ -196,6 +185,92 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
// ---------- members that come and go ----------
/// Why `n` can't go into `parent`, an Intertwine group or a container inside one, if it can't
/// ([`refused_member`]). Other containers take it as they did.
pub(crate) fn refused_in(d: &Document, parent: Option<NodeId>, n: &Node) -> Option<&'static str> {
parent.filter(|p| in_intertwine(d, *p)).and_then(|_| refused_member(n))
}
/// The Intertwine groups that `ids` are members of, each once.
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let mut seen = std::collections::HashSet::new();
ids.iter().filter_map(|i| d.parent_of(*i)).filter(|g| d.node(*g).is_some_and(is_intertwine) && seen.insert(*g)).collect()
}
/// `n` without the areas it is drawn over other members in.
fn without_areas(n: &mut Node) {
if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() {
let mut e = n.extras_mut();
e.intertwine = None;
e.intertwine_tiers = Vec::new();
}
}
/// Whether Intertwine group `g` has nothing of its own that changes how its members are drawn:
/// it is visible and unlocked, with full opacity, normal blending, no appearance and no extras
/// (an opacity mask among them).
fn bare(g: &Node) -> bool {
let plain = Node::new(g.id, NodeKind::Intertwine { children: vec![] });
(g.visible, g.locked, g.opacity, g.blend, g.isolate, g.knockout, g.knockout_shape)
== (plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape)
&& g.appearance == plain.appearance
&& *g.extras() == *plain.extras()
}
/// After objects moved in the Layers panel: each of `placed` (the objects now in place, each with
/// the container it came from, None for a copy) that is not in the container it came from loses
/// the areas it was drawn over other members in, so it joins an Intertwine group at no tier and
/// leaves one as ordinary art. Then each of `left` (the Intertwine groups objects came from) that
/// has fewer than two members is taken apart: its one member goes in its place without areas, and
/// an empty one is removed. A group with one member and something of its own ([`bare`]) becomes a
/// plain group of that member instead, keeping its id and all it has. The other members keep their
/// areas.
pub(crate) fn settle_members(d: &mut Document, placed: &[(NodeId, Option<NodeId>)], left: &[NodeId]) -> Result<()> {
for (id, from) in placed {
if d.node(*id).is_some_and(|n| n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty())
&& from.is_none_or(|f| d.parent_of(*id) != Some(f))
{
without_areas(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?);
}
}
let lone: Vec<NodeId> =
left.iter().copied().filter(|g| d.node(*g).is_some_and(|n| is_intertwine(n) && n.children().is_none_or(|c| c.len() < 2))).collect();
let (kept, lone): (Vec<NodeId>, Vec<NodeId>) =
lone.into_iter().partition(|g| d.node(*g).is_some_and(|n| n.children().is_some_and(|c| c.len() == 1) && !bare(n)));
for g in &kept {
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
if let NodeKind::Intertwine { children } = &mut n.kind {
let children = std::mem::take(children)
.into_iter()
.map(|c| {
let mut c = (*c).clone();
without_areas(&mut c);
Arc::new(c)
})
.collect();
n.kind = NodeKind::Group { children, clip: false };
}
}
let mut apart = Beside::replacing(d, &lone);
for g in &lone {
let Some(n) = d.node(*g) else { continue };
let members: Vec<Node> = n
.children()
.into_iter()
.flatten()
.map(|c| {
let mut c = (**c).clone();
without_areas(&mut c);
c
})
.collect();
apart.put(d, *g, members)?;
}
apart.finish(d)
}
// ---------- Expand ----------
/// Replace Intertwine group `id` by a plain group of the art it draws
+21 -4
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Rows",
[],
None,
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
has_doc,
move_rows
),
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers), deselecting every selected object left hidden or locked (the key object too)",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
has_doc,
move_node
),
@@ -242,14 +242,15 @@ pub(crate) fn row_roots(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
/// Whether `parent` (None: the top level) can hold `n`: layers go at the top level or in layers,
/// anything else in layers and groups.
/// anything else in layers, groups and Intertwine groups (which also check what the object holds:
/// [`super::intertwine::refused_in`]).
pub(crate) fn accepts(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
match parent {
None => n.is_layer(),
Some(p) => match d.node(p).map(|x| &x.kind) {
Some(NodeKind::Layer { .. }) => true,
// A ruler guide stays directly in a layer or sublayer.
Some(NodeKind::Group { .. }) => !n.is_layer() && !n.is_ruler_guide(),
Some(NodeKind::Group { .. } | NodeKind::Intertwine { .. }) => !n.is_layer() && !n.is_ruler_guide(),
_ => false,
},
}
@@ -791,10 +792,17 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
}
if let Some(what) = nodes.iter().find_map(|n| super::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
if parent.is_some_and(|p| locked_within(d, p)) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
// Intertwine groups it leaves.
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
let left = if copy { vec![] } else { super::intertwine::groups_of(d, &ids) };
let moved = s.edit(label, |d, sel| {
let nodes = if copy {
let mut nodes = vec![];
@@ -829,6 +837,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if copy {
super::typecmd::refresh_bounds_of(d, &out);
}
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
super::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(out)
@@ -848,8 +858,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if !accepts(d, parent, n) {
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
}
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
let from = d.parent_of(id);
let left = super::intertwine::groups_of(d, &[id]);
s.edit("Reorder", |d, sel| {
d.move_node(id, parent, index)?;
super::intertwine::settle_members(d, &[(id, from)], &left)?;
sel.prune(d);
sel.deselect_uneditable(d);
Ok(())
})?;
+6 -1
View File
@@ -80,11 +80,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value>
if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) {
return ok();
}
s.edit("Send to Current Layer", |d, _| {
let placed: Vec<(NodeId, Option<NodeId>)> = ids.iter().map(|i| (*i, st.doc.parent_of(*i))).collect();
let left = crate::cmd::intertwine::groups_of(&st.doc, &ids);
s.edit("Send to Current Layer", |d, sel| {
let moved = d.remove_many(&ids)?;
let ch = d.children_mut(Some(layer))?;
let at = Node::guide_run_start(ch);
ch.splice(at..at, moved);
// Members sent out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
sel.prune(d);
Ok(())
})?;
ok()
+3 -3
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Align",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
has_selection_or_guides,
align
),
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute",
["Window", "Align"],
None,
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
can_distribute,
distribute
),
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Distribute Spacing",
["Window", "Align"],
None,
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
can_distribute,
distribute_spacing
),
+140 -44
View File
@@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_doc::{AnchorRef, Document, LockedArtboards, Node, NodeId, NodeKind, Selection};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
@@ -930,52 +930,145 @@ fn anchors_many(s: &mut Session, p: &Value) -> Result<Value> {
None if bool_or(p, "add", false) => "add",
None => "set",
};
s.select(|d, sel| {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<(usize, usize)> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<(usize, usize)> = refs.intersection(&all).copied().collect();
let next: BTreeSet<(usize, usize)> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
})?;
s.select(|d, sel| select_anchor_items(d, sel, items, mode))?;
ok()
}
/// `select.anchorsMany`'s change to `sel`: each item in order, with the selected objects kept in a
/// [`Members`] map while the items run, so that an item's membership check and change don't go
/// through `sel.objects`.
fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BTreeSet<AnchorRef>)>, mode: &str) {
if mode == "set" {
sel.clear();
}
if items.is_empty() {
return;
}
let mut members = Members::of(sel);
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
if all.is_empty() {
match mode {
"toggle" => members.toggle(sel, id),
"subtract" => members.remove(sel, id),
_ => members.add(sel, id),
}
continue;
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if members.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
members.remove(sel, id);
continue;
}
members.add(sel, id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
members.finish(sel);
}
/// The selected objects of a [`Selection`] while [`select_anchor_items`] changes them. Each
/// selected id maps to the activation that selected it: 0 for the objects selected before, and
/// a new number for each later [`Members::add`] of an unselected id, which `added` lists in order.
/// [`Members::finish`] writes them back to `objects`.
struct Members {
live: std::collections::HashMap<NodeId, usize>,
added: Vec<(NodeId, usize)>,
removed: bool,
}
impl Members {
fn of(sel: &Selection) -> Self {
count_objects_walk();
Self { live: sel.objects.iter().map(|id| (*id, 0)).collect(), added: Vec::new(), removed: false }
}
fn contains(&self, id: NodeId) -> bool {
self.live.contains_key(&id)
}
/// [`Selection::add`]: clears what any selection change clears, and selects `id` at the end
/// unless it is selected.
fn add(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if let std::collections::hash_map::Entry::Vacant(e) = self.live.entry(id) {
let activation = self.added.len() + 1;
e.insert(activation);
self.added.push((id, activation));
}
}
/// [`Selection::remove`]: clears what any selection change clears, and deselects `id` with
/// its anchors, segments, and the key or key anchor it is.
fn remove(&mut self, sel: &mut Selection, id: NodeId) {
sel.target = None;
sel.slices.clear();
sel.symbol_part = None;
sel.on_path_member = None;
if self.live.remove(&id).is_some() {
self.removed = true;
}
sel.anchors.remove(&id);
sel.segments.remove(&id);
if sel.key == Some(id) {
sel.key = None;
}
if sel.key_anchor.is_some_and(|(k, _)| k == id) {
sel.key_anchor = None;
}
}
/// [`Selection::toggle`].
fn toggle(&mut self, sel: &mut Selection, id: NodeId) {
if self.contains(id) { self.remove(sel, id) } else { self.add(sel, id) }
}
/// Writes the selected objects to `sel.objects`: the slots of the objects selected before and
/// still selected by that activation, in their order, then the ids selected since and still
/// selected by the activation that added them, in the order they were added.
fn finish(self, sel: &mut Selection) {
if self.removed {
count_objects_walk();
sel.objects.retain(|id| self.live.get(id) == Some(&0));
}
sel.objects.extend(self.added.into_iter().filter(|(id, n)| self.live.get(id) == Some(n)).map(|(id, _)| id));
}
}
#[cfg(test)]
thread_local! {
/// Tests: how many walks [`select_anchor_items`] made over the selected objects on this thread.
pub(crate) static OBJECTS_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: count one walk over the selected objects.
fn count_objects_walk() {
#[cfg(test)]
OBJECTS_WALKS.set(OBJECTS_WALKS.get() + 1);
}
/// Select › Same › Fill/Stroke Color: is `a` the same colour as `b`? Tints of one global or spot
/// swatch are, unless `tint` (General › Select Same Tint %) asks for the same tint too.
pub(crate) fn same_paint(a: &Paint, b: &Paint, tint: bool) -> bool {
@@ -1287,3 +1380,6 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
#[cfg(test)]
mod tests;
+286
View File
@@ -0,0 +1,286 @@
//! `select.anchorsMany`'s item loop ([`select_anchor_items`]) against a loop that changes the
//! selection one item at a time through [`Selection::add`], [`Selection::remove`] and
//! [`Selection::toggle`].
use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use vectorcraft_color::Color;
use vectorcraft_doc::{AnchorRef, Document, NodeId, Selection, SymbolPart};
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
use super::{OBJECTS_WALKS, select_anchor_items};
type Items = Vec<(NodeId, BTreeSet<AnchorRef>)>;
const MODES: [&str; 4] = ["set", "add", "toggle", "subtract"];
/// The item loop through `Selection`'s own methods, each of which goes through `objects`.
fn item_by_item(d: &Document, sel: &mut Selection, items: Items, mode: &str) {
if mode == "set" {
sel.clear();
}
for (id, refs) in items {
let segment_pick = sel.segments.remove(&id).is_some();
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
if all.is_empty() {
match mode {
"toggle" => sel.toggle(id),
"subtract" => sel.remove(id),
_ => sel.add(id),
}
continue;
}
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
None if sel.contains(id) => all.clone(),
None => BTreeSet::new(),
};
let refs: BTreeSet<AnchorRef> = refs.intersection(&all).copied().collect();
let next: BTreeSet<AnchorRef> = match mode {
"toggle" => now.symmetric_difference(&refs).copied().collect(),
"subtract" => now.difference(&refs).copied().collect(),
_ => now.union(&refs).copied().collect(),
};
if next.is_empty() {
sel.remove(id);
continue;
}
sel.add(id);
if next.len() < all.len() {
sel.anchors.insert(id, next);
} else {
sel.anchors.remove(&id);
}
}
}
/// A document with `n` four-anchor rectangles and, after them, a group of two more → the
/// rectangles' ids and the group's.
fn doc(n: usize) -> (Document, Vec<NodeId>, NodeId) {
let mut b = DocBuilder::new(2000.0, 2000.0);
let rects = (0..n)
.map(|i| {
let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0);
b.rect(Rect::new(x, y, x + 5.0, y + 5.0), Color::rgb(0.2, 0.4, 0.6), |_| {})
})
.collect();
let black = Color::rgb(0.0, 0.0, 0.0);
let kids = vec![b.rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), black), b.rect_node(Rect::new(2.0, 0.0, 3.0, 1.0), black)];
let group = b.group(kids, false);
(b.build(), rects, group)
}
fn anchors(refs: &[(usize, usize)]) -> BTreeSet<AnchorRef> {
refs.iter().copied().collect()
}
/// A selection with every field set: rectangles 0 to 4 and the group, rectangle 2 listed twice,
/// partial anchors on 1 and 3, a segment pick on 4, rectangle 1 the key, a key anchor on 3, and a
/// target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded(r: &[NodeId], group: NodeId) -> Selection {
let mut s = Selection { objects: vec![r[0], r[1], r[2], r[3], group, r[2], r[4]], ..Selection::default() };
s.anchors.insert(r[1], anchors(&[(0, 0), (0, 1)]));
s.anchors.insert(r[3], anchors(&[(0, 2)]));
s.anchors.insert(r[4], anchors(&[(0, 0), (0, 1)]));
s.segments.insert(r[4], anchors(&[(0, 0)]));
s.key = Some(r[1]);
s.key_anchor = Some((r[3], (0, 2)));
s.target = Some(r[0]);
s.slices = vec![r[5]];
s.guides = vec![r[6]];
s.key_guide = Some(r[6]);
s.new_art = Arc::new(HashSet::from([r[2]]));
s.symbol_part = Some(SymbolPart { instance: r[0], path: vec![0] });
s.on_path_member = Some(r[7]);
s
}
/// Item lists with repeated ids, removals followed by additions, the group, anchors outside a
/// path, items that empty a path, and the empty list, then pseudo-random lists.
fn item_streams(r: &[NodeId], group: NodeId) -> Vec<Items> {
let all = [(0, 0), (0, 1), (0, 2), (0, 3)];
let mut streams: Vec<Items> = vec![
vec![],
vec![(r[2], anchors(&[(0, 0)]))],
vec![(r[2], anchors(&all)), (r[2], anchors(&all))],
vec![(r[2], anchors(&all)), (r[5], anchors(&[(0, 1)])), (r[2], anchors(&[(0, 3)]))],
vec![(group, anchors(&[])), (group, anchors(&[(0, 0)])), (group, anchors(&[]))],
vec![(r[6], anchors(&[(0, 0)])), (r[6], anchors(&[(0, 0)])), (r[7], anchors(&[(0, 9), (3, 0)]))],
vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&all)), (r[3], anchors(&all))],
vec![(r[4], anchors(&[])), (r[4], anchors(&[(0, 2)]))],
vec![(r[1], anchors(&all)), (r[3], anchors(&all)), (r[1], anchors(&[(0, 0)])), (r[3], anchors(&[(0, 2)]))],
vec![(r[8], anchors(&[(0, 0)])), (r[0], anchors(&all)), (r[8], anchors(&all)), (r[0], anchors(&[(0, 1)]))],
];
let pool: Vec<NodeId> = r.iter().copied().chain([group]).collect();
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
for len in [3, 9, 25, 80, 200] {
let items = (0..len)
.map(|_| {
let id = pool[(next() % pool.len() as u64) as usize];
// Bits 0 to 4 of a draw pick anchors 0 to 3 and one past the end.
let bits = next();
let refs = (0..5).filter(|i| (bits >> i) & 1 == 1).map(|i| (0, i)).collect();
(id, refs)
})
.collect();
streams.push(items);
}
streams
}
/// Starting selections: the seeded one, none, every rectangle whole, and every rectangle with
/// one anchor.
fn starts(r: &[NodeId], group: NodeId) -> Vec<Selection> {
let mut whole = Selection::default();
whole.set(r.iter().copied().chain([group]));
let mut partial = whole.clone();
for id in r {
partial.anchors.insert(*id, anchors(&[(0, 1)]));
}
vec![seeded(r, group), Selection::default(), whole, partial]
}
#[test]
fn anchor_items_do_what_the_item_by_item_loop_does() {
let (d, r, group) = doc(12);
for start in starts(&r, group) {
for items in item_streams(&r, group) {
for mode in MODES {
let mut expected = start.clone();
item_by_item(&d, &mut expected, items.clone(), mode);
let mut got = start.clone();
select_anchor_items(&d, &mut got, items.clone(), mode);
assert_eq!(got, expected, "mode {mode}, items {items:?}, from {start:?}");
assert_eq!(got.new_art, expected.new_art);
}
}
}
}
#[test]
fn a_path_deselected_and_selected_again_goes_last_without_its_key() {
let (d, r, group) = doc(12);
let all = anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]);
let mut s = seeded(&r, group);
// Toggling the selected anchors of 1 and 3 deselects them; toggling again selects them again.
let items = vec![(r[1], anchors(&[(0, 0), (0, 1)])), (r[3], anchors(&[(0, 2)])), (r[1], anchors(&[(0, 0)])), (r[3], all)];
select_anchor_items(&d, &mut s, items, "toggle");
assert_eq!(s.objects, [r[0], r[2], group, r[2], r[4], r[1], r[3]]);
assert_eq!(s.anchors.get(&r[1]), Some(&anchors(&[(0, 0)])));
assert_eq!(s.anchors.get(&r[3]), None);
assert_eq!((s.key, s.key_anchor), (None, None));
}
/// Every rectangle with one anchor, as a Direct Selection marquee sends them.
fn marquee(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0)]))).collect()
}
/// Every rectangle with all four anchors, which deselects each in subtract mode.
fn every_anchor(r: &[NodeId]) -> Items {
r.iter().map(|id| (*id, anchors(&[(0, 0), (0, 1), (0, 2), (0, 3)]))).collect()
}
#[test]
fn anchor_items_walk_the_selected_objects_at_most_twice() {
let (d, r, group) = doc(2000);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (start, items, mode) in [
(Selection::default(), marquee(&r), "set"),
(all.clone(), marquee(&r), "toggle"),
(all.clone(), every_anchor(&r), "subtract"),
(all.clone(), every_anchor(&r).into_iter().chain(marquee(&r)).collect(), "toggle"),
] {
let mut s = start;
OBJECTS_WALKS.set(0);
select_anchor_items(&d, &mut s, items, mode);
let walks = OBJECTS_WALKS.get();
assert!(walks <= 2, "{mode}: {walks} walks over the selected objects");
}
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
}
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
fn time(f: impl FnOnce()) -> Duration {
match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = Instant::now();
f();
start.elapsed()
}
}
}
fn ms(d: Duration) -> f64 {
d.as_secs_f64() * 1000.0
}
/// Timings of the item loop and the item-by-item loop on 2,000, 20,000 and 50,000 rectangles, run
/// in turn on clones of the same selection, 7 runs each. Ignored by default; it prints the median,
/// fastest and slowest run and sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --lib anchor_items_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn anchor_items_perf() {
const RUNS: usize = 7;
eprintln!("anchor_items_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("anchor_items_perf: {:>6} {:<26} {:>28} {:>28}", "paths", "case", "item by item ms (min-max)", "item loop ms (min-max)");
for n in [2_000, 20_000, 50_000] {
let (d, r, group) = doc(n);
let mut all = Selection::default();
all.set(r.iter().copied().chain([group]));
for (case, start, items, mode) in [
("set, marquee", Selection::default(), marquee(&r), "set"),
("add, marquee", Selection::default(), marquee(&r), "add"),
("toggle, Select All", all.clone(), marquee(&r), "toggle"),
("subtract every anchor", all.clone(), every_anchor(&r), "subtract"),
] {
let (mut old, mut new) = (Vec::new(), Vec::new());
for run in 0..RUNS {
let (mut a, mut b) = (start.clone(), start.clone());
let (ia, ib) = (items.clone(), items.clone());
// The two loops take turns going first.
if run % 2 == 0 {
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
} else {
new.push(time(|| select_anchor_items(&d, &mut b, ib, mode)));
old.push(time(|| item_by_item(&d, &mut a, ia, mode)));
}
assert_eq!(a, b, "{n} paths, {case}");
}
old.sort();
new.sort();
eprintln!(
"anchor_items_perf: {n:>6} {case:<26} {:>10.3} ({:>7.3}-{:>8.3}) {:>10.3} ({:>7.3}-{:>8.3})",
ms(old[RUNS / 2]),
ms(old[0]),
ms(old[RUNS - 1]),
ms(new[RUNS / 2]),
ms(new[0]),
ms(new[RUNS - 1]),
);
}
}
}
+10 -2
View File
@@ -53,7 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
style_delete
),
cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate),
cmd!(
"graphicStyle.duplicate",
"Duplicate Graphic Style",
["Window", "Graphic Styles"],
None,
"{name} a copy of the style at the end of the list, named `<name> copy` (`<name> copy 2`… when that is taken); no object is linked to it → {name}",
has_doc,
style_duplicate
),
cmd!(
query "graphicStyle.list",
"List Graphic Styles",
@@ -431,7 +439,7 @@ fn style_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let pos = style_index(d, &name)?;
let nm = unique_name(&format!("{name} copy"), |n| d.graphic_style(n).is_some());
let g = GraphicStyle { name: nm.clone(), id: d.next_graphic_style_id(), ..d.graphic_styles[pos].clone() };
d.graphic_styles.insert(pos + 1, g);
d.graphic_styles.push(g);
Ok(nm)
})?;
Ok(json!({"name": new}))
+231
View File
@@ -452,6 +452,237 @@ fn what_cannot_be_intertwined_is_refused_with_a_reason() {
assert!(e.to_string().contains("not an Intertwine group"), "{e}");
}
// ---------- members dragged in and out in the Layers panel ----------
/// A green rectangle (84..96 × 46..54) that crosses ring B's stroke at (90, 50) and no part of A.
fn green_bar(s: &mut Session) -> NodeId {
let id = id_of(&s.execute("shape.rectangle", &json!({"x": 84, "y": 46, "width": 12, "height": 8})).unwrap());
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
id
}
fn kids(s: &Session, g: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(g).and_then(vectorcraft_doc::Node::children).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
}
fn rows(s: &mut Session, ids: &[NodeId], target: NodeId, place: &str, copy: bool) -> Result<Value> {
s.execute("layer.move", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "target": target.0, "place": place, "copy": copy}))
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn has_areas(s: &Session, id: NodeId) -> bool {
let n = s.doc().unwrap().doc.node(id).unwrap();
n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty()
}
fn parent(s: &Session, id: NodeId) -> Option<NodeId> {
s.doc().unwrap().doc.parent_of(id)
}
/// The help page: "You can drag additional objects into the group later."
#[test]
fn layer_move_adds_a_member_without_losing_existing_weave() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = green_bar(&mut s);
let undo = undo_len(&s);
rows(&mut s, &[c], g, "inside", false).unwrap();
assert_eq!(kids(&s, g), [a, b, c], "on top of the group's objects");
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(area(&s, a).is_some(), "the arranged overlap is kept");
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "the rings are woven as before");
assert!(green(&r, 90, 50), "the new member is drawn in its own order");
// A live member: its overlap with B can be arranged.
assert_eq!(arrange(&mut s, json!({"id": g.0, "at": [90, 50]}))["count"], 1);
assert!(blue(&render(&s), 90, 50));
for format in ["vectorcraft", "svg"] {
let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone();
let mut o = Session::new();
o.execute("document.open", &json!({"name": format!("woven.{format}"), "dataBase64": data})).unwrap();
let r = render(&o);
assert!(red(&r, 50, 30) && blue(&r, 50, 70) && blue(&r, 90, 50), "{format}");
}
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
assert_eq!(parent(&s, c), parent(&s, g));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
}
/// An object that overlaps no member still joins the group, beside a member's row too; Alt-drag
/// adds a copy, which starts drawn in its own order everywhere.
#[test]
fn layer_move_accepts_nonoverlapping_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let c = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
rows(&mut s, &[c], a, "above", false).unwrap();
assert_eq!(kids(&s, g), [a, c, b], "above member A");
let v = rows(&mut s, &[a], g, "inside", true).unwrap();
let copy = NodeId(v["ids"][0].as_u64().unwrap());
assert_eq!(kids(&s, g), [a, c, b, copy]);
assert!(has_areas(&s, a) && !has_areas(&s, copy), "the copy has no arranged areas");
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70), "the copy of A is drawn over B at both crossings");
}
#[test]
fn layer_move_rejects_unsupported_intertwine_members_atomically() {
let mut s = session();
let (a, b) = rings(&mut s);
let p = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[p]);
let pg = id_of(&s.execute("object.group", &json!({})).unwrap());
select(&mut s, &[a, b, pg]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
let f = id_of(&s.execute("shape.rectangle", &json!({"x": 180, "y": 180, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g2, f]);
let holder = id_of(&s.execute("object.group", &json!({})).unwrap());
let layer = s.doc().unwrap().doc.layer_of(g).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = undo_len(&s);
// No nested Intertwine groups: not as a member, inside a member's group, beside a member's
// row, nor held in a group.
for (ids, target, place) in [(g2, g, "inside"), (g2, pg, "inside"), (g2, a, "above"), (holder, g, "inside"), (holder, b, "below")] {
let err = rows(&mut s, &[ids], target, place, false).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{place} {}: {err}", target.0);
let err = rows(&mut s, &[ids], target, place, true).unwrap_err();
assert!(err.to_string().contains("can't be intertwined"), "copy: {err}");
}
let err = s.execute("node.move", &json!({"id": holder.0, "parent": g.0, "index": 0})).unwrap_err();
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{err}");
let err = rows(&mut s, &[layer], g, "inside", false).unwrap_err();
assert!(err.to_string().contains("can't go into"), "{err}");
assert_eq!(undo_len(&s), undo, "no undo step");
assert!(s.doc().unwrap().doc == before, "the document is as it was");
// A plain object goes into the group inside the Intertwine group.
rows(&mut s, &[f], pg, "inside", false).unwrap();
assert_eq!(kids(&s, pg), [p, f]);
}
#[test]
fn layer_move_clears_areas_when_member_leaves() {
let mut s = session();
let (a, b) = rings(&mut s);
let c = green_bar(&mut s);
select(&mut s, &[a, b, c]);
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
arrange(&mut s, json!({"at": [50, 30]}));
assert!(has_areas(&s, a));
rows(&mut s, &[a], g, "above", false).unwrap();
assert_eq!(parent(&s, a), parent(&s, g));
assert!(!has_areas(&s, a), "ordinary art again");
assert_eq!(kids(&s, g), [b, c], "two members stay an Intertwine group");
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
let r = render(&s);
assert!(red(&r, 50, 30) && red(&r, 50, 70) && green(&r, 90, 50), "A is above the group at both crossings");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b, c]);
assert!(has_areas(&s, a));
assert!(red(&render(&s), 50, 30));
}
#[test]
fn layer_move_between_intertwines_drops_old_areas() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
select(&mut s, &[d, e]);
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
rows(&mut s, &[a], g2, "inside", false).unwrap();
assert_eq!(kids(&s, g2), [d, e, a]);
assert!(!has_areas(&s, a), "the areas of the group it left do not come along");
assert!(s.doc().unwrap().doc.node(g).is_none(), "the group A left has one member and is taken apart");
assert_eq!(parent(&s, b), parent(&s, g2));
}
#[test]
fn layer_move_dissolves_a_group_left_with_one_member() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
let top = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
select(&mut s, &[g]);
let undo = undo_len(&s);
rows(&mut s, &[b], top, "above", false).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, top, b], "the one member left is in the group's place");
assert!(!has_areas(&s, a), "with no other member it has no areas");
assert!(!s.doc().unwrap().selection.contains(g));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, layer), [g, top]);
assert_eq!(kids(&s, g), [a, b]);
let r = render(&s);
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "woven as before");
// Both members out: the empty group is removed.
rows(&mut s, &[a, b], g, "above", false).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [a, b, top]);
assert!(!has_areas(&s, a) && !has_areas(&s, b));
}
/// A group left with one member that has an opacity of its own stays, as a plain group of that
/// member, so the member is drawn as before.
#[test]
fn layer_move_keeps_a_lone_members_group_with_its_own_opacity() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
s.execute("object.setProps", &json!({"ids": [g.0], "opacity": 40})).unwrap();
let layer = parent(&s, g).unwrap();
rows(&mut s, &[b], g, "above", false).unwrap();
assert_eq!(kids(&s, layer), [g, b]);
assert_eq!(kids(&s, g), [a]);
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "a plain group");
assert!((n.opacity - 0.4).abs() < 1e-6, "{}", n.opacity);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
assert_eq!(kids(&s, g), [a, b]);
}
#[test]
fn node_move_and_send_to_current_layer_clean_up_membership() {
let mut s = session();
let (g, a, b) = intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let layer = parent(&s, g).unwrap();
s.execute("node.move", &json!({"id": b.0, "parent": layer.0, "index": 0})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kids(&s, g), [a, b]);
// A member sent to the current layer leaves the group the same way.
select(&mut s, &[a]);
s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g).is_none());
assert_eq!(kids(&s, layer), [b, a]);
assert!(!has_areas(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// node.move puts an object into an Intertwine group.
let c = green_bar(&mut s);
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 1})).unwrap();
assert_eq!(kids(&s, g), [a, c, b]);
}
// ---------- on the canvas ----------
fn press(s: &mut Session, pts: &[(f64, f64)], shift: bool) -> Vec<UiRequest> {
+130
View File
@@ -302,6 +302,136 @@ fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() {
}
}
/// Each copy of a group's Transform effect draws the drop shadow listed before the effect under
/// itself, of both its squares together and scaled with it, and Expand Appearance keeps those
/// shadows: the squares (20..40 together) have their shadow 20 pt to their right, and their copy
/// scaled 200 % and moved 80 pt down (10..50 across, 90..130 down) has its own 40 pt to its right.
/// A copy moved 30 pt right (50..70) lies under the squares' shadow (40..60), which still paints
/// over it once expanded. The expanded art has no effects left, and each object in it an id of its
/// own.
#[test]
fn each_copys_shadow_on_a_group_expands_as_the_canvas_draws_it() {
let cases = [
(json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1}), (80, 110), "the copy's shadow"),
(json!({"moveH": 30, "copies": 1}), (55, 30), "the squares' shadow over the copy"),
];
for (params, (x, y), what) in cases {
let mut s = session();
let mut ids = vec![];
for x in [20, 30] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 20}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": ids}));
run(&mut s, "object.group", json!({}));
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": params}));
let before = render(&s);
assert_eq!(before.pixel(x, y), [0, 255, 0, 255], "{params}: {what}");
run(&mut s, "effect.expandAppearance", json!({}));
let after = render(&s);
let diff = differing(&before, &after, 64);
assert_eq!(diff, 0, "{params}: {diff} pixels differ");
let doc = &s.doc().unwrap().doc;
let (mut seen, mut count, mut effects) = (std::collections::HashSet::new(), 0, 0);
for l in &doc.layers {
l.walk(&mut |n| {
seen.insert(n.id);
count += 1;
effects += n.appearance.effects.len();
});
}
assert_eq!(seen.len(), count, "{params}: each object has an id of its own");
assert_eq!(effects, 0, "{params}: no effects are left");
}
}
/// A member's random Transform effect takes its seed from the member's id, and the canvas draws
/// every copy of the group with that id: Expand Appearance of a group with a stroke of its own, a
/// shadow and a copying Transform effect gives each copy's symbol instance the same random move, so
/// the copies, 60 pt apart, still draw alike.
#[test]
fn each_copys_random_member_expands_as_the_canvas_draws_it() {
let mut s = session();
let mut ids = vec![];
for x in [20, 50] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 20, "height": 20}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
ids[0] = run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveH": 16, "moveV": 16, "random": true}}));
run(&mut s, "select.set", json!({"ids": ids}));
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [g]}));
run(&mut s, "appearance.addStroke", json!({}));
assert!(node(&s, NodeId(g)).appearance.items.iter().any(|i| i.visible()), "the group has a stroke of its own");
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow}));
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveV": 60, "copies": 2}}));
// The pixels of each copy's 60 pt band that differ from the first copy's by more than 64.
let unlike = |r: &vectorcraft_render::Rendered| {
let px = |x: usize, y: usize| {
let i = (y * r.width as usize + x) * 4;
r.pixels.get(i..i + 4).map(<[u8]>::to_vec).unwrap_or_default()
};
let mut n = 0;
for k in [60, 120] {
for y in 0..60 {
for x in 0..r.width as usize {
n += usize::from(px(x, y).iter().zip(px(x, y + k)).any(|(a, b)| a.abs_diff(b) > 64));
}
}
}
n
};
let before = render(&s);
assert_eq!(unlike(&before), 0, "the canvas draws the copies alike");
let art = vectorcraft_render::effects::evaluate_container(Some(&s.doc().unwrap().doc), &node(&s, NodeId(g))).unwrap();
let mut live = 0;
art.walk(&mut |n| live += n.appearance.effects.iter().filter(|e| e.id == "distort.transform").count());
assert_eq!(live, 3, "each copy's instance keeps its random effect live");
run(&mut s, "effect.expandAppearance", json!({}));
let after = render(&s);
assert_eq!(unlike(&after), 0, "the expanded copies draw alike");
assert!(differing(&before, &after, 64) < 200, "the copies stay where they are drawn");
}
/// A member's own Offset Path applies before the copying Transform effect of its group, which has
/// a stroke of its own, whether or not a shadow is listed before that Transform effect: the copy
/// scaled 200 % draws the offset square scaled, with or without a shadow at 0 % opacity.
#[test]
fn a_members_offset_path_applies_before_its_painted_groups_copies() {
let draw = |shadow: bool| {
let mut s = session();
let mut ids = vec![];
for x in [20, 40] {
ids.push(run(&mut s, "shape.rectangle", json!({"x": x, "y": 20, "width": 10, "height": 10}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
}
run(&mut s, "select.set", json!({"ids": [ids[0]]}));
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 5}}));
run(&mut s, "select.set", json!({"ids": ids}));
let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({}));
if shadow {
let fx = json!({"x": 10, "y": 0, "blur": 0, "opacity": 0, "mode": "normal", "color": "#00ff00"});
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": fx}));
}
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}}));
let n = node(&s, g);
assert_eq!(vectorcraft_render::effects::outer_effects(&n).len() < n.appearance.effects.len(), shadow, "each copy carries the shadow");
render(&s)
};
let diff = differing(&draw(false), &draw(true), 64);
assert_eq!(diff, 0, "{diff} pixels differ");
}
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
+39
View File
@@ -224,6 +224,45 @@ fn shadows_and_glows_keep_their_blend_modes() {
assert_eq!(modes, [vectorcraft_color::BlendMode::Multiply, vectorcraft_color::BlendMode::Screen]);
}
/// Each copy of a group's Transform effect has its own image of the shadow listed before the
/// effect, under that copy: the squares' shadow (40..60) paints over their copy moved 30 pt right
/// (50..70), as on the canvas, and the copies' objects have ids of their own.
#[test]
fn each_copys_shadow_on_a_group_flattens_under_that_copy() {
let mut d = Document::new(200.0, 200.0);
let members = [20.0, 30.0].map(|x| Arc::new(rect(&mut d, Rect::new(x, 40.0, x + 10.0, 60.0), Color::rgb(1.0, 0.0, 0.0))));
let mut g = Node::group(d.alloc_id(), members.to_vec());
g.appearance.effects = vec![
Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 20.0, "y": 0.0, "blur": 0.0, "opacity": 100.0, "mode": "normal", "color": "#00ff00"}),
visible: true,
},
Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 1}), visible: true },
];
add(&mut d, g);
let canvas = render(&d);
let flat = crate::flatten_raster_effects(&d).unwrap();
let back = render(&flat);
let at = |r: &Rendered, x: usize| {
let i = (50 * r.width as usize + x) * 4;
(r.pixels[i], r.pixels[i + 1], r.pixels[i + 2])
};
for x in [55, 65, 85] {
let (want, got) = (at(&canvas, x), at(&back, x));
assert!(want.0.abs_diff(got.0) < 32 && want.1.abs_diff(got.1) < 32 && want.2.abs_diff(got.2) < 32, "x {x}: {want:?} {got:?}");
}
assert!(at(&back, 55).1 > 200 && at(&back, 55).0 < 60, "the squares' shadow over the copy: {:?}", at(&back, 55));
let (mut seen, mut count) = (std::collections::HashSet::new(), 0);
for l in &flat.layers {
l.walk(&mut |n| {
seen.insert(n.id);
count += 1;
});
}
assert_eq!(seen.len(), count, "each object has an id of its own");
}
#[test]
fn pdf_resolution_cap_warns_once_for_original_object_when_appearance_items_split() {
let mut d = Document::new(300.0, 300.0);
+279 -1
View File
@@ -1,5 +1,5 @@
//! Use Preview Bounds: the Transform panel values, the bounding box, Align and Distribute measure
//! visual bounds (strokes and geometry effects included) when it is on.
//! visual bounds (strokes, geometry and projected 3D effects included) when it is on.
use std::sync::Arc;
@@ -103,6 +103,284 @@ fn near(a: Rect, b: Rect, tolerance: f64) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tolerance)
}
const PREVIEW_3D: [&str; 4] = ["threeD.extrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"];
/// A live projected rectangle, with the effect on the object or its painted fill.
fn projected_rect(s: &mut Session, effect: &str, item: bool) -> NodeId {
let id = rect(s, 100.0, 80.0, 0.0);
run(s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect), "item": if item { json!(0) } else { Value::Null }}));
id
}
/// Settings for `effect` that turn the art and give it depth.
fn params_3d(effect: &str) -> Value {
let mut params = json!({"rotationX": -20, "rotationY": 35, "rotationZ": 15, "perspectiveAngle": 0, "shade": false});
match effect {
"threeD.revolve" => {
params["segments"] = json!(8);
params["angle"] = json!(240);
params["offset"] = json!(12);
}
"threeD.extrude" => {
params["depth"] = json!(40);
params["bevel"] = json!("rounded");
}
"threeD.inflate" => params["depth"] = json!(20),
_ => {}
}
params
}
/// Measure the renderer's projected vector art, including any geometry effects left after 3D.
fn projected(s: &Session, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap()
}
/// All four projected effects contribute at object and item scope; off and hidden keep source bounds.
#[test]
fn preview_3d_measures_the_projected_art_at_object_and_item_scope() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
let expected = projected(&s, id);
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
preview(&mut s, false);
assert_eq!(s.transform_bounds(&[id]), Some(source));
preview(&mut s, true);
run(&mut s, "effect.setParams", json!({"ids": [id.0], "index": 0, "item": if item { json!(0) } else { Value::Null }, "visible": false}));
assert_eq!(s.transform_bounds(&[id]), Some(source), "hidden {effect}, item={item}");
}
}
}
/// Align and spacing use projected edges, with one undo step and no repeat-alignment edit.
#[test]
fn preview_3d_align_and_spacing_measure_projected_edges() {
for effect in PREVIEW_3D {
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 20.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert!((projected(&s, a).x0 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
let aligned = s.doc().unwrap().doc.clone();
run(&mut s, "object.align", json!({"horizontal": "left"}));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "already aligned {effect}");
assert_eq!(s.doc().unwrap().doc, aligned);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
run(&mut s, "edit.redo", json!({}));
assert_eq!(s.doc().unwrap().doc, aligned);
let mut s = session();
let a = projected_rect(&mut s, effect, false);
let b = rect(&mut s, 350.0, 30.0, 0.0);
preview(&mut s, true);
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let before = s.doc().unwrap().doc.clone();
run(&mut s, "object.distributeSpacing", json!({"axis": "horizontal", "spacing": 0}));
assert!((projected(&s, a).x1 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A group's and a symbol's projected members are measured as art rather than flat source paths.
#[test]
fn preview_3d_measures_projected_group_and_symbol_members() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let expected = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut shape = source.doc().unwrap().doc.node(source_id).unwrap().clone();
shape.id = d.alloc_id();
let group = Node::group(d.alloc_id(), vec![Arc::new(shape.clone())]);
let group_id = group.id;
let layer = d.layers[0].id;
d.insert(Some(layer), 0, group).unwrap();
shape.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: false, name: "3D / Bounds".into(), art: Arc::new(shape) });
let shift = Affine::translate((250.0, 0.0));
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Bounds".into(), xf: shift });
let instance_id = instance.id;
d.insert(Some(layer), 1, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[group_id]).unwrap(), expected, 1e-6), "group {effect}");
assert!(near(s.transform_bounds(&[instance_id]).unwrap(), shift.transform_rect_bbox(expected), 1e-6), "symbol {effect}");
}
}
/// A symbol instance with a 3D effect of its own is measured by the art the renderer projects from its symbol.
#[test]
fn preview_3d_measures_an_instance_with_its_own_effect() {
for effect in PREVIEW_3D {
let mut d = Document::new(600.0, 400.0);
let square = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 80.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(Symbol { dynamic: false, name: "3D / Own".into(), art: Arc::new(square) });
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Own".into(), xf: Affine::translate((50.0, 40.0)) });
let (layer, id) = (d.layers[0].id, instance.id);
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect)}));
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art_in(Some(d), n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), n)).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let source = geometric(&s, id);
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}");
}
}
/// Dynamic instance overrides are applied before deciding which painted 3D surfaces remain.
#[test]
fn preview_3d_dynamic_symbol_overrides_precede_projection() {
for effect in PREVIEW_3D {
let mut source = session();
let source_id = projected_rect(&mut source, effect, false);
let full = projected(&source, source_id);
let mut d = Document::new(600.0, 400.0);
let mut art = source.doc().unwrap().doc.node(source_id).unwrap().clone();
art.id = d.alloc_id();
d.symbols.push(Symbol { dynamic: true, name: "3D / Dynamic".into(), art: Arc::new(art) });
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Dynamic".into(), xf: Affine::IDENTITY });
instance
.extras_mut()
.symbol_overrides
.push(vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(Paint::None), ..Default::default() });
let id = instance.id;
let changed = vectorcraft_doc::symbol_overrides::dynamic_art(&d.symbols[0].art, &instance);
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &changed);
if effect == "threeD.extrude" {
assert!(expected.is_some(), "the Extrude fixture must retain its source bounds");
}
assert!(expected.is_none_or(|b| !near(b, full, 1e-3)), "the override must remove the projected surface: {effect}");
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance).unwrap();
let mut s = Session::new();
s.add_document(d, None);
preview(&mut s, true);
let actual = s.transform_bounds(&[id]);
assert!(
match (actual, expected) {
(Some(a), Some(b)) => near(a, b, 1e-6),
(None, None) => true,
_ => false,
},
"overridden {effect}: {actual:?}, expected {expected:?}"
);
run(&mut s, "symbol.instance.reset", json!({"ids": [id.0]}));
assert!(near(s.transform_bounds(&[id]).unwrap(), full, 1e-6), "reset {effect}");
}
}
/// Geometry after projection remains part of the measured stack at object and item scope.
#[test]
fn preview_3d_applies_geometry_after_the_projected_surface() {
for effect in PREVIEW_3D {
for item in [false, true] {
let mut s = session();
let id = projected_rect(&mut s, effect, item);
run(
&mut s,
"effect.apply",
json!({"ids": [id.0], "effect": "path.offsetPath", "params": {"offset": 5}, "item": if item { json!(0) } else { Value::Null }}),
);
let expected = projected(&s, id);
preview(&mut s, true);
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
}
}
}
/// Typed width sizes the projected art and remains one undoable edit.
#[test]
fn preview_3d_set_bounds_sizes_the_projected_width() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
let target = projected(&s, id).width() * 1.25;
preview(&mut s, true);
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
run(&mut s, "object.setBounds", json!({"width": target, "reference": 0, "proportional": true, "strokes": false}));
assert!((projected(&s, id).width() - target).abs() < 1e-4, "{effect}: {:?}, target {target}", projected(&s, id));
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().doc, before);
}
}
/// A rotated selection measures the projected surface in its own bounding-box frame.
#[test]
fn preview_3d_oriented_box_follows_projected_art() {
for effect in PREVIEW_3D {
let mut s = session();
let id = projected_rect(&mut s, effect, false);
run(&mut s, "object.rotate", json!({"angle": 30}));
let d = &s.doc().unwrap().doc;
let angle = d.bbox_angle(&[id]);
assert!(angle.abs() > 0.1);
let n = d.node(id).unwrap();
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
let frame = vectorcraft_doc::OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse();
let expected = vectorcraft_render::effects::preview::bounds_in(&d.symbol_boxes(), &art, frame).unwrap();
preview(&mut s, true);
let measured = s.transform_box(&[id]).unwrap();
assert_eq!(measured.angle, angle);
assert!(near(measured.rect, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
/// A click on a member of a layer with a 3D effect selects that member, with Use Preview Bounds on
/// or off, and the layer is still measured by its projected art.
#[test]
fn a_click_selects_the_member_of_a_layer_with_a_3d_effect() {
for effect in PREVIEW_3D {
for on in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 80.0, 0.0);
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "effect.apply", json!({"ids": [layer.0], "effect": effect, "params": params_3d(effect), "item": null}));
preview(&mut s, on);
run(&mut s, "select.none", json!({}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 140.0, 125.0), v).unwrap();
}
assert_eq!(s.active().unwrap().selection.objects, [id], "{effect}, preview={on}");
let d = &s.doc().unwrap().doc;
let art =
vectorcraft_render::effects::revolve_art(&d.layers[0]).or_else(|| vectorcraft_render::effects::solid_art(&d.layers[0])).unwrap();
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
let measured = vectorcraft_render::effects::preview::bounds_of(d, &[layer], true).unwrap();
assert!(near(measured, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
}
}
}
#[test]
fn a_square_with_offset_path_is_measured_by_the_offset_shape() {
let mut s = session();
+26
View File
@@ -151,6 +151,32 @@ fn style_names_are_unique() {
assert_ne!(style(&s, "Y copy").id, style(&s, "Y").id);
}
#[test]
fn duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "graphicStyle.new", json!({"name": "S"}));
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
let before = names(&s);
// A style that is not last: the copy still goes after every other style.
let first = before[0].clone();
assert_ne!(first, *before.last().unwrap());
assert_eq!(run(&mut s, "graphicStyle.duplicate", json!({"name": first}))["name"], format!("{first} copy"));
let after = names(&s);
assert_eq!(after[..before.len()], before[..]);
assert_eq!(after.last(), Some(&format!("{first} copy")));
let (src, copy) = (style(&s, &first), style(&s, &format!("{first} copy")));
assert_eq!(copy.appearance, src.appearance);
assert_ne!(copy.id, src.id);
// Nothing is linked to the copy, and the source keeps its links.
assert!(linked(&mut s, &format!("{first} copy")).is_empty());
assert_eq!(linked(&mut s, "S"), vec![a.0]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(names(&s), before);
assert!(s.execute("graphicStyle.duplicate", &json!({"name": "nope"})).is_err());
assert_eq!(names(&s), before);
}
/// Three rectangles: `a` (the source of style "S"), `b` and `c`, all linked to "S".
fn linked_three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let a = rect(s, 10.0);
+2 -1
View File
@@ -4524,7 +4524,8 @@ proptest! {
})?;
match opened {
Some(Ok(editing)) => prop_assert!(editing),
Some(Err(e)) => prop_assert_eq!(Some(e), page_error),
// The page's error, followed by why the editing data couldn't be read when it says.
Some(Err(e)) => prop_assert!(page_error.as_deref().is_some_and(|p| e == p || e.starts_with(&format!("{p}; its editing data couldn't be read either ("))), "{e}"),
None => {}
}
}
+169 -1
View File
@@ -1,7 +1,10 @@
//! Clear deletes its exact targets, including compound members (#786).
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{NodeId, Selection};
use vectorcraft_engine::{EngineError, Session};
fn compound() -> (Session, NodeId, NodeId, NodeId) {
@@ -225,3 +228,168 @@ fn clear_explicit_ids_preserves_unrelated_selection() {
assert!(s.active().unwrap().doc.node(r2).is_none());
assert!(s.active().unwrap().selection.is_empty());
}
fn rectangles(s: &mut Session, n: i64) -> Vec<NodeId> {
(0..n)
.map(|i| {
NodeId(s.execute("shape.rectangle", &json!({"x": 10 + 40 * i, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap())
})
.collect()
}
/// Clear with `ids` leaves the selection that removing each id on its own leaves: the other objects
/// in their order, their anchor and segment picks, a key object or key anchor that is not removed,
/// and the selected guides. Undo brings back the document and the selection, and Redo the result.
#[test]
fn clear_explicit_ids_leaves_what_removing_each_id_leaves() {
for key_anchor in [false, true] {
for removed in [[1, 4, 1, 6], [0, 2, 2, 6]] {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = rectangles(&mut s, 7);
s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap();
let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap();
let sel = &mut s.active_mut().unwrap().selection;
// The seventh rectangle is not selected: Clear removes it from the document only.
sel.set(r[..6].iter().copied());
sel.guides = vec![guide];
for (id, anchor) in [(r[1], (0, 1)), (r[2], (0, 2)), (r[4], (0, 0)), (r[5], (0, 2))] {
sel.anchors.insert(id, BTreeSet::from([anchor, (0, 1)]));
}
for id in [r[2], r[5]] {
sel.segments.insert(id, BTreeSet::from([(0, 1)]));
}
if key_anchor {
sel.key_anchor = Some((r[4], (0, 0)));
} else {
sel.key = Some(r[4]);
}
let before = sel.clone();
// The selection is one that `prune` keeps as it is, so Undo can restore it unchanged.
let mut pruned = before.clone();
pruned.prune(&s.active().unwrap().doc);
assert_eq!(pruned, before);
let doc_before = s.active().unwrap().doc.clone();
let ids: Vec<NodeId> = removed.iter().map(|i| r[*i]).collect();
s.execute("edit.clear", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
let st = s.active().unwrap();
let mut expected = before.clone();
for id in &ids {
expected.remove(*id);
}
expected.prune(&st.doc);
assert_eq!(st.selection, expected, "key anchor {key_anchor}, removed {removed:?}");
assert_eq!(st.selection.guides, vec![guide]);
assert!(ids.iter().all(|id| st.doc.node(*id).is_none()));
let doc_after = st.doc.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, doc_before);
assert_eq!(s.active().unwrap().selection, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, doc_after);
assert_eq!(s.active().unwrap().selection, expected);
}
}
}
/// Cut of many selected objects puts each of them on the clipboard in paint order, removes them and
/// the selected guide, and leaves nothing selected. One Undo brings all of it back.
#[test]
fn cut_of_many_objects_takes_them_all_out_of_the_selection() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = rectangles(&mut s, 40);
s.execute("guide.add", &json!({"vertical": true, "pos": 10})).unwrap();
let guide = s.active().unwrap().doc.ruler_guides()[0].id.unwrap();
let ids: Vec<u64> = r.iter().rev().map(|id| id.0).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let sel = &mut s.active_mut().unwrap().selection;
sel.guides = vec![guide];
sel.key = Some(r[7]);
let before = sel.clone();
let doc_before = s.active().unwrap().doc.clone();
s.execute("edit.cut", &json!({})).unwrap();
assert_eq!(s.clipboard.nodes.iter().map(|n| n.id).collect::<Vec<_>>(), r);
let st = s.active().unwrap();
assert!(r.iter().all(|id| st.doc.node(*id).is_none()));
assert!(st.doc.ruler_guides().is_empty());
assert_eq!(st.selection, Selection::default());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, doc_before);
assert_eq!(s.active().unwrap().selection, before);
}
/// Timings of taking the cut objects out of a selection of 2,000, 20,000 and 50,000 objects: one
/// [`Selection::remove`] per id, as Clear with `ids` did before, against one
/// [`Selection::remove_all`], for all of the objects and for every other one. The two run in turn
/// in one process, 7 times each, and the two results are compared field by field. It also times
/// Cut of every object, with Undo between the runs. Ignored by default; it prints its timings and
/// sets no bound on them:
/// `cargo test --release -p vectorcraft-engine --test it clear_selection_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn clear_selection_perf() {
fn ms(d: &[Duration]) -> String {
d.iter().map(|d| format!("{:.3}", d.as_secs_f64() * 1000.0)).collect::<Vec<_>>().join(" ")
}
fn median(d: &mut [Duration]) -> f64 {
d.sort();
d[d.len() / 2].as_secs_f64() * 1000.0
}
for n in [2_000_i64, 20_000, 50_000] {
let mut b = vectorcraft_testkit::fixtures::DocBuilder::new(4000.0, 4000.0);
let r: Vec<NodeId> = (0..n)
.map(|i| {
let (x, y) = ((i % 400) as f64 * 10.0, (i / 400) as f64 * 10.0);
b.rect(vectorcraft_geom::Rect::new(x, y, x + 8.0, y + 8.0), vectorcraft_color::Color::rgb(0.2, 0.4, 0.6), |_| {})
})
.collect();
let doc = b.build();
let mut sel = Selection::default();
sel.set(r.iter().copied());
for id in r.iter().step_by(10) {
sel.anchors.insert(*id, BTreeSet::from([(0, 0)]));
}
sel.key = Some(r[r.len() / 2]);
for (what, ids) in [("all", r.clone()), ("every other", r.iter().copied().step_by(2).collect::<Vec<_>>())] {
let (mut each, mut all) = (Vec::new(), Vec::new());
for _ in 0..7 {
let mut one_by_one = sel.clone();
let start = Instant::now();
for id in &ids {
one_by_one.remove(*id);
}
one_by_one.prune(&doc);
each.push(start.elapsed());
let mut at_once = sel.clone();
let start = Instant::now();
at_once.remove_all(ids.iter().copied());
at_once.prune(&doc);
all.push(start.elapsed());
assert_eq!(at_once, one_by_one);
}
eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove each ms: {}", ids.len(), ms(&each));
eprintln!("clear_selection_perf: {n} selected, {what} ({} ids), remove_all ms: {}", ids.len(), ms(&all));
eprintln!(
"clear_selection_perf: {n} selected, {what}: median remove each {:.3} ms, remove_all {:.3} ms",
median(&mut each),
median(&mut all)
);
}
let mut s = Session::new();
let data = vectorcraft_format::base64_encode(&vectorcraft_format::save(&doc, false));
s.execute("document.open", &json!({"name": "perf.vectorcraft", "dataBase64": data})).unwrap();
s.execute("select.all", &json!({})).unwrap();
let mut cut = Vec::new();
for _ in 0..7 {
let start = Instant::now();
s.execute("edit.cut", &json!({})).unwrap();
cut.push(start.elapsed());
assert!(s.active().unwrap().selection.objects.is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().selection.objects.len(), r.len());
}
eprintln!("clear_selection_perf: {n} selected, edit.cut ms: {}", ms(&cut));
eprintln!("clear_selection_perf: {n} selected, edit.cut median {:.3} ms", median(&mut cut));
}
}
+128
View File
@@ -1805,6 +1805,134 @@ fn linear_picks_show_and_snap_to_smart_guides() {
assert_eq!(text(&s, id), "60.02 pt");
}
/// A shape with a curve at each top corner, for the tests of where Linear picks land.
const CURVED_TOP: &str = "M130 358 C185 358 230 315 230 260 L425 260 C490 260 541 305 541 358 L541 440 L130 440 Z";
/// Where the next Linear click lands (the last marker the overlays draw, and its size) and the
/// labels shown, with the pointer at (`x`, `y`).
fn linear_marker(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> (Option<(vectorcraft_geom::Point, f32)>, Vec<String>) {
use vectorcraft_engine::tools::Overlay;
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
let o = s.overlays(view);
let at = o.iter().filter_map(|o| if let Overlay::Anchor { p, size, .. } = o { Some((*p, *size)) } else { None }).next_back();
let labels = o.iter().filter_map(|o| if let Overlay::Label { text, .. } = o { Some(text.clone()) } else { None }).collect();
(at, labels)
}
/// A plain click at (`x`, `y`): the pointer moves there, then presses and releases.
fn linear_click(s: &mut Session, view: ViewInfo, x: f64, y: f64) {
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
}
/// Linear picks land on the anchors and paths of the art with an "anchor" or "path" label, and on
/// the ends and lines of dimensions already drawn, from as far as on the art's anchors: zoomed in,
/// a dimension started a few pixels from the end of another starts exactly at that end.
#[test]
fn linear_picks_land_on_anchors_paths_and_drawn_dimensions() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
let hover = |s: &mut Session, view: ViewInfo, x: f64, y: f64| {
let (at, labels) = linear_marker(s, view, x, y);
(at.map(|(p, _)| p), labels)
};
// Beside the end of the curve: on the anchor, labeled.
assert_eq!(hover(&mut s, plain, 231.0, 262.0), (Some(pt(230.0, 260.0)), vec!["anchor".to_string()]));
// Beside the curve: on its closest point, labeled.
let (at, labels) = hover(&mut s, plain, 200.0, 337.0);
assert!(at.is_some_and(|q| q.distance(pt(200.0, 337.0)) < 6.0 && q != pt(200.0, 337.0)), "{at:?}");
assert_eq!(labels, ["path"]);
// A first dimension from the bottom of the curve to its top, placed above the art.
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(130.0, 358.0), pt(230.0, 260.0)));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", zoomed).unwrap();
// Zoomed in, 5.8 pixels from the end of its dimension line: on that end, marked as an anchor.
assert_eq!(linear_marker(&mut s, zoomed, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec!["anchor".to_string()]));
// 6.4 pixels beside its extension line: on the line.
let (at, labels) = hover(&mut s, zoomed, 230.8, 230.0);
assert!(at.is_some_and(|q| (q.x - 230.0).abs() < 1e-6 && (q.y - 230.0).abs() < 1e-6), "{at:?}");
assert_eq!(labels, ["path"]);
// The next dimension starts where the first one's line ends.
linear_click(&mut s, zoomed, 230.6, 207.4);
linear_click(&mut s, zoomed, 425.0, 260.0);
linear_click(&mut s, zoomed, 330.0, 207.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
let d = recipe(&s, second);
assert!(near(d.a, pt(230.0, 207.0)) && near(d.b, pt(425.0, 260.0)), "{:?} {:?}", d.a, d.b);
}
/// An anchor of the art that a dimension already measures takes a point picked beside it, not the
/// end of the extension line a few points off it. A locked dimension pulls no point, and with
/// Smart Guides and Snap to Point off no dimension pulls a point and no label shows. A press on
/// the end of a dimension's line over a segment of the art that moves a few pixels before the
/// release picks that end, as a press on an anchor does.
#[test]
fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..zoomed };
let mut s = session();
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
run(&mut s, "select.none", json!({}));
s.select_tool("dimension", plain).unwrap();
let pt = vectorcraft_geom::Point::new;
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 230.0, 260.0);
linear_click(&mut s, plain, 180.0, 207.0);
let first = s.doc().unwrap().selection.objects[0].0;
// Locked, the first dimension's line end does not pull a point 5.8 pixels away.
run(&mut s, "object.lock", json!({}));
let (at, _) = linear_marker(&mut s, zoomed, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)), "a locked dimension: {at:?}");
run(&mut s, "object.unlockAll", json!({}));
run(&mut s, "select.none", json!({}));
// 2.5 pixels above the curve's top anchor and 1.5 pixels below the end of the extension line
// that starts 4 points above it: on the anchor, linked to the art.
assert_eq!(linear_marker(&mut s, plain, 230.0, 257.5), (Some((pt(230.0, 260.0), 10.0)), vec!["anchor".to_string()]));
// Smart Guides and Snap to Point off: no pull to the dimension's line end, and no labels.
let (at, labels) = linear_marker(&mut s, off, 230.6, 207.4);
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)) && labels.is_empty(), "{at:?} {labels:?}");
let (at, labels) = linear_marker(&mut s, off, 230.1, 260.1);
assert!(at.is_some_and(|(p, _)| p == pt(230.0, 260.0)) && labels.is_empty(), "{at:?} {labels:?}");
// Snap to Point on and Smart Guides off: the line end takes the point, and no label shows.
assert_eq!(linear_marker(&mut s, ViewInfo { snap_to_point: true, ..off }, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec![]));
// A second dimension whose line lies on the bottom edge, from x 425 to x 541.
linear_click(&mut s, plain, 425.0, 260.0);
linear_click(&mut s, plain, 541.0, 358.0);
linear_click(&mut s, plain, 480.0, 440.0);
let second = s.doc().unwrap().selection.objects[0].0;
assert_ne!(second, first);
run(&mut s, "select.none", json!({}));
// A press 1.4 pixels from its line's left end, on the bottom edge, moved 5 pixels: the end is
// picked, and no dimension of the edge is dragged out.
for (kind, x) in [(PointerKind::Move, 426.0), (PointerKind::Down, 426.0), (PointerKind::Drag, 431.0), (PointerKind::Up, 431.0)] {
s.pointer(&PointerEvent::new(kind, x, 441.0), plain).unwrap();
}
linear_click(&mut s, plain, 541.0, 440.0);
linear_click(&mut s, plain, 480.0, 470.0);
let third = s.doc().unwrap().selection.objects[0].0;
assert_ne!(third, second);
let d = recipe(&s, third);
assert!(near(d.a, pt(425.0, 440.0)) && near(d.b, pt(541.0, 440.0)), "{:?} {:?}", d.a, d.b);
// A dimension of the left edge whose line lies 4 points off it, where its extension lines
// start: zoomed in, the end of its line still takes a point 4.7 pixels away.
run(&mut s, "select.none", json!({}));
linear_click(&mut s, plain, 130.0, 358.0);
linear_click(&mut s, plain, 130.0, 440.0);
linear_click(&mut s, plain, 126.0, 400.0);
run(&mut s, "select.none", json!({}));
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
}
/// The page content streams of exported PDF `v`, inflated.
fn pdf_content(v: &Value) -> String {
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
+1
View File
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
craft-eps = { workspace = true }
craft-ps = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
+3 -2
View File
@@ -158,8 +158,9 @@
//! art, the character and paragraph attributes the text document doesn't hold, freeform gradients, gradients
//! along or across a stroke and gradients without stops, with more than 256 stops or without extent
//! as their average color
//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked
//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
+142 -18
View File
@@ -2734,23 +2734,29 @@ fn a_clipping_path_keeps_its_gradient() {
#[test]
fn freeform_gradients_are_written_as_their_average_color() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]);
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings);
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5))));
use vectorcraft_color::gradient::GradientMethod;
// The average of its points' colors, whatever its method.
for method in [GradientMethod::Classic, GradientMethod::Perceptual, GradientMethod::HueClockwise] {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]);
g.method = method;
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENTS], "{method:?}");
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5))), "{method:?}");
}
}
/// A gradient that dithers or mixes perceptually is written as a classic one; a stop linked to a
/// global process color is written as its color; each with a warning.
/// A gradient that dithers is written without its noise; a Perceptual gradient or one mixed around
/// the hue wheel as the stops on its curve; a stop linked to a global process color as its color;
/// each with a warning.
#[test]
fn gradient_options_and_links_the_data_cant_hold_are_reported() {
let mut doc = Document::new(200.0, 100.0);
@@ -2764,7 +2770,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_MIX]);
assert_eq!(out.warnings, [writer::GRADIENT_DITHER]);
// A swatch of such a gradient that nothing uses.
let mut swatch_only = Document::new(200.0, 100.0);
let mut dithered = sunset();
@@ -2773,7 +2779,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
swatches.push(Swatch { name: "Dithered".into(), paint: gradient_paint(dithered, None, None), global: false, spot: false });
swatch_only.swatches = swatches.into();
let out = export_ai_editing(&swatch_only, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_MIX), "{:?}", out.warnings);
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_DITHER), "{:?}", out.warnings);
// A gradient along a stroke: the stroke's outline in its average color.
let mut along = Document::new(200.0, 100.0);
let layer = along.layers[0].id;
@@ -2800,7 +2806,7 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_MIX, writer::STOP_LINKS]);
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL, writer::STOP_LINKS]);
let back = read_back(&doc);
let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None));
@@ -2834,6 +2840,124 @@ fn gradient_options_and_links_the_data_cant_hold_are_reported() {
}
}
/// Do `got`'s colors and opacities lie within 0.03 of `want`'s along the whole ramp?
fn same_curve(want: &Gradient, got: &Gradient, what: &str) {
for k in 0..=100 {
let t = k as f32 / 100.0;
let ((a, ao), (b, bo)) = (want.sample(t), got.sample(t));
let (a, b) = (a.to_rgb(), b.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03) && (ao - bo).abs() < 0.03, "{what} at {t}: {a:?} {ao} vs {b:?} {bo}");
}
}
/// The data's gradients mix their stops' colors directly: a Perceptual gradient swatch is written
/// under its name as a classic gradient of the stops on its curve, no more than the reader reads,
/// and art painted with it uses that definition; both open with the colors they had, with a
/// warning. With Dither, dither's loss is reported as well. A Classic gradient keeps its own stops
/// without either warning.
#[test]
fn perceptual_gradients_are_written_with_the_stops_on_their_curve() {
use vectorcraft_color::gradient::GradientMethod;
let classic = sunset();
let want = Gradient { method: GradientMethod::Perceptual, ..classic.clone() };
// The same stops mixed directly stray from the Perceptual curve.
assert!(
(0..=100).any(|k| {
let t = k as f32 / 100.0;
want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05)
}),
"the methods mix alike"
);
let gradient_names =
|doc: &Document| -> Vec<String> { program(doc).lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).map(String::from).collect() };
let with = |g: &Gradient, swatch: Option<&str>| {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Dusk".into(), paint: gradient_paint(g.clone(), None, None), global: false, spot: false });
doc.swatches = swatches.into();
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g.clone(), None, swatch)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
doc
};
let doc = with(&want, Some("Dusk"));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL]);
let names = gradient_names(&doc);
assert!(names.iter().any(|n| n == "(Dusk)") && !names.iter().any(|n| n == "(Gradient)"), "the art uses the swatch's definition: {names:?}");
let back = read_back(&doc);
let Some(Paint::Gradient(swatch)) = back.swatch("Dusk").map(|s| &s.paint) else { panic!("the swatch is lost") };
assert!(swatch.gradient.method.is_classic());
let written = swatch.gradient.stops.len();
assert!((want.stops.len() + 1..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
same_curve(&want, &swatch.gradient, "the swatch");
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!(fill.gradient.stops.len(), written);
same_curve(&want, &fill.gradient, "the fill");
// Perceptual with Dither: both losses.
let dithered = Gradient { dither: true, ..want.clone() };
let doc = with(&dithered, None);
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_PERCEPTUAL, writer::GRADIENT_DITHER]);
let back = read_back(&doc);
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
same_curve(&want, &fill.gradient, "the dithered fill");
// More stops than the reader reads: the average of its own stops, as a classic gradient's.
for method in [GradientMethod::Perceptual, GradientMethod::HueClockwise] {
let stops = (0..300)
.map(|i| GradientStop::new(i as f32 / 299.0, if i % 2 == 0 { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }))
.collect();
let many = Gradient { method, ..Gradient::new(GradientKind::Linear, stops) };
let doc = with(&many, None);
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_SHAPES), "{method:?}: {:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == writer::GRADIENT_PERCEPTUAL || w == writer::GRADIENT_HUE), "{method:?}: {:?}", out.warnings);
let back = read_back(&doc);
assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5))), "{method:?}");
}
// Classic: its own stops, under the swatch's name, without a warning.
let doc = with(&classic, Some("Dusk"));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let back = read_back(&doc);
let Some(Paint::Gradient(swatch)) = back.swatch("Dusk").map(|s| &s.paint) else { panic!("the swatch is lost") };
assert_eq!(swatch.gradient.stops.len(), classic.stops.len());
let Paint::Gradient(fill) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") };
assert_eq!(fill.gradient.stops.len(), classic.stops.len());
}
/// A gradient mixed around the hue wheel whose stop is linked to a global process color loses the
/// link with its stops on the curve, and says so.
#[test]
fn hue_gradients_report_the_links_their_curve_drops() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false });
doc.swatches = swatches.into();
let mut g = sunset();
g.method = vectorcraft_color::gradient::GradientMethod::HueClockwise;
if let Some(s) = g.stops.first_mut() {
s.set_color(BRAND, Some(("Brand".into(), 1.0)));
}
let n = painted(
&mut doc,
shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)),
vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))],
);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::GRADIENT_HUE, writer::STOP_LINKS]);
}
/// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition
/// would cut its art off at the tile's edge.
#[test]
+3 -1
View File
@@ -37,7 +37,9 @@ pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
#[cfg(test)]
pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name};
pub(super) use paints::{
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
};
#[cfg(test)]
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
+47 -20
View File
@@ -19,8 +19,8 @@ pub(in crate::ai_editing) const GRADIENTS: &str =
pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps";
pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str =
"the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_MIX: &str =
"gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_DITHER: &str = "gradients that dither are written without dither's noise in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_PERCEPTUAL: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
pub(in crate::ai_editing) const GRADIENT_HUE: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
pub(in crate::ai_editing) const CONIC: &str =
"conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps";
@@ -57,13 +57,14 @@ fn writable_gradient(g: &Gradient) -> bool {
g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS
}
/// `g` as the data holds its colors: one mixed around the hue wheel (the data's gradients mix
/// their stops' colors directly) as a classic gradient of the stops on its curve
/// ([`Gradient::as_classic_curve`]), no more than the `.ai` reader reads when it pads
/// ([`GRADIENT_HUE`]); others as they are.
fn hue_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
/// `g` as the data holds its colors: one mixed by the Perceptual method or around the hue wheel
/// (the data's gradients mix their stops' colors directly) as a classic gradient of the stops on
/// its curve in process colors ([`Gradient::as_classic_curve`]), no more than the `.ai` reader
/// reads when it pads ([`GRADIENT_PERCEPTUAL`], [`GRADIENT_HUE`]); a classic one, and one the
/// data can't hold as a gradient ([`writable_gradient`]), as it is.
fn curve_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if !g.method.is_hue() {
if g.method.is_classic() || !writable_gradient(g) {
return Cow::Borrowed(g);
}
let curve = g.as_classic_curve();
@@ -88,6 +89,16 @@ pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl
}
}
/// Is `stop` linked to a global process color of `doc` (one [`Writer::stop_color`] writes as its
/// color, [`STOP_LINKS`])?
fn links_global_process(doc: &vectorcraft_doc::Document, stop: &GradientStop) -> bool {
stop.swatch
.as_deref()
.filter(|n| *n != REGISTRATION)
.and_then(|name| doc.swatch(name))
.is_some_and(|sw| matches!(sw.paint, Paint::Solid { swatch: None, .. }) && !sw.spot && sw.global)
}
/// The stops of `g` in order of their place on the ramp.
fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> {
let mut stops: Vec<&GradientStop> = g.stops.iter().collect();
@@ -100,10 +111,11 @@ impl Writer<'_> {
pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) {
let doc = self.doc;
for sw in doc.swatches_iter() {
// As `swatch_paint` writes it: one mixed around the hue wheel as the stops on its curve,
// and the stops of one that repeats or reflects repeated.
// As `swatch_paint` writes it: one mixed by the Perceptual method or around the hue
// wheel as the stops on its curve, and the stops of one that repeats or reflects
// repeated.
if let Paint::Gradient(g) = &sw.paint
&& let stops = hue_as_stops(&g.gradient)
&& let stops = curve_as_stops(&g.gradient)
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
&& writable_gradient(&gradient)
&& !self.gradients.iter().any(|d| d.name == sw.name)
@@ -165,9 +177,11 @@ impl Writer<'_> {
// The data has no spread: a gradient that repeats or reflects is written with its stops
// repeated over `area` (a conic one, written linear, around its turn).
let mut g: GradientPaint = (**g).clone();
if g.gradient.method.is_hue() {
self.warn(GRADIENT_HUE);
g.gradient = hue_as_stops(&g.gradient).into_owned();
// A gradient written as its average color (a freeform one, or one without stops or with
// more than the reader reads) keeps its own stops.
if !g.gradient.method.is_classic() && writable_gradient(&g.gradient) {
self.warn_curve(&g.gradient);
g.gradient = curve_as_stops(&g.gradient).into_owned();
}
if g.gradient.is_spread() {
self.warn(SPREAD);
@@ -192,6 +206,18 @@ impl Writer<'_> {
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..g }))
}
/// The warnings for gradient `g`, mixed by the Perceptual method or around the hue wheel,
/// written as the stops on its curve ([`curve_as_stops`]): [`GRADIENT_PERCEPTUAL`] or
/// [`GRADIENT_HUE`], and [`STOP_LINKS`] when one of its stops is linked to a global process
/// color (the stops on the curve hold no links).
fn warn_curve(&mut self, g: &Gradient) {
self.warn(if g.method.is_hue() { GRADIENT_HUE } else { GRADIENT_PERCEPTUAL });
let doc = self.doc;
if g.stops.iter().any(|s| links_global_process(doc, s)) {
self.warn(STOP_LINKS);
}
}
/// The fills and strokes of `n` that paint (outline `bp`), their gradients placed
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints, the stops
/// of one that repeats or reflects repeated over the box the stroke paints, miter spikes
@@ -363,8 +389,8 @@ impl Writer<'_> {
/// linear gradient's from the last to the first and a radial one's from the first to the last,
/// `BD`, `%AI5_EndGradient`.
fn gradient_def(&mut self, s: &mut String, d: &GradientDef) {
if d.gradient.dither || !d.gradient.method.is_classic() {
self.warn(GRADIENT_MIX);
if d.gradient.dither {
self.warn(GRADIENT_DITHER);
}
if d.gradient.kind == GradientKind::Conic {
self.warn(CONIC);
@@ -587,16 +613,17 @@ impl Writer<'_> {
/// be written.
pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool {
// A swatch has no placement: one that repeats or reflects holds its stops repeated along
// its vector, and one mixed around the hue wheel the stops on its curve.
// its vector, and one mixed by the Perceptual method or around the hue wheel the stops on
// its curve.
let stops = match &sw.paint {
Paint::Gradient(g) => Some(hue_as_stops(&g.gradient)),
Paint::Gradient(g) => Some(curve_as_stops(&g.gradient)),
_ => None,
};
let unrolled = stops.as_deref().map(|g| g.unrolled_within(crate::import::MAX_GRADIENT_STOPS));
match &sw.paint {
Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => {
if g.gradient.method.is_hue() {
self.warn(GRADIENT_HUE);
if !g.gradient.method.is_classic() {
self.warn_curve(&g.gradient);
}
if g.gradient.is_spread() {
self.warn(SPREAD);
+147
View File
@@ -1413,6 +1413,153 @@ fn names_outside_windows_1252_are_replaced_and_kept_apart() {
assert_eq!(inks(&read), want);
}
/// `doc` written with [`Numbered::take`](super::writer::Numbered::take) numbering names by its
/// counters (`scanned` false) or by searching the names given for each number it tries.
fn export_numbering(doc: &Document, scanned: bool) -> LegacyAiOutput {
let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() };
super::writer::SCANNED_NAMES.with(|s| s.set(scanned));
let out = export_legacy_ai(doc, &o);
super::writer::SCANNED_NAMES.with(|s| s.set(false));
out.unwrap()
}
/// A linear gradient from `color` to white, named `swatch`.
fn gradient_from(color: Color, swatch: Option<&str>) -> Paint {
let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, color), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]);
let mut paint = GradientPaint::new(g);
paint.swatch = swatch.map(String::from);
Paint::Gradient(Box::new(paint))
}
/// A name the counters give is the first free `name 2`, `name 3`… for every order of names, those
/// already numbered (`Sky 2`, `Gradient 2 2`) and the empty name included.
#[test]
fn numbered_names_are_the_first_free_number() {
let bases = ["Gradient", "Gradient 2", "Gradient 3", "Gradient 2 2", "Sky", "Sky 2", "Sky 4", "?", "? 2", ""];
let mut seed = 7u32;
let order: Vec<&str> = (0..3000)
.map(|_| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
bases[(seed >> 16) as usize % bases.len()]
})
.collect();
let names = |scanned: bool| {
super::writer::SCANNED_NAMES.with(|s| s.set(scanned));
let mut numbered = super::writer::Numbered::default();
let names: Vec<String> = order.iter().map(|b| numbered.take((*b).to_string())).collect();
super::writer::SCANNED_NAMES.with(|s| s.set(false));
names
};
let (counted, scanned) = (names(false), names(true));
for (i, (c, s)) in counted.iter().zip(&scanned).enumerate() {
assert_eq!(c, s, "name {i}, {:?}", order[i]);
}
let given: std::collections::HashSet<&String> = counted.iter().collect();
assert_eq!(given.len(), counted.len(), "every name is given once");
}
/// Gradient definitions and spot colors whose names collide are numbered as the file has always
/// numbered them: a gradient's swatch name or `Gradient`, then the first free number, with equal
/// gradients sharing a definition. The whole file is the same either way.
#[test]
fn colliding_gradient_and_spot_names_are_numbered_as_before() {
let mut doc = spots_and_gradient(&["\u{8d64}", "?", "\u{9752}", "? 2"], "Gradient 3");
let layer = doc.layers[0].id;
let swatches = [None, None, Some("Gradient"), None, Some("\u{6e10}"), Some("?"), None, Some("Gradient 2"), Some("")];
for (i, swatch) in swatches.into_iter().enumerate() {
let c = i as f32 / 10.0;
for repeat in 0..2 {
let x = 10.0 + 15.0 * i as f64;
let r = Rect::new(x, 60.0 + 15.0 * f64::from(repeat), x + 10.0, 70.0 + 15.0 * f64::from(repeat));
let n = shape(&mut doc, shapes::rectangle(r), gradient_from(Color::cmyk(c, 1.0 - c, 0.5, 0.0), swatch), Paint::None);
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
}
let out = export_numbering(&doc, false);
let before = export_numbering(&doc, true);
let text = String::from_utf8(out.bytes).unwrap();
assert_eq!(text, String::from_utf8(before.bytes).unwrap());
assert_eq!(out.warnings, before.warnings);
let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect();
let want = [
"(Gradient 3)",
"(Gradient)",
"(Gradient 2)",
"(Gradient 4)",
"(Gradient 5)",
"(?)",
"(? 2)",
"(Gradient 6)",
"(Gradient 2 2)",
"(Gradient 7)",
];
assert_eq!(defined, want);
for name in want {
assert_eq!(text.matches(&format!("1 {name} ")).count(), if name == "(Gradient 3)" { 1 } else { 2 }, "{name}");
}
assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}");
}
/// The time this thread has run, and how it was measured.
fn thread_time() -> (std::time::Duration, &'static str) {
if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) {
return (std::time::Duration::from_nanos(ns), "thread CPU time");
}
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
(START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time")
}
/// The time to write 1,500 objects that each have a gradient of their own and no swatch name,
/// with a few named ones that collide, numbering names by counters and by searching the names
/// given: the median of 7 runs of each, alternating, with the files compared. Run with
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture many_unnamed_gradients`.
#[test]
#[ignore = "timing"]
fn many_unnamed_gradients_are_named_quickly() {
let mut doc = Document::new(1000.0, 1000.0);
let layer = doc.layers[0].id;
let count = 1500u16;
for i in 0..count + 4 {
let swatch = match i {
0 => Some("Gradient 3"),
1 => Some("Gradient"),
2 | 3 => Some("Sky"),
_ => None,
};
let t = f32::from(i) / f32::from(count + 4);
let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40) * 25.0);
let paint = gradient_from(Color::rgb(t, 1.0 - t, (t * 7.0).fract()), swatch);
let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None);
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let mut times = [vec![], vec![]];
let mut files: [Option<Vec<u8>>; 2] = [None, None];
let mut how = "";
for _ in 0..7 {
for (k, scanned) in [false, true].into_iter().enumerate() {
let (start, h) = thread_time();
let out = export_numbering(&doc, scanned);
times[k].push(thread_time().0.saturating_sub(start));
how = h;
let defs = String::from_utf8_lossy(&out.bytes).lines().filter(|l| l.ends_with(" Bd")).count();
assert_eq!(defs, usize::from(count) + 4);
files[k].get_or_insert(out.bytes);
}
}
assert_eq!(files[0], files[1]);
for t in &mut times {
t.sort();
}
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
println!("{} gradient definitions, median of 7 runs ({how}):", count + 4);
println!("| naming | median (ms) | runs (ms) |");
println!("|---|---:|---|");
for (k, label) in ["counters", "search of the names given"].into_iter().enumerate() {
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
}
}
/// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's
/// indexes 6, 4 and 5, and they open as the same presets.
#[test]
+54 -13
View File
@@ -15,6 +15,9 @@ use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPP
thread_local! {
/// How many times [`Writer::coverage`] has worked out an image's coverage on this thread.
pub(super) static COVERAGE_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Whether [`Numbered::take`] numbers names on this thread by searching the names given so
/// far, one number at a time, for each number it tries.
pub(super) static SCANNED_NAMES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel.
@@ -66,6 +69,10 @@ pub(super) struct Writer<'a> {
whole_images: std::collections::HashMap<usize, Arc<Vec<u8>>>,
/// Writing a graph's art with its records: a graph inside it is written as its art.
in_graph: bool,
/// The names of [`Self::gradients`].
gradient_names: Numbered,
/// The names spot colors are written with ([`Self::spot`]).
spot_written: Numbered,
}
impl<'a> Writer<'a> {
@@ -94,6 +101,8 @@ impl<'a> Writer<'a> {
last_coverage: None,
whole_images: std::collections::HashMap::new(),
in_graph: false,
gradient_names: Numbered::default(),
spot_written: Numbered::default(),
}
}
@@ -155,12 +164,7 @@ impl<'a> Writer<'a> {
Some((_, w)) => w.clone(),
None => {
let base = self.latin_name(name, TITLE_AND_COLOR_NAMES);
let mut written = base.clone();
let mut i = 1;
while self.spot_names.iter().any(|(_, w)| *w == written) {
i += 1;
written = format!("{base} {i}");
}
let written = self.spot_written.take(base);
self.spot_names.push((name.to_string(), written.clone()));
written
}
@@ -823,14 +827,8 @@ impl<'a> Writer<'a> {
if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) {
return name.clone();
}
let taken = |n: &str, defs: &[(String, Gradient)]| defs.iter().any(|(m, _)| m == n);
let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES);
let mut name = base.clone();
let mut i = 1;
while taken(&name, &self.gradients) {
i += 1;
name = format!("{base} {i}");
}
let name = self.gradient_names.take(base);
self.gradients.push((name.clone(), g.clone()));
name
}
@@ -1244,3 +1242,46 @@ impl<'a> Writer<'a> {
s.push_str("%AI5_EndRaster\nF\n");
}
}
/// Names kept apart: a name already given is numbered, as the first free `name 2`, `name 3`…
#[derive(Default)]
pub(super) struct Numbered {
taken: std::collections::HashSet<String>,
/// The number to try first for each name already given, after the numbers it was given.
next: std::collections::HashMap<String, usize>,
/// The names given, in order, for [`SCANNED_NAMES`].
#[cfg(test)]
given: Vec<String>,
}
impl Numbered {
/// `base`, or the first free `base 2`, `base 3`… when `base` is taken; it is then taken.
pub(super) fn take(&mut self, base: String) -> String {
#[cfg(test)]
if SCANNED_NAMES.with(std::cell::Cell::get) {
let mut name = base.clone();
let mut i = 1;
while self.given.contains(&name) {
i += 1;
name = format!("{base} {i}");
}
self.given.push(name.clone());
return name;
}
let name = if self.taken.contains(&base) {
// Names are never given back, so every number below `from` is still taken. Of the
// numbers `from..=tries`, at least one is free.
let from = self.next.get(&base).copied().unwrap_or(2);
let tries = from.saturating_add(self.taken.len());
let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries);
self.next.insert(base.clone(), i.saturating_add(1));
format!("{base} {i}")
} else {
base
};
self.taken.insert(name.clone());
#[cfg(test)]
self.given.push(name.clone());
name
}
}
+30 -154
View File
@@ -1,11 +1,9 @@
//! PostScript writing primitives: numbers, strings, paths, the prolog's short operator names, and
//! the data encodings images and embedded data use (ASCII85, run-length, Flate).
use std::fmt::Write;
use std::io::{Read, Write as _};
use vectorcraft_geom::{BezPath, FillRule};
use kurbo::PathEl;
use vectorcraft_geom::{Affine, BezPath, FillRule};
pub(crate) use craft_ps::write::{bytes, deflate, inflate, matrix, num, push_num, push_num_places, push_nums, string, written};
/// The procedures the page uses, in `VCdict`.
pub(crate) const PROLOG: &str = "/VCdict 64 dict def
@@ -21,142 +19,9 @@ VCdict begin
end
";
/// `v` as PostScript writes it: at most four decimals, no trailing zeros (0 when not finite).
pub(crate) fn num(v: f64) -> String {
let mut s = String::new();
push_num(&mut s, v);
s
}
/// Append [`num`]`(v)` to `s`.
pub(crate) fn push_num(s: &mut String, v: f64) {
push_num_places(s, v, 4);
}
/// The value [`num`]`(v)` stands for, as a reader parses it back.
pub(crate) fn written(v: f64) -> f64 {
num(v).parse().unwrap_or(0.0)
}
/// Append `v` to `s` with at most `places` decimals (up to 9), no trailing zeros (0 when not
/// finite).
pub(crate) fn push_num_places(s: &mut String, v: f64, places: u32) {
let places = places.min(9);
let scale = 10f64.powi(places as i32);
// Past where the scaling overflows, values have no fractional digits to round.
let v = if !v.is_finite() {
0.0
} else if (v * scale).is_finite() {
(v * scale).round() / scale
} else {
v
};
if v == v.trunc() && v.abs() < 1e15 {
let _ = write!(s, "{}", v as i64);
return;
}
let start = s.len();
let _ = write!(s, "{v:.*}", places as usize);
let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len();
s.truncate(start + keep);
}
/// `vs` as numbers separated by spaces, then a space.
pub(crate) fn push_nums(s: &mut String, vs: &[f64]) {
for v in vs {
push_num(s, *v);
s.push(' ');
}
}
/// `text` as a PostScript string: `(` `)` `\` escaped, anything outside printable ASCII as octal
/// escapes of its UTF-8 bytes.
pub(crate) fn string(text: &str) -> String {
let mut s = String::with_capacity(text.len() + 2);
s.push('(');
for b in text.bytes() {
match b {
b'(' | b')' | b'\\' => {
s.push('\\');
s.push(char::from(b));
}
0x20..=0x7e => s.push(char::from(b)),
_ => {
let _ = write!(s, "\\{b:03o}");
}
}
}
s.push(')');
s
}
/// `bytes` as a PostScript string: `(` `)` `\` escaped, carriage returns, line feeds and tabs as
/// `\r` `\n` `\t`, other bytes outside printable ASCII as octal escapes.
pub(crate) fn bytes(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() + 2);
s.push('(');
for &b in bytes {
match b {
b'(' | b')' | b'\\' => {
s.push('\\');
s.push(char::from(b));
}
b'\r' => s.push_str("\\r"),
b'\n' => s.push_str("\\n"),
b'\t' => s.push_str("\\t"),
0x20..=0x7e => s.push(char::from(b)),
_ => {
let _ = write!(s, "\\{b:03o}");
}
}
}
s.push(')');
s
}
/// A matrix operand `[a b c d e f]`.
pub(crate) fn matrix(a: Affine) -> String {
let mut s = String::from("[");
push_nums(&mut s, &a.as_coeffs());
s.pop();
s.push(']');
s
}
/// Append path `bp` (`m`, `l`, `c`, `h`; quadratics raised to cubics), one segment a line.
/// Append path `bp` using the short operators defined by our `VCdict` prolog.
pub(crate) fn push_path(s: &mut String, bp: &BezPath) {
let mut last = kurbo::Point::ZERO;
let mut start = kurbo::Point::ZERO;
for el in bp.elements() {
match *el {
PathEl::MoveTo(p) => {
push_nums(s, &[p.x, p.y]);
s.push_str("m\n");
(last, start) = (p, p);
}
PathEl::LineTo(p) => {
push_nums(s, &[p.x, p.y]);
s.push_str("l\n");
last = p;
}
PathEl::QuadTo(a, p) => {
let c1 = last + (a - last) * (2.0 / 3.0);
let c2 = p + (a - p) * (2.0 / 3.0);
push_nums(s, &[c1.x, c1.y, c2.x, c2.y, p.x, p.y]);
s.push_str("c\n");
last = p;
}
PathEl::CurveTo(a, b, p) => {
push_nums(s, &[a.x, a.y, b.x, b.y, p.x, p.y]);
s.push_str("c\n");
last = p;
}
PathEl::ClosePath => {
s.push_str("h\n");
last = start;
}
}
}
craft_ps::write::push_path(s, bp, craft_ps::write::PathOps::SHORT);
}
/// The fill operator for `rule`.
@@ -197,25 +62,36 @@ pub(crate) fn ascii85_decode_within(text: &str, max: usize) -> Option<Vec<u8>> {
/// Run-length encoding (PackBits: what PostScript's `RunLengthDecode` reads), shared with TIFF.
pub(crate) use vectorcraft_render::encode::tiff::packbits;
/// `data` compressed for `FlateDecode` (zlib).
pub(crate) fn deflate(data: &[u8]) -> Vec<u8> {
let mut e = flate2::write::ZlibEncoder::new(Vec::with_capacity(data.len() / 2), flate2::Compression::default());
// Writing to a Vec doesn't fail.
let _ = e.write_all(data);
e.finish().unwrap_or_default()
}
/// zlib `data` inflated, when it is valid and at most `max` bytes.
pub(crate) fn inflate(data: &[u8], max: u64) -> Option<Vec<u8>> {
let mut out = vec![];
flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).ok()?;
(out.len() as u64 <= max).then_some(out)
}
#[cfg(test)]
mod tests {
use super::{ascii85, ascii85_decode, num, push_num_places};
#[test]
fn shared_writer_preserves_vcdict_path_and_operands() {
let mut path = vectorcraft_geom::BezPath::new();
path.move_to((1.0, 2.0));
path.line_to((3.0, 4.0));
path.close_path();
let mut output = String::new();
super::push_path(&mut output, &path);
assert_eq!(output, "1 2 m\n3 4 l\nh\n");
assert_eq!(super::matrix(vectorcraft_geom::Affine::IDENTITY), "[1 0 0 1 0 0]");
assert_eq!(super::fill_op(vectorcraft_geom::FillRule::EvenOdd), "f*\n");
assert_eq!(super::clip_op(vectorcraft_geom::FillRule::NonZero), "W\n");
}
#[test]
fn shared_writer_keeps_large_integer_zeroes_and_bounded_flate() {
let mut output = String::new();
push_num_places(&mut output, 1e15, 0);
assert_eq!(output, "1000000000000000");
let packed = super::deflate(b"EPS payload");
assert_eq!(super::inflate(&packed, 11).as_deref(), Some(&b"EPS payload"[..]));
assert!(super::inflate(&packed, 10).is_none());
assert_eq!(super::inflate(&packed, u64::MAX).as_deref(), Some(&b"EPS payload"[..]));
assert!(super::inflate(&packed[..packed.len() - 1], 11).is_none());
}
#[test]
fn ascii85_first_line_never_starts_with_percent() {
let data = [0x0C, 0x80, 0, 0, 1, 2, 3, 4];
+14
View File
@@ -1555,6 +1555,20 @@ fn headless_backend_methods() {
let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap();
assert_eq!(selected["tool"], tool.id);
}
// The Trim at Crossings Tool is listed once, in the Scissors tool's group after the Knife.
let trim = vectorcraft_tools::addons::trim::ID;
let with_trim: Vec<_> =
groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == trim)).collect();
assert_eq!(with_trim.len(), 1, "{trim} is in one group");
let ids: Vec<_> = with_trim[0].iter().map(|entry| entry["id"].clone()).collect();
let knife = ids.iter().position(|id| *id == "knife").expect("the Knife in the same group");
assert!(ids.contains(&json!("scissors")), "the Scissors tool's group: {ids:?}");
assert_eq!(ids.get(knife + 1), Some(&json!(trim)));
assert_eq!(ids.iter().filter(|id| **id == trim).count(), 1);
let entry = with_trim[0].iter().find(|entry| entry["id"] == trim).unwrap();
assert_eq!(entry["label"], "Trim at Crossings Tool");
assert!(entry["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim);
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
+1 -1
View File
@@ -87,7 +87,7 @@ pub use import::{
pub use pages::reads_of;
pub use pages::{
IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info,
is_postscript, open_pdf,
is_postscript, open_pdf, read_illustrator_data_without_pdf_part,
};
pub use piece_info::{PRIVATE_CHUNK, PrivateData};
pub use post::{THUMBNAIL_SIZE, Thumbnail};
+41 -18
View File
@@ -502,25 +502,42 @@ pub struct IllustratorData {
/// objects, and only the private data streams are read, with the same limits. `None` when the
/// file itself can't be opened, or as for [`illustrator_data`].
pub fn illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Option<IllustratorData> {
let pdf = open_structural_with_options(bytes, password, &open_options()).ok()?;
let data = private_data(&pdf)?;
let page = pdf.pages().first()?;
read_illustrator_data_without_pdf_part(bytes, password).ok().flatten()
}
/// [`illustrator_data_without_pdf_part`], with why the private data can't be read: `Ok(None)`
/// when the file can't be opened or has no private data, `Err` (for a note, such as "it is larger
/// than 256 MB") when it has private data that can't be read.
pub fn read_illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Result<Option<IllustratorData>, String> {
let Ok(pdf) = open_structural_with_options(bytes, password, &open_options()) else { return Ok(None) };
let Some(data) = read_private_data(&pdf)? else { return Ok(None) };
let Some(page) = pdf.pages().first() else { return Ok(None) };
// (The page transform is in points: it applies the `UserUnit`.)
let trim = frame(page, CropTo::Trim).1;
Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) })
Ok(Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) }))
}
/// The private data of `pdf`'s first page, as [`illustrator_data`] reads it.
fn private_data(pdf: &Pdf) -> Option<Vec<u8>> {
let page = pdf.pages().first()?;
let private = page.raw().get::<Dict<'_>>(b"PieceInfo")?.get::<Dict<'_>>(PRIVATE_DATA_OWNER)?.get::<Dict<'_>>(b"Private")?;
read_private_data(pdf).ok().flatten()
}
/// [`private_data`], with why a private data stream can't be read ([`inflated`]).
fn read_private_data(pdf: &Pdf) -> Result<Option<Vec<u8>>, String> {
let Some(private) = pdf
.pages()
.first()
.and_then(|page| page.raw().get::<Dict<'_>>(b"PieceInfo")?.get::<Dict<'_>>(PRIVATE_DATA_OWNER)?.get::<Dict<'_>>(b"Private"))
else {
return Ok(None);
};
let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" };
let mut data = vec![];
for n in 1..=100_000u32 {
let Some(stream) = private.get::<Stream<'_>>(format!("{key}{n}").as_bytes()) else { break };
data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len())?);
data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len()).map_err(|why| why.to_string())?);
}
(!data.is_empty()).then_some(data)
Ok((!data.is_empty()).then_some(data))
}
/// Does the PDF's first page carry an editor's copy of the art: a PDF-compatible `.ai`
@@ -538,10 +555,12 @@ fn has_private_data_keys(pdf: &Pdf) -> bool {
/// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's
/// `decoded()`, which has no limit, so a stream of zeros can't grow to the size of the memory. Only a
/// stream that is plain or only deflated is read (the private data is no other), without decode
/// parameters; else, or when it is larger once decoded, `None`. A filter the reader doesn't know
/// counts as another filter.
fn inflated(stream: &Stream<'_>, most: usize) -> Option<Vec<u8>> {
/// parameters; else, or when it is larger once decoded, `Err` with why. A filter the reader
/// doesn't know counts as another filter.
fn inflated(stream: &Stream<'_>, most: usize) -> Result<Vec<u8>, String> {
use std::io::Read;
let unread = || "it is stored in a form that isn't read".to_string();
let too_large = || format!("it is larger than {} MB", MAX_PRIVATE >> 20);
let dict = stream.dict();
let named = |key: &[u8]| match dict.get::<Object<'_>>(key) {
None | Some(Object::Null(_)) => Some(0),
@@ -555,24 +574,28 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Option<Vec<u8>> {
Some(_) => true,
};
if params(b"DecodeParms") || params(b"DP") {
return None;
return Err(unread());
}
let filters = stream.filters();
// (The reader leaves out the filters it doesn't know.)
if named(b"Filter")?.max(named(b"F")?) != filters.len() {
return None;
if named(b"Filter").zip(named(b"F")).is_none_or(|(a, b)| a.max(b) != filters.len()) {
return Err(unread());
}
let raw = stream.raw_data();
let mut out = vec![];
let limit = u64::try_from(most).ok()?.checked_add(1)?;
let limit = u64::try_from(most).ok().and_then(|m| m.checked_add(1)).ok_or_else(too_large)?;
match filters.as_slice() {
[] if raw.len() <= most => out.extend_from_slice(&raw),
[] => return Err(too_large()),
[craft_pdf::syntax::Filter::FlateDecode] => {
flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).ok()?;
flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).map_err(|_| "its zlib compression is damaged".to_string())?;
}
_ => return None,
_ => return Err(unread()),
}
(out.len() <= most).then_some(out)
if out.len() > most {
return Err(too_large());
}
Ok(out)
}
/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)?
+9
View File
@@ -446,7 +446,16 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() {
let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&first, &two], "", None);
assert!(illustrator_data(&pdf, None).is_none(), "{odd}");
assert!(illustrator_data_without_pdf_part(&pdf, None).is_none(), "{odd}");
let why = read_illustrator_data_without_pdf_part(&pdf, None);
assert_eq!(why, Err("it is stored in a form that isn't read".to_string()), "{odd}");
}
// Damaged zlib data, and a file without private data or that isn't a PDF.
let damaged = stream("/Filter /FlateDecode", "not zlib");
let pdf = pdf_with_catalog(std::slice::from_ref(&page), &[&damaged, &two], "", None);
assert_eq!(read_illustrator_data_without_pdf_part(&pdf, None), Err("its zlib compression is damaged".to_string()));
let bare = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "")], &[], "", None);
assert_eq!(read_illustrator_data_without_pdf_part(&bare, None), Ok(None));
assert_eq!(read_illustrator_data_without_pdf_part(b"not a pdf", None), Ok(None));
}
/// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept
+13
View File
@@ -232,3 +232,16 @@ fn lzw_strips_read_back_as_weezl_reads_them() {
assert!(same >= weezl.len().min(4_300), "{} bytes: the same for {same}", strip.len());
}
}
#[test]
fn shared_packbits_preserves_packet_bytes_and_append_contract() {
let mut out = vec![42];
t::packbits(b"aabbccc", &mut out);
assert_eq!(out, [42, 3, b'a', b'a', b'b', b'b', 254, b'c']);
let before = out.clone();
t::packbits(&[], &mut out);
assert_eq!(out, before);
let mut run = vec![];
t::packbits(&[7; 129], &mut run);
assert_eq!(run, [129, 7, 0, 7]);
}
+1 -24
View File
@@ -282,30 +282,7 @@ fn resolution(ppi: f64) -> Values {
/// `data` run-length encoded (PackBits: what TIFF's compression 32773 and PostScript's
/// `RunLengthDecode` read), without an end marker.
pub fn packbits(data: &[u8], out: &mut Vec<u8>) {
let mut i = 0;
while i < data.len() {
let Some(&b) = data.get(i) else { break };
let run = data.get(i..).map_or(1, |rest| rest.iter().take(128).take_while(|x| **x == b).count());
if run >= 3 {
out.push((257 - run) as u8);
out.push(b);
i += run;
continue;
}
// Literal bytes up to the next run of three.
let mut j = i;
while j < data.len() && j - i < 128 {
let three = data.get(j..j + 3).is_some_and(|w| w[0] == w[1] && w[1] == w[2]);
if three {
break;
}
j += 1;
}
let j = j.max(i + 1).min(data.len());
out.push((j - i - 1) as u8);
out.extend(data.get(i..j).unwrap_or_default());
i = j;
}
craft_stream_codecs::runlength::encode_packbits_into(data, out);
}
/// The TIFF options of a raster export.
+4 -2
View File
@@ -791,9 +791,11 @@ pub(crate) fn three_d_art_bounds(symbols: &SymbolBoxes, art: &Node) -> Option<Re
pieces(symbols, &art)
}
/// `b`, the bounds of what `n` draws, grown by how far `n`'s own raster effects paint past it.
/// `b`, the bounds of what `n` draws, grown by how far `n`'s own raster effects paint past it: those
/// around its whole art ([`effects::outer_effects`]), as the copies of a Transform effect that carry
/// the ones listed before it are measured in `b`.
pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> Rect {
let o = outset(symbols, &n.appearance.effects, b);
let o = outset(symbols, effects::outer_effects(n), b);
b.inflate(o, o)
}
+33 -13
View File
@@ -142,12 +142,15 @@ impl Renderer {
}
// One paint box for the line and the heads, so a gradient runs on into the heads.
let paint_bounds = bounds.inflate(st.width / 2.0, st.width / 2.0);
// A width profile's outline is fitted through samples, and fitted again differently when
// it is outlined near the view only: its curves are drawn as they are.
let fine = st.profile.is_none() && crate::stroke::fine(f.view * xf, f.px);
if let Some(g) = st.path_gradient() {
self.fill_path_gradient(ctx, f, bp, rule, st, chars, &pieces, width, &g.gradient);
self.fill_path_gradient(ctx, f, bp, rule, st, chars, &pieces, width, fine, &g.gradient);
} else {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width, fine) {
Some(o) => o,
None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)),
None => Arc::new(uncached_outline(&pieces.line, st, width, f.px * 0.25, fine)),
};
// Miters, caps and heads can reach past the paint box: a paint drawn as pixels covers
// them too.
@@ -191,7 +194,8 @@ impl Renderer {
/// piece clips the slices, grown a pixel into each other and each replacing what it covers, so
/// neighbours meet without seams and translucent colours paint once. The slices of a stroke
/// of `self.cur` are kept in `stroke_slices`, and a moved copy of the object draws the slices
/// made before it moved, moved by the same offset ([`Self::moved_slices`]).
/// made before it moved, moved by the same offset ([`Self::moved_slices`]). `fine` is passed on
/// to [`Self::cached_stroke`].
#[allow(clippy::too_many_arguments)]
fn fill_path_gradient(
&mut self,
@@ -203,6 +207,7 @@ impl Renderer {
chars: Option<(&Arc<TextGeom>, usize)>,
pieces: &effects::stroke::StrokePieces,
width: f64,
fine: bool,
g: &vectorcraft_color::Gradient,
) {
let level = (f.px * 0.25).log2().floor() as i32;
@@ -255,9 +260,9 @@ impl Renderer {
}
None => (make(), kurbo::Vec2::ZERO),
};
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) {
let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width, fine) {
Some(o) => o,
None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)),
None => Arc::new(uncached_outline(&pieces.line, st, width, f.px * 0.25, fine)),
};
ctx.set_fill_rule(peniko::Fill::NonZero);
for clip in std::iter::once(&*line).chain(pieces.heads.iter().map(|h| &h.outline)) {
@@ -293,6 +298,9 @@ impl Renderer {
/// tolerance (vello's 0.25 device px) is bucketed to powers of two, never coarser than needed,
/// so zooming reuses outlines until the level changes. Other strokes aren't cached: for them
/// this returns `None`. `line` is the line of `st` along `path` ([`effects::stroke::stroke_pieces`]).
/// With `fine` ([`crate::stroke::fine`]) a wide stroke's long curves are drawn as lines
/// ([`crate::stroke::wide`]); the keys keep the two kinds of outline apart.
#[allow(clippy::too_many_arguments)]
fn cached_stroke(
&mut self,
f: &Frame,
@@ -301,11 +309,16 @@ impl Renderer {
line: &BezPath,
st: &StrokeLayer,
width: f64,
fine: bool,
) -> Option<Arc<BezPath>> {
let level = (f.px * 0.25).log2().floor() as i32;
let expand = || Arc::new(crate::stroke::outline(line, st, width, 2f64.powi(level)));
let tol = 2f64.powi(level);
// The keys' last field: the tolerance level, and whether long curves are drawn as lines.
let slot = level.saturating_mul(2).saturating_add(i32::from(fine));
let refined = |outline: BezPath| if fine { crate::stroke::wide(outline, width, tol) } else { outline };
let expand = || Arc::new(refined(crate::stroke::outline(line, st, width, tol)));
if let Some((g, run)) = chars {
let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), level);
let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), slot);
if let Some((kept, outline)) = self.char_strokes.get(&key, self.stamp)
&& Arc::ptr_eq(kept, g)
{
@@ -316,7 +329,7 @@ impl Renderer {
return Some(outline);
}
let node = self.cur.clone().filter(|n| owns_stroke(n, st))?;
let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), level);
let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), slot);
let v = f.visible;
let holds = |crop: Option<Rect>| crop.is_none_or(|r| r.x0 <= v.x0 && r.y0 <= v.y0 && r.x1 >= v.x1 && r.y1 >= v.y1);
if let Some(e) = self.strokes.get_mut(&key)
@@ -329,7 +342,7 @@ impl Renderer {
// Under its object's id, the stroke's place and the outline's width and tolerance, the key
// of the stroke's latest outline is kept, except for art made again in every frame.
let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st)));
let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level));
let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), slot));
let own = moved.is_some() && self.own_path(&node, path);
if let Some(mk) = moved
&& let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v)
@@ -342,7 +355,6 @@ impl Renderer {
// A long stroke is outlined only in and around the view, with a margin of the view's
// own size on each side. Width profiles keep their positions on the whole path.
let region = v.inflate(v.width(), v.height());
let tol = 2f64.powi(level);
if crops()
&& line.elements().len() > CROP_ELEMENTS
&& st.dash.is_none()
@@ -364,7 +376,7 @@ impl Renderer {
&& st.profile.is_none()
&& let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol)
{
let outline = Arc::new(outline);
let outline = Arc::new(refined(outline));
self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved);
return Some(outline);
}
@@ -372,7 +384,7 @@ impl Renderer {
.then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width))
.flatten();
let (outline, crop) = match cropped {
Some(part) => (Arc::new(crate::stroke::outline(&part, st, width, tol)), Some(region)),
Some(part) => (Arc::new(refined(crate::stroke::outline(&part, st, width, tol))), Some(region)),
None => (expand(), None),
};
self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved);
@@ -619,6 +631,14 @@ fn crops() -> bool {
true
}
/// The outline of the line `line` of stroke `st` at `width` and tolerance `tol`, for a stroke that
/// [`Renderer::cached_stroke`] does not keep; with `fine`, its long curves drawn as lines
/// ([`crate::stroke::wide`]).
fn uncached_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, fine: bool) -> BezPath {
let outline = crate::stroke::outline(line, st, width, tol);
if fine { crate::stroke::wide(outline, width, tol) } else { outline }
}
/// How far stroke `st` at `width` can paint from its path, at a join or a cap, with two output
/// pixels (`px`) and the outline's tolerance `tol` added.
pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 {
+303 -1
View File
@@ -1,6 +1,8 @@
//! Raster-only stroke fitting: preserve thin curved bands through fill flattening.
//! Raster-only stroke fitting: preserve thin curved bands through fill flattening, and draw the
//! rims of wide curved strokes as lines centered on their curves.
use crate::effects;
use crate::kurbo::{Affine, CubicBez, Line, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point, QuadBez, Vec2};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_geom::BezPath;
@@ -19,3 +21,303 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
vectorcraft_geom::flatten(outline.iter(), fine, |el| flat.push(el));
flat
}
/// Strokes at least this many tolerances wide (8 device pixels at a tolerance of 0.25 px) have
/// their long curves drawn as lines by [`wide`].
const WIDE: f64 = 32.0;
/// A curve of a wide stroke's outline is drawn as lines when its control points span at least this
/// many tolerances (32 device pixels at 0.25 px) across or down.
const SPAN: f64 = 128.0;
/// The chords [`wide`] draws a curve with lie within about this many tolerances of it, before
/// their ends are moved out.
const CHORD: f64 = 0.8;
/// The most lines [`wide`] draws one outline's curves with. An outline that would take more is
/// drawn as it is.
const MAX_LINES: usize = 1 << 20;
/// Two curves meet smoothly when the sine of the angle between their tangents where they meet is
/// at most this.
const SMOOTH: f64 = 0.01;
/// Whether an outline made in the space `m` maps to device pixels, with a tolerance of at most a
/// quarter of `px` (the size of a device pixel in that space, [`crate::frame::Frame::px`]), stays
/// within that tolerance on the device: whether `m` stretches no length by more than `1 / px`.
/// `false` for a transform that collapses or isn't finite.
pub(crate) fn fine(m: Affine, px: f64) -> bool {
let [a, b, c, d, _, _] = m.as_coeffs();
let (sum, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
// The largest singular value of the linear part.
let most = ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt();
det != 0.0 && most.is_finite() && px.is_finite() && px > 0.0 && most * px <= 1.0 + 1e-9
}
/// `outline`, the outline of a stroke `width` wide made at tolerance `tol`, with its long curves
/// ([`SPAN`]) drawn as lines that lie within about half of `tol` on either side of the curve, when
/// the stroke is at least [`WIDE`] tolerances wide. Vello draws a curve with chords that all lie
/// on its inner side, up to 0.25 device pixels in, which leaves a wide stroke's rims too light
/// outside and too dark inside. Here each line end is moved out by half the gap between the curve
/// and its chords, and the lines cross the curve. Where two such curves meet smoothly the shared
/// end moves too; elsewhere (a corner, a line, a short curve) the end stays on the curve and the
/// first or last line is half as long. Narrower strokes, outlines with no long curve and outlines
/// that would take more than [`MAX_LINES`] lines are returned as they are.
pub(crate) fn wide(outline: BezPath, width: f64, tol: f64) -> BezPath {
if !(tol > 0.0 && tol.is_finite() && width >= tol * WIDE) {
return outline;
}
lines(&outline, tol).unwrap_or(outline)
}
/// One subpath: where it starts, its segments, each with the most steps it is drawn with as lines
/// ([`steps`]; 0: drawn as it is), and whether it is closed.
struct Sub {
start: Point,
segs: Vec<(PathSeg, usize)>,
closed: bool,
}
/// `path` with its long curves drawn as lines ([`wide`]); `None` when it has no long curve, would
/// take more than [`MAX_LINES`] lines, or does not start each subpath with a move.
fn lines(path: &BezPath, tol: f64) -> Option<BezPath> {
let chord = tol * CHORD;
let subs = subpaths(path.elements(), tol, chord)?;
let mut total = 0usize;
for (_, steps) in subs.iter().flat_map(|s| &s.segs) {
if *steps > 0 {
total = total.saturating_add(steps.saturating_add(2));
}
}
if total == 0 || total > MAX_LINES {
return None;
}
let mut out = BezPath::new();
for sub in &subs {
draw_sub(&mut out, sub, chord);
}
Some(out)
}
/// The subpaths of `els`, each segment with its steps ([`steps`]). A close adds a line back to the
/// start when the subpath ends elsewhere. `None` when a segment comes before any move or after a
/// close without a move.
fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option<Vec<Sub>> {
let mut subs: Vec<Sub> = Vec::new();
for el in els {
if let PathEl::MoveTo(p) = *el {
subs.push(Sub { start: p, segs: Vec::new(), closed: false });
continue;
}
let sub = subs.last_mut()?;
if sub.closed {
return None;
}
let last = sub.segs.last().map_or(sub.start, |(s, _)| s.end());
let seg = match *el {
PathEl::LineTo(p) => PathSeg::Line(Line::new(last, p)),
PathEl::QuadTo(a, b) => PathSeg::Quad(QuadBez::new(last, a, b)),
PathEl::CurveTo(a, b, c) => PathSeg::Cubic(CubicBez::new(last, a, b, c)),
PathEl::ClosePath | PathEl::MoveTo(_) => {
if last != sub.start {
sub.segs.push((PathSeg::Line(Line::new(last, sub.start)), 0));
}
sub.closed = true;
continue;
}
};
sub.segs.push((seg, steps(seg, tol, chord)));
}
Some(subs)
}
/// The cubic that draws curve `seg`; `None` for a line.
fn cubic(seg: PathSeg) -> Option<CubicBez> {
match seg {
PathSeg::Cubic(c) => Some(c),
PathSeg::Quad(q) => Some(q.raise()),
PathSeg::Line(_) => None,
}
}
/// How many equal steps of its parameter keep the chords of curve `seg` within `chord` of it (by
/// the second differences of its control points), when its control points span at least [`SPAN`]
/// times `tol`; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a curve
/// that would take more than [`MAX_LINES`] steps.
fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize {
let Some(c) = cubic(seg) else { return 0 };
let pts = [c.p0, c.p1, c.p2, c.p3];
if !pts.iter().all(|p| p.is_finite()) {
return 0;
}
let (lo, hi) = pts.iter().fold((Point::new(f64::INFINITY, f64::INFINITY), Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), p| {
(Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))
});
let span = (hi.x - lo.x).max(hi.y - lo.y);
if !span.is_finite() || span < tol * SPAN {
return 0;
}
let second = |a: Point, b: Point, c: Point| (a.to_vec2() - b.to_vec2() * 2.0 + c.to_vec2()).hypot();
let bend = second(c.p0, c.p1, c.p2).max(second(c.p1, c.p2, c.p3));
let n = (0.75 * bend / chord).sqrt().ceil().max(1.0);
if !n.is_finite() || n > MAX_LINES as f64 {
return 0;
}
n as usize
}
/// The direction curve `c` leaves its start in, or `None` when all its points are at its start.
fn start_tangent(c: &CubicBez) -> Option<Vec2> {
[c.p1, c.p2, c.p3].into_iter().map(|p| p - c.p0).find(|v| v.hypot2() > 0.0)
}
/// The direction curve `c` reaches its end in, or `None` when all its points are at its end.
fn end_tangent(c: &CubicBez) -> Option<Vec2> {
[c.p2, c.p1, c.p0].into_iter().map(|p| c.p3 - p).find(|v| v.hypot2() > 0.0)
}
/// How many pieces of a curve [`params`] measures its bending on.
const SAMPLES: usize = 32;
/// The parameters curve `c` has its line ends at, and whether its first and its last step are
/// halves. Each step holds an equal share of the curve's bending (the integral of the square root
/// of its curvature along it), and there are as many as keep each chord within about `chord` of the
/// curve, at most `most` (its equal steps, [`steps`]). The steps are equal when the bending can't
/// be measured (a cusp, or a point that isn't finite) or is 0. The first or last step is halved
/// when that end stays on the curve (`pin_start`, `pin_end`); a curve of one step is then drawn
/// in two halves.
fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) -> (Vec<f64>, (bool, bool)) {
let (d1, d2) = (c.deriv(), c.deriv().deriv());
let bend = |u: f64| {
let (v, a) = (d1.eval(u).to_vec2(), d2.eval(u).to_vec2());
(v.cross(a).abs() / v.hypot()).sqrt()
};
let mut sums = [0.0; SAMPLES + 1];
let mut before = bend(0.0);
for j in 1..=SAMPLES {
let here = bend(j as f64 / SAMPLES as f64);
sums[j] = sums[j - 1] + (before + here) / 2.0;
before = here;
}
let total = sums[SAMPLES];
let most = most.max(1);
let n = if total.is_finite() && total > 0.0 { ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most) } else { most };
// The parameter at which a share `s` (0 to 1) of the bending lies before it.
let at = |s: f64| -> f64 {
if !(total.is_finite() && total > 0.0) {
return s;
}
let want = s * total;
let j = sums.partition_point(|&x| x <= want).clamp(1, SAMPLES);
let (lo, hi) = (sums[j - 1], sums[j]);
let part = if hi > lo { ((want - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 };
(j as f64 - 1.0 + part) / SAMPLES as f64
};
if n == 1 && (pin_start || pin_end) {
return (vec![0.0, at(0.5), 1.0], (true, true));
}
let h = 1.0 / n as f64;
let mut t = Vec::with_capacity(n + 3);
t.push(0.0);
if pin_start {
t.push(at(h / 2.0));
}
t.extend((1..n).map(|k| at(k as f64 * h)));
if pin_end {
t.push(at(1.0 - h / 2.0));
}
t.push(1.0);
(t, (pin_start, pin_end))
}
/// How far the curve `c` lies from the chord between parameters `a` and `b`, at its parameter
/// midway: the curve's point there minus the chord's middle.
fn bulge(c: &CubicBez, a: f64, b: f64) -> Vec2 {
c.eval((a + b) / 2.0) - c.eval(a).midpoint(c.eval(b))
}
/// A curve of a subpath drawn as lines: the curve, its line ends' parameters, whether its first and
/// its last step are halves ([`params`]), and how far the curve lies from its first and last
/// chords ([`bulge`]).
struct Drawn {
curve: CubicBez,
t: Vec<f64>,
halves: (bool, bool),
first: Vec2,
last: Vec2,
}
/// Draws `sub` into `out`, its curves with steps as lines ([`wide`]) with chords within about
/// `chord` of them, and its other segments as they are.
fn draw_sub(out: &mut BezPath, sub: &Sub, chord: f64) {
let n = sub.segs.len();
let curve = |i: usize| sub.segs.get(i).filter(|(_, steps)| *steps > 0).and_then(|(s, _)| cubic(*s));
// Whether segment `i` starts where the one before it ends, both drawn as lines and meeting
// smoothly: there the shared end moves off the curve with both.
let smooth: Vec<bool> = (0..n)
.map(|i| {
let before = if i == 0 { sub.closed.then(|| n - 1) } else { Some(i - 1) };
let (Some(a), Some(b)) = (before.and_then(curve), curve(i)) else { return false };
match (end_tangent(&a), start_tangent(&b)) {
(Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(),
_ => false,
}
})
.collect();
// Whether segment `i` ends where the next one starts, as above; the last one's next is the
// first, which starts smoothly only on a closed subpath.
let meets = |i: usize| smooth.get((i + 1) % n).copied().unwrap_or(false);
let drawn: Vec<Option<Drawn>> = (0..n)
.map(|i| {
let c = curve(i)?;
let steps = sub.segs.get(i).map_or(1, |(_, s)| *s);
let (t, halves) = params(&c, steps, chord, !smooth.get(i).copied().unwrap_or(false), !meets(i));
let (first, last) = match (t.first().zip(t.get(1)), t.len().checked_sub(2).and_then(|k| t.get(k).zip(t.last()))) {
(Some((a, b)), Some((c2, d))) => (bulge(&c, *a, *b), bulge(&c, *c2, *d)),
_ => (Vec2::ZERO, Vec2::ZERO),
};
Some(Drawn { curve: c, t, halves, first, last })
})
.collect();
// How far the start of segment `i` moves: half the curve's gap from the chords on either side.
let moved = |i: usize| -> Vec2 {
if !smooth.get(i).copied().unwrap_or(false) {
return Vec2::ZERO;
}
let before = if i == 0 { n - 1 } else { i - 1 };
match (drawn.get(before).and_then(Option::as_ref), drawn.get(i).and_then(Option::as_ref)) {
(Some(a), Some(b)) => (a.last + b.first) / 4.0,
_ => Vec2::ZERO,
}
};
out.move_to(sub.start + moved(0));
for (i, (seg, _)) in sub.segs.iter().enumerate() {
let end = seg.end() + moved((i + 1) % n);
match (drawn.get(i).and_then(Option::as_ref), seg) {
(Some(d), _) => draw_lines(out, d, end),
(None, PathSeg::Line(_)) => out.line_to(end),
(None, PathSeg::Quad(q)) => out.quad_to(q.p1, end),
(None, PathSeg::Cubic(c)) => out.curve_to(c.p1, c.p2, end),
}
}
if sub.closed {
out.close_path();
}
}
/// Draws curve `d` into `out` as lines to its inner line ends, each moved out by half the curve's
/// gap from the chords beside it, and a line to `end`. Beside a halved step, which lies a quarter
/// as far from the curve, the whole step's gap is used: half the other chord's gap, or the two
/// halves' gaps together.
fn draw_lines(out: &mut BezPath, d: &Drawn, end: Point) {
let t = &d.t;
let last = t.len().saturating_sub(2);
for k in 1..t.len().saturating_sub(1) {
let (Some(&a), Some(&u), Some(&b)) = (t.get(k - 1), t.get(k), t.get(k + 1)) else { continue };
let (before, after) = (bulge(&d.curve, a, u), bulge(&d.curve, u, b));
let shift = match (d.halves.0 && k == 1, d.halves.1 && k == last) {
(true, true) => before + after,
(true, false) => after / 2.0,
(false, true) => before / 2.0,
(false, false) => (before + after) / 4.0,
};
out.line_to(d.curve.eval(u) + shift);
}
out.line_to(end);
}
+1
View File
@@ -15,6 +15,7 @@ mod cmykblend;
mod colorize;
mod colrglyphs;
mod container;
mod curvedstrokeedges;
mod dither;
pub(super) mod fontchange;
mod freeform;
@@ -0,0 +1,248 @@
//! Wide strokes along curves: both rims cover their edge pixels close to the exact coverage of
//! the curves they follow, and narrow strokes, short curves and straight outlines are drawn as
//! they were.
use super::*;
use crate::stroke::{fine, wide};
use vectorcraft_doc::{AppearanceItem, StrokeGradientMode, StrokeLayer};
/// The share of pixel (`px`, `py`) inside the circle at `c` with radius `r`, integrated over 512
/// columns of the pixel.
fn disc_coverage(c: kurbo::Point, r: f64, px: u32, py: u32) -> f64 {
const COLUMNS: u32 = 512;
let (top, bottom) = (f64::from(py), f64::from(py) + 1.0);
(0..COLUMNS)
.map(|k| {
let x = f64::from(px) + (f64::from(k) + 0.5) / f64::from(COLUMNS);
let u = (x - c.x) / r;
if u.abs() >= 1.0 {
return 0.0;
}
let h = r * (1.0 - u * u).sqrt();
((c.y + h).min(bottom) - (c.y - h).max(top)).max(0.0)
})
.sum::<f64>()
/ f64::from(COLUMNS)
}
/// A circle of radius `r` at `c`, as eight cubics, each an eighth of it, within five millionths
/// of `r` of it.
fn circle(c: (f64, f64), r: f64) -> BezPath {
let c = kurbo::Point::new(c.0, c.1);
let at = |a: f64| c + kurbo::Vec2::from_angle(a) * r;
let step = std::f64::consts::FRAC_PI_4;
let handle = r * 4.0 / 3.0 * (step / 4.0).tan();
let mut p = BezPath::new();
p.move_to(at(0.0));
for k in 0..8 {
let (a, b) = (f64::from(k) * step, f64::from(k + 1) * step);
let tangent = |a: f64| kurbo::Vec2::from_angle(a + std::f64::consts::FRAC_PI_2) * handle;
p.curve_to(at(a) + tangent(a), at(b) - tangent(b), at(b));
}
p.close_path();
p
}
/// A document of 1200 points holding a circle of radius 400 at its middle, stroked 80 pt with
/// `paint` at `opacity`. A gradient is laid along the stroke.
fn ring(paint: Paint, opacity: f32) -> Document {
let mut d = Document::new(1200.0, 1200.0);
let path = vectorcraft_geom::PathData::from_bezpath(&circle((600.0, 600.0), 400.0));
let mut node = Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, paint, 80.0));
for item in &mut node.appearance.items {
if let AppearanceItem::Stroke(st) = item {
st.opacity = opacity;
st.gradient_mode = StrokeGradientMode::Along;
}
}
let l = d.layers[0].id;
d.insert(Some(l), 0, node).unwrap();
d
}
/// The worst edge pixel of one rim: how many alpha levels it is off, where, and how many edge
/// pixels the rim has.
#[derive(Debug, Default)]
struct Rim {
worst: u8,
pixels: usize,
at: String,
}
/// The rims of the ring of [`ring`] (outer radius 440, inner 360) drawn through `view`, which
/// scales by `scale`, at `side`×`side`, with `paint` and `opacity`. An edge pixel is one whose
/// exact coverage by the circle of its rim is between 2% and 98%; its alpha is compared with that
/// coverage of the alpha the ring paints.
fn ring_rims(view: Affine, side: u32, scale: f64, paint: Paint, opacity: f32) -> (Rim, Rim) {
let opts = RenderOptions { background: None, artboards: false, ..Default::default() };
let got = Renderer::new().render(&ring(paint, opacity), side, side, view, &opts);
let c = view * kurbo::Point::new(600.0, 600.0);
let full = 255.0 * f64::from(opacity);
let (mut outer, mut inner) = (Rim::default(), Rim::default());
for y in 0..side {
for x in 0..side {
let from = (kurbo::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5) - c).hypot();
for (rim, r, outside) in [(&mut outer, 440.0 * scale, true), (&mut inner, 360.0 * scale, false)] {
// Only pixels within two pixels of a rim can be crossed by it.
if (from - r).abs() >= 2.0 {
continue;
}
let e = disc_coverage(c, r, x, y);
if !(0.02..=0.98).contains(&e) {
continue;
}
// Inside the outer rim the ring covers the pixel; inside the inner rim it doesn't.
let want = if outside { e } else { 1.0 - e } * full;
let alpha = f64::from(got.pixel(x, y)[3]);
let diff = (alpha - want).abs().round().min(255.0) as u8;
rim.pixels += 1;
if diff > rim.worst {
rim.worst = diff;
rim.at = format!("({x},{y}) {alpha} vs {want:.1}");
}
}
}
}
(outer, inner)
}
/// Most alpha levels an edge pixel of a wide curved stroke may differ from the exact coverage of
/// its rim.
const EDGE_LEVELS: u8 = 36;
/// A wide stroke along a curve paints both of its rims within [`EDGE_LEVELS`] of their exact
/// coverage: zoomed out and at 1:1, through a turned view, with a gradient laid along it, and
/// translucent (within half as many levels).
#[test]
fn wide_curved_strokes_cover_their_rims_as_the_curves_do() {
let turned = Affine::translate((150.0, 150.0)) * Affine::rotate(0.5) * Affine::scale(0.25) * Affine::translate((-600.0, -600.0));
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let black = || Paint::solid(Color::BLACK);
let mut off = vec![];
for (name, view, side, scale, paint, opacity) in [
("zoomed out", Affine::scale(0.25), 300, 0.25, black(), 1.0),
("1:1", Affine::translate((-100.0, -100.0)), 1000, 1.0, black(), 1.0),
("turned", turned, 300, 0.25, black(), 1.0),
("gradient", Affine::scale(0.25), 300, 0.25, gradient, 1.0),
("translucent", Affine::scale(0.25), 300, 0.25, black(), 0.5),
] {
let (outer, inner) = ring_rims(view, side, scale, paint, opacity);
let bound = if opacity < 1.0 { EDGE_LEVELS / 2 + 1 } else { EDGE_LEVELS };
for (rim, r) in [("outer", outer), ("inner", inner)] {
assert!(r.pixels > 200, "{name}, {rim} rim: {} edge pixels", r.pixels);
if r.worst > bound {
off.push(format!("{name}, {rim} rim: {} levels off at {} ({} edge pixels)", r.worst, r.at, r.pixels));
}
}
}
assert!(off.is_empty(), "{off:#?}");
}
/// The outline of the 80 pt stroke along a circle of radius 400 about (600, 600), at `tol`.
fn ring_outline(tol: f64) -> BezPath {
let st = StrokeLayer::new(Paint::solid(Color::BLACK), 80.0);
crate::stroke::outline(&circle((600.0, 600.0), 400.0), &st, 80.0, tol)
}
/// How many moves and closes `p` has.
fn moves_and_closes(p: &BezPath) -> (usize, usize) {
let els = p.elements();
(els.iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(), els.iter().filter(|e| matches!(e, kurbo::PathEl::ClosePath)).count())
}
/// A wide stroke's outline has its long curves drawn as lines that cross them: the line ends lie
/// outside the circles, the lines' middles inside, all within half of the tolerance, with its
/// subpaths kept.
#[test]
fn wide_outlines_draw_their_curves_as_lines_across_them() {
for tol in [1.0, 0.25] {
let raw = ring_outline(tol);
let lines = wide(raw.clone(), 80.0, tol);
assert_eq!(moves_and_closes(&lines), moves_and_closes(&raw), "tolerance {tol}");
assert!(lines.elements().iter().all(|e| matches!(e, kurbo::PathEl::MoveTo(_) | kurbo::PathEl::LineTo(_) | kurbo::PathEl::ClosePath)));
let c = kurbo::Point::new(600.0, 600.0);
// How far a point is outside the rim it is nearest to.
let off = |p: kurbo::Point| {
let r = (p - c).hypot();
if r > 400.0 { r - 440.0 } else { r - 360.0 }
};
let (mut ends, mut middles) = (vec![], vec![]);
for seg in lines.segments() {
if let kurbo::PathSeg::Line(l) = seg
&& l.p1 != l.p0
{
ends.push(off(l.p1));
middles.push(off(l.p0.midpoint(l.p1)));
}
}
assert!(ends.len() > 100, "tolerance {tol}: {} lines", ends.len());
let most = ends.iter().chain(&middles).fold(0.0_f64, |m, d| m.max(d.abs()));
assert!(most <= tol / 2.0, "tolerance {tol}: a line {most} from its curve");
assert!(ends.iter().filter(|d| **d > tol * 0.1).count() > ends.len() / 2, "tolerance {tol}: line ends outside the curves");
assert!(middles.iter().filter(|d| **d < -tol * 0.1).count() > middles.len() / 2, "tolerance {tol}: line middles inside the curves");
}
}
/// Outlines of strokes narrower than 32 tolerances, outlines without a curve spanning 128
/// tolerances, and outlines that would take more than a million lines are kept as they are.
#[test]
fn narrow_short_straight_or_huge_outlines_are_kept() {
let tol = 0.25;
let st = |w: f64| StrokeLayer::new(Paint::solid(Color::BLACK), w);
let narrow = crate::stroke::outline(&circle((600.0, 600.0), 400.0), &st(7.0), 7.0, tol);
let small = crate::stroke::outline(&circle((50.0, 50.0), 10.0), &st(9.0), 9.0, tol);
let straight = crate::stroke::outline(&Rect::new(0.0, 0.0, 400.0, 300.0).to_path(0.1), &st(20.0), 20.0, tol);
// Eight curves of about 200,000 lines each.
let huge = circle((0.0, 0.0), 1e11);
for (name, p, width) in [("narrow", narrow, 7.0), ("small curves", small, 9.0), ("straight", straight, 20.0), ("huge", huge, 20.0)] {
assert!(p.elements().len() > 1, "{name}");
assert_eq!(wide(p.clone(), width, tol).elements(), p.elements(), "{name}: kept");
}
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
let raw = ring_outline(1.0);
assert_eq!(wide(raw.clone(), 80.0, bad).elements(), raw.elements(), "tolerance {bad}");
}
}
/// Where a long curve meets a corner, a line or a curve that isn't finite, its end stays where it
/// was, and the segments that aren't long curves are kept as they are.
#[test]
fn curve_ends_at_corners_lines_and_bad_curves_stay_put() {
let mut p = BezPath::new();
p.move_to((0.0, 0.0));
p.curve_to((0.0, 100.0), (100.0, 200.0), (200.0, 200.0));
p.line_to((300.0, 200.0));
p.curve_to((300.0, 100.0), (400.0, 0.0), (500.0, 0.0));
p.curve_to((f64::NAN, 0.0), (600.0, 0.0), (700.0, 0.0));
p.curve_to((700.0, 300.0), (900.0, 300.0), (900.0, 0.0));
p.quad_to((905.0, 5.0), (910.0, 0.0));
let lines = wide(p.clone(), 40.0, 0.25);
let points: Vec<_> = lines.elements().iter().filter_map(|e| e.end_point()).collect();
for corner in [(0.0, 0.0), (200.0, 200.0), (300.0, 200.0), (500.0, 0.0), (700.0, 0.0), (900.0, 0.0), (910.0, 0.0)] {
assert!(points.contains(&kurbo::Point::from(corner)), "{corner:?} kept: {lines:?}");
}
let curves: Vec<_> = lines.elements().iter().filter(|e| matches!(e, kurbo::PathEl::CurveTo(..) | kurbo::PathEl::QuadTo(..))).collect();
assert_eq!(curves.len(), 2, "the curve that isn't finite and the short curve are kept: {curves:?}");
assert!(lines.elements().len() > 40, "{} elements", lines.elements().len());
}
/// An outline is drawn with lines through a view that stretches no length by more than the frame's
/// pixel size allows: one that zooms, turns or shrinks the stroke's space, and not one that
/// stretches it unevenly, enlarges it beyond the frame's pixels, collapses it or isn't finite.
#[test]
fn outlines_are_drawn_as_lines_only_through_even_views() {
let px = |v: Affine| 1.0 / v.determinant().abs().sqrt();
for (name, m, px, want) in [
("zoomed out", Affine::scale(0.25), px(Affine::scale(0.25)), true),
("turned", Affine::rotate(0.5) * Affine::scale(3.0), px(Affine::scale(3.0)), true),
("flipped", Affine::FLIP_X, 1.0, true),
("text made smaller", Affine::scale(0.5), 1.0, true),
("stretched", Affine::scale_non_uniform(0.25, 0.2), px(Affine::scale_non_uniform(0.25, 0.2)), false),
("text made larger", Affine::scale(2.0), 1.0, false),
("collapsed", Affine::scale(0.0), 1.0, false),
("not a number", Affine::scale(f64::NAN), 1.0, false),
("no pixel size", Affine::IDENTITY, f64::INFINITY, false),
] {
assert_eq!(fine(m, px), want, "{name}");
}
}
+50
View File
@@ -199,6 +199,56 @@ fn a_long_dashed_stroke_draws_the_same_pixels_outlined_near_the_view() {
}
}
/// 600 half circles of radius 60 in a row along y = 0, from x = 0, each as two quarter circles and
/// alternately above and below the row.
fn waves() -> BezPath {
let k = 60.0 * 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for i in 0..600 {
let (x, s) = (f64::from(i) * 120.0, if i % 2 == 0 { -1.0 } else { 1.0 });
bp.curve_to((x, s * k), (x + 60.0 - k, s * 60.0), (x + 60.0, s * 60.0));
bp.curve_to((x + 60.0 + k, s * 60.0), (x + 120.0, s * k), (x + 120.0, 0.0));
}
bp
}
/// Whether `outline` has a curve whose control points span 32 pt or more across or down.
fn has_long_curve(outline: &BezPath) -> bool {
outline.segments().any(|s| {
let pts = match s {
kurbo::PathSeg::Line(_) => return false,
kurbo::PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
kurbo::PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
};
let b = pts.iter().fold(kurbo::Rect::from_points(pts[0], pts[0]), |b, p| b.union_pt(*p));
b.width().max(b.height()) >= 32.0
})
}
/// A long wide stroke along curves, solid or dashed, outlined near the view has its long curves
/// drawn as lines and draws the same pixels as when it is outlined whole. With a width profile,
/// the outline made near the view keeps its curves.
#[test]
fn a_long_wide_curved_stroke_draws_the_same_pixels_outlined_near_the_view() {
let at = Point::new(36_030.0, 0.0);
let solid = stroke(24.0, LineJoin::Miter, LineCap::Butt);
for (what, d) in [("solid", doc(&waves(), solid.clone())), ("dashed", doc(&waves(), dashed(solid.clone(), &[150.0, 40.0], 0.0, false)))] {
let mut r = Renderer::new();
let near = render(&mut r, &d, at);
assert!(r.strokes.values().any(|e| e.crop.is_some()), "{what}: outlined near the view");
assert!(r.strokes.values().all(|e| !has_long_curve(&e.outline)), "{what}: its long curves drawn as lines");
assert!(near.pixels == whole(&d, at).pixels, "{what}: the same pixels as the whole outline");
assert!(near.pixels.chunks(4).any(|p| p[0] < 128), "{what}: the stroke shows");
}
let mut lens = solid;
lens.profile = WidthProfile::preset("lens");
let mut r = Renderer::new();
render(&mut r, &doc(&waves(), lens), at);
assert!(r.strokes.values().any(|e| e.crop.is_some()), "lens profile: outlined near the view");
assert!(r.strokes.values().all(|e| has_long_curve(&e.outline)), "lens profile: its curves kept");
}
#[test]
fn a_long_dashed_stroke_draws_the_same_pixels_after_its_path_changes() {
let st = dashed(stroke(5.0, LineJoin::Miter, LineCap::Butt), &[18.0, 7.0], 3.0, false);
+40
View File
@@ -1350,6 +1350,46 @@ fn each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow() {
assert_eq!(img.pixel(60, 80), [255, 255, 255, 255], "inside the copy's stroke shadow");
}
/// Each copy of a group's or layer's Transform effect draws the drop shadow listed before the
/// effect under itself, of all its members together and scaled with it: two red squares side by
/// side (10..30 together) have one green shadow 20 pt to their right, and their copy scaled 200 %
/// and moved 60 pt down (0..40 across, 60..100 down) has its own 40 pt to its right. The bounds
/// reach as far as the copy's shadow, and no further.
#[test]
fn each_copy_of_a_groups_or_layers_transform_effect_draws_its_own_shadow() {
let shadow = fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}));
let copies = fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}));
let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
for layer in [false, true] {
let mut d = Document::new(100.0, 100.0);
let members: Vec<Arc<Node>> = [Rect::new(10.0, 10.0, 20.0, 30.0), Rect::new(20.0, 10.0, 30.0, 30.0)]
.into_iter()
.map(|r| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), red.clone())))
.collect();
if layer {
let l = Arc::make_mut(&mut d.layers[0]);
if let Some(ch) = l.children_mut() {
*ch = members;
}
l.appearance.effects = vec![shadow.clone(), copies.clone()];
} else {
let mut g = Node::group(d.alloc_id(), members);
g.appearance.effects = vec![shadow.clone(), copies.clone()];
let l = d.layers[0].id;
d.insert(Some(l), 0, g).unwrap();
}
let img = render(&d);
assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "layer {layer}: the squares");
assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "layer {layer}: the squares' shadow");
assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "layer {layer}: the copy");
assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "layer {layer}: the copy's shadow, 40 pt to its right");
assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "layer {layer}: past the copy's shadow");
let n = if layer { d.layers[0].clone() } else { d.layers[0].children().unwrap()[0].clone() };
let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), &n).unwrap();
assert!((b.x1 - 80.0).abs() < 1e-9, "layer {layer}: {b:?}");
}
}
/// Each copy of an image's Transform effect draws the drop shadow listed before the effect under
/// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its
/// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to
+5
View File
@@ -292,6 +292,11 @@ impl Writer<'_> {
self.warn("type on a path with Tsume is outlined to keep its look");
return self.text_outlines(n, t);
}
// Justification…'s Desired word and letter spacing and glyph scaling do too.
if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) {
self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look");
return self.text_outlines(n, t);
}
// A `<textPath>` holds the characters of the text, not the bullets or numbers drawn
// before them.
if !lay.markers.is_empty() {
+564 -14
View File
@@ -2,6 +2,7 @@
//! it, made as the importer makes art of any SVG file. The text crate asks for it through the
//! reader the app registers ([`vectorcraft_text::set_svg_glyph_reader`]).
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
@@ -20,6 +21,8 @@ const MAX_SVG_GLYPH_BYTES: u64 = 1 << 20;
/// embedded content and scripts (and images of SVG documents, in [`glyph`]).
const LEFT_OUT: [&str; 3] = ["text", "foreignObject", "script"];
const XLINK: &str = "http://www.w3.org/1999/xlink";
/// Glyph `gid`'s art from its SVG `document` (possibly gzipped), in a font of `upem` units per em:
/// its element `glyph<gid>` (or the whole document when that is its root), in font units (y down),
/// the root's `viewBox` (or else its size) fitted into the em square by its larger side, centred.
@@ -28,6 +31,11 @@ const LEFT_OUT: [&str; 3] = ["text", "foreignObject", "script"];
/// ([`own_art`]). With the art, whether it uses the text's colours. `None` when the document doesn't read, is too large or has
/// no such element.
pub fn glyph_art(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Option<Color>) -> Option<(Node, bool)> {
glyph_art_with(document, gid, upem, fill, stroke, true)
}
/// [`glyph_art`], the importer reading only what the glyph refers to when `reduce` ([`glyph`]).
fn glyph_art_with(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Option<Color>, reduce: bool) -> Option<(Node, bool)> {
// The SVGZ budget left is the glyph's cap.
let unpacked = AtomicU64::new(crate::MAX_SVGZ.saturating_sub(MAX_SVG_GLYPH_BYTES));
let text = crate::text_within(document, &unpacked).ok()?;
@@ -39,7 +47,7 @@ pub fn glyph_art(document: &[u8], gid: u32, upem: f64, fill: Color, stroke: Opti
let [r, g, b, _] = c.to_rgba8(1.0);
format!("#{r:02x}{g:02x}{b:02x}")
};
let Glyph { svg, whole, frame } = glyph(&text, &id, &hex(fill))?;
let Glyph { svg, whole, frame } = glyph(&text, &id, &hex(fill), reduce)?;
let coloured = ["currentColor", "currentcolor", "context-fill", "context-stroke"].iter().any(|k| svg.contains(k));
// usvg resolves `context-fill` and `context-stroke` only for markers.
let svg = svg.replace("context-fill", &hex(fill)).replace("context-stroke", &stroke.map_or_else(|| "none".into(), hex));
@@ -86,9 +94,10 @@ struct Glyph {
/// `svg` with only what glyph `id` draws, as if the root `use`d it: the rest of the document (a
/// font may keep all its glyphs in one) only defines what it refers to, and what its parents apply
/// doesn't reach it. Without the [`LEFT_OUT`] elements and event attributes, the root without a
/// size (the em square is its frame) and in the text's colour `color`. `None` when it doesn't read
/// or has no element `id`.
fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
/// size (the em square is its frame) and in the text's color `color`. With `reduce`, the `defs`
/// hold only what the glyph refers to ([`referred`]), when that can be followed; else the whole
/// rest of the document. `None` when it doesn't read or has no element `id`.
fn glyph(svg: &str, id: &str, color: &str, reduce: bool) -> Option<Glyph> {
// Before the XML reader: it nests by recursion and expands entities without a total limit.
if crate::import::xml_too_deep(svg) || crate::entities::expansion_too_large(svg) {
return None;
@@ -105,8 +114,7 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
// data URL not typed as a raster goes too: the importer reads an untyped one (`text/plain`) as
// SVG, SVGZ as well, when its bytes aren't a raster.
let svg_image = |n: &roxmltree::Node| {
let href = n.attribute("href").or_else(|| n.attribute(("http://www.w3.org/1999/xlink", "href")));
let data = href.map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:")));
let data = link(*n).map(|h| h.value()).map(|h| h.trim_start()).filter(|h| h.get(..5).is_some_and(|v| v.eq_ignore_ascii_case("data:")));
let raster = |h: &str| {
["data:image/png", "data:image/jpeg", "data:image/jpg", "data:image/gif", "data:image/webp"]
.iter()
@@ -114,7 +122,8 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
};
n.tag_name().name() == "image" && data.is_some_and(|h| !raster(h))
};
for n in root.descendants().filter(|n| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n))) {
let cut = |n: &roxmltree::Node| n.is_element() && (LEFT_OUT.contains(&n.tag_name().name()) || svg_image(n));
for n in root.descendants().filter(cut) {
edits.push((n.range(), String::new()));
}
for a in root.attributes().filter(|a| matches!(a.name(), "width" | "height" | "color")) {
@@ -128,10 +137,18 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
let start = root.range().start + 1;
let name = start + svg.get(start..)?.find(|c: char| c.is_whitespace() || c == '>' || c == '/')?;
edits.push((name..name, format!(" color=\"{color}\"")));
// The namespaces the glyph's parents declare, which it leaves: the root declares them too.
// The namespaces the glyph's parents declare, which it leaves: the root declares them too, or the
// glyph itself, where the root gives the prefix (or the default) another one.
let own = target.range().start + 1;
let own = own + svg.get(own..)?.find(|c: char| c.is_whitespace() || c == '>' || c == '/')?;
for ns in target.namespaces() {
if let Some(prefix) = ns.name().filter(|p| root.lookup_namespace_uri(Some(p)).is_none()) {
edits.push((name..name, format!(" xmlns:{prefix}=\"{}\"", crate::xml_escape(ns.uri()))));
let uri = crate::xml_escape(ns.uri());
let at_root = root.lookup_namespace_uri(ns.name());
match ns.name() {
Some(prefix) if at_root.is_none() => edits.push((name..name, format!(" xmlns:{prefix}=\"{uri}\""))),
_ if whole || at_root == Some(ns.uri()) || declares(svg, target, ns.name())? => {}
Some(prefix) => edits.push((own..own, format!(" xmlns:{prefix}=\"{uri}\""))),
None => edits.push((own..own, format!(" xmlns=\"{uri}\""))),
}
}
edits.sort_by_key(|(r, _)| (r.start, r.end));
@@ -141,11 +158,14 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
// The root's content goes in `defs`, and the glyph after it, on its own.
let content = root.first_child()?.range().start;
let close = svg.get(..root.range().end)?.rfind("</")?;
let defs = match reduce.then(|| referred(svg, &xml, target, cut)).flatten() {
Some(pieces) => pieces.into_iter().map(|r| edited(svg, r, &edits)).collect::<Option<String>>()?,
None => [edited(svg, content..at.start, &edits)?, edited(svg, at.end..close, &edits)?].concat(),
};
[
edited(svg, 0..content, &edits)?,
"<defs>".into(),
edited(svg, content..at.start, &edits)?,
edited(svg, at.end..close, &edits)?,
defs,
"</defs>".into(),
edited(svg, at.clone(), &edits)?,
edited(svg, close..svg.len(), &edits)?,
@@ -164,12 +184,265 @@ fn glyph(svg: &str, id: &str, color: &str) -> Option<Glyph> {
Some(Glyph { svg: out, whole, frame: view_box.or_else(size) })
}
/// Whether the start tag of `element` in `svg` declares namespace `prefix` (`None`: the default
/// one). `None` when the tag doesn't read.
fn declares(svg: &str, element: roxmltree::Node, prefix: Option<&str>) -> Option<bool> {
let want = prefix.map_or_else(|| "xmlns".to_string(), |p| format!("xmlns:{p}"));
let tag = svg.get(element.range().start + 1..)?;
let mut rest = tag.trim_start_matches(|c: char| !(c.is_whitespace() || c == '>' || c == '/'));
loop {
rest = rest.trim_start();
if rest.is_empty() || rest.starts_with(['>', '/']) {
return Some(false);
}
let eq = rest.find('=')?;
let value = rest.get(eq + 1..)?.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
let close = 1 + value.get(1..)?.find(quote)?;
if rest.get(..eq)?.trim_end() == want {
return Some(true);
}
rest = value.get(close + 1..)?;
}
}
/// The byte ranges of `svg` (whose XML is `xml`) that the `defs` of glyph element `target` need, in
/// order: the elements it refers to with `url(#id)` (in an attribute, a `style` or a sheet) or
/// `href="#id"`, those they refer to in turn, and every `<style>` sheet, each whole, with the start
/// and end tags of the elements holding them (and what those refer to), so what they inherit and the
/// sheets' rules match as in the whole document. `None` when that can't be followed and the whole
/// rest of the document goes in: a document with a DTD or an `xml:base`, ids used twice, a
/// reference to an element that isn't there, holds the glyph or is inside one `cut` takes out, a
/// link to another file, a reference with an escape, or a sheet with selectors that look at
/// siblings ([`plain_sheet`]). Each element is queued and read at most once.
fn referred<'a, 'i>(
svg: &str,
xml: &'a roxmltree::Document<'i>,
target: roxmltree::Node<'a, 'i>,
cut: impl Fn(&roxmltree::Node<'a, 'i>) -> bool,
) -> Option<Vec<Range<usize>>> {
if svg.contains("<!DOCTYPE") || target.ancestors().skip(1).any(|a| cut(&a)) {
return None;
}
let root = xml.root_element();
// Whether element `inner` is `outer` or inside it.
let within =
|outer: roxmltree::Node, inner: roxmltree::Node| outer.range().start <= inner.range().start && inner.range().end <= outer.range().end;
let mut ids = HashMap::new();
let mut wanted = vec![];
// The elements `cut` takes out with what they hold, found in document order.
let mut left_out = HashSet::new();
let mut cut_end = 0;
for n in xml.descendants().filter(|n| n.is_element()) {
if n.attribute(("http://www.w3.org/XML/1998/namespace", "base")).is_some() {
return None;
}
if let Some(id) = n.attribute("id")
&& ids.insert(id, n).is_some()
{
return None;
}
if n.range().start >= cut_end && cut(&n) {
cut_end = n.range().end;
}
if n.range().start < cut_end {
left_out.insert(n.id());
} else if n.tag_name().name() == "style" && !within(target, n) {
wanted.push(n);
}
}
let mut refs = vec![];
for a in root.attributes() {
refer(root, a, &mut refs)?;
}
// Elements whose whole subtree is read, those queued to be, the elements kept whole and the
// elements holding them.
let mut read = HashSet::new();
let mut queued: HashSet<_> = wanted.iter().map(|n| n.id()).collect();
queued.insert(target.id());
let mut holders = HashSet::new();
let mut kept = wanted.clone();
let mut queue = wanted;
queue.push(target);
while let Some(n) = queue.pop() {
// The elements holding a kept one go in around it: what they refer to goes in too. Above
// one already held, all are.
if n != target {
for a in n.ancestors().skip(1).take_while(|a| *a != root) {
if !holders.insert(a.id()) {
break;
}
for at in a.attributes() {
refer(a, at, &mut refs)?;
}
}
}
let mut stack = vec![n];
while let Some(m) = stack.pop() {
if !m.is_element() || !read.insert(m.id()) {
continue;
}
for a in m.attributes() {
refer(m, a, &mut refs)?;
}
if m.tag_name().name() == "style" {
let sheet: String = m.children().filter_map(|c| c.text()).collect();
if !plain_sheet(&sheet) || m.children().filter_map(|c| c.text()).try_for_each(|t| urls(t, &mut refs)).is_none() {
return None;
}
}
stack.extend(m.children());
}
for id in refs.drain(..) {
let r = *ids.get(id)?;
if within(target, r) {
continue;
}
if within(r, target) || left_out.contains(&r.id()) {
return None;
}
if !read.contains(&r.id()) && queued.insert(r.id()) {
kept.push(r);
queue.push(r);
}
}
}
kept.sort_by_key(|n| n.range().start);
let mut tags = HashSet::new();
let mut pieces = vec![];
// The end of the last element kept whole: one starting before it is inside it, in its range.
let mut end = 0;
for n in kept {
if n.range().start < end {
continue;
}
end = n.range().end;
pieces.push(n.range());
for a in n.ancestors().skip(1).take_while(|a| *a != root) {
if !tags.insert(a.id()) {
break;
}
let (first, last) = (a.first_child()?.range(), a.last_child()?.range());
pieces.push(a.range().start..first.start);
pieces.push(last.end..a.range().end);
}
}
pieces.sort_by_key(|r| r.start);
Some(pieces)
}
/// Adds to `refs` the ids attribute `a` of element `n` refers to: an `href`'s `#id`, a value's
/// `url(#id)`s ([`urls`]). Of the links, only the one the importer follows: a plain `href`, else an
/// `xlink:href`. `None` when it refers to anything else, other than an image's or a link's file or
/// a data URL.
fn refer<'a>(n: roxmltree::Node, a: roxmltree::Attribute<'a, '_>, refs: &mut Vec<&'a str>) -> Option<()> {
if a.name() != "href" {
return urls(a.value(), refs);
}
if link(n).map(|l| l.range()) != Some(a.range()) {
return Some(());
}
let v = a.value().trim_matches(|c: char| c.is_ascii_whitespace());
match v.strip_prefix('#') {
Some(id) => refs.push(plain_id(id)?),
None if v.is_empty() || starts_with_ignoring_case(v, "data:") || matches!(n.tag_name().name(), "image" | "a") => {}
None => return None,
}
Some(())
}
/// Element `n`'s link as the importer follows it (SVG 2): its plain `href`, else its `xlink:href`.
fn link<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> Option<roxmltree::Attribute<'a, 'i>> {
let href = |ns: Option<&str>| n.attributes().find(|a| a.name() == "href" && a.namespace() == ns);
href(None).or_else(|| href(Some(XLINK)))
}
/// Adds to `refs` the ids of the `url(#id)`s in CSS or attribute value `v` (in any case, the id
/// quoted or not), passing data URLs by. `None` when one is of another form: another file, an
/// escape, a URL that doesn't close.
fn urls<'a>(v: &'a str, refs: &mut Vec<&'a str>) -> Option<()> {
// An escape can spell `url(` or an id in another way.
if v.contains('\\') {
return None;
}
let space = |c: char| c.is_ascii_whitespace();
let mut from = 0;
while let Some(at) = v.get(from..)?.as_bytes().windows(4).position(|w| w.eq_ignore_ascii_case(b"url(")) {
from += at + 4;
let rest = v.get(from..)?.trim_start_matches(space);
let (quote, rest) = match rest.chars().next() {
Some(q @ ('"' | '\'')) => (Some(q), rest.get(1..)?),
_ => (None, rest),
};
if starts_with_ignoring_case(rest, "data:") {
continue;
}
let id = rest.strip_prefix('#')?;
let end = id.find(|c: char| space(c) || matches!(c, ')' | '"' | '\'')).unwrap_or(id.len());
let mut tail = id.get(end..)?.trim_start_matches(space);
if let Some(q) = quote {
tail = tail.strip_prefix(q)?.trim_start_matches(space);
}
if !tail.starts_with(')') {
return None;
}
refs.push(plain_id(id.get(..end)?)?);
}
Some(())
}
/// `id` when it is matched as it is written: not empty, and without an escape (`\`), a percent
/// escape or a space.
fn plain_id(id: &str) -> Option<&str> {
(!id.is_empty() && !id.contains(|c: char| matches!(c, '\\' | '%') || c.is_whitespace())).then_some(id)
}
fn starts_with_ignoring_case(s: &str, prefix: &str) -> bool {
s.get(..prefix.len()).is_some_and(|p| p.eq_ignore_ascii_case(prefix))
}
/// Whether the rules of style sheet `css` are matched by each element and its ancestors alone, so
/// they match as before when other elements are left out: selectors of type, `*`, `#id` and
/// `.class`, joined by descendant and child (`>`) combinators, in lists. No pseudo-classes
/// (`:nth-child`, `:has`), sibling combinators, attribute selectors, escapes or at-rules.
fn plain_sheet(css: &str) -> bool {
let mut text = String::new();
let mut rest = css;
while let Some(at) = rest.find("/*") {
text.push_str(&rest[..at]);
let Some(end) = rest[at + 2..].find("*/") else { return false };
text.push(' ');
rest = &rest[at + 2 + end + 2..];
}
text.push_str(rest);
if text.contains(['@', '\\']) {
return false;
}
let mut rest = text.as_str();
while let Some(open) = rest.find('{') {
let selectors = &rest[..open];
if !selectors.chars().all(|c| c.is_ascii_alphanumeric() || c.is_ascii_whitespace() || matches!(c, '_' | '-' | '.' | '#' | '*' | '>' | ',')) {
return false;
}
let body = &rest[open + 1..];
let Some(close) = body.find('}') else { return false };
if body[..close].contains('{') {
return false;
}
rest = &body[close + 1..];
}
rest.trim().is_empty()
}
/// `svg[range]` with the `edits` (in order) that lie in it made: one around the range (a left-out
/// element holding the glyph) isn't, so it stays whole, defining only.
/// element holding the glyph) isn't, so it stays whole, defining only. The `edits` are sorted by
/// where they start.
fn edited(svg: &str, range: Range<usize>, edits: &[(Range<usize>, String)]) -> Option<String> {
let mut out = String::new();
let mut at = range.start;
for (r, with) in edits.iter().filter(|(r, _)| range.start <= r.start && r.end <= range.end) {
let first = edits.partition_point(|(r, _)| r.start < range.start);
let within = edits.get(first..)?.iter().take_while(|(r, _)| r.start <= range.end);
for (r, with) in within.filter(|(r, _)| r.end <= range.end) {
// An element inside one already cut goes with it.
if r.start < at {
continue;
@@ -205,3 +478,280 @@ fn own_art(n: &Node, doc: &Document) -> Option<Node> {
}
Some(n)
}
#[cfg(test)]
mod tests {
use super::*;
/// A document of `n` glyphs `glyph0`… that share one gradient, each two paths.
fn shared(n: usize) -> String {
let glyphs: String = (0..n)
.map(|i| {
format!(
r##"<g id="glyph{i}"><path fill="url(#shade)" d="M{i} 0c100 -200 300 -200 400 0s-100 300 -400 0z"/><path fill="#{:06x}" d="M0 0h50v-50z"/></g>"##,
i * 97 % 0xff_ffff
)
})
.collect();
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><defs><linearGradient id="shade"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>{glyphs}</svg>"##
)
}
fn rewrite(svg: &str, gid: u32, reduce: bool) -> String {
glyph(svg, &format!("glyph{gid}"), "#000000", reduce).unwrap().svg
}
fn art(svg: &str, gid: u32, reduce: bool) -> Node {
glyph_art_with(svg.as_bytes(), gid, 1000.0, Color::BLACK, None, reduce).unwrap().0
}
#[test]
fn a_glyph_of_a_shared_document_hands_the_importer_only_what_it_refers_to() {
let (small, large) = (shared(20), shared(2000));
assert!(large.len() > 100 << 10 && (large.len() as u64) < MAX_SVG_GLYPH_BYTES, "{}", large.len());
let one = rewrite(&large, 10, true);
assert_eq!(one, rewrite(&small, 10, true), "the same, however many other glyphs the document holds");
let middle = rewrite(&large, 1000, true);
assert!(middle.len() < 2 << 10, "{} bytes", middle.len());
assert!(middle.contains(r#"id="shade""#) && middle.contains(r#"id="glyph1000""#), "{middle}");
assert!(!middle.contains(r#"id="glyph999""#) && !middle.contains(r#"id="glyph1001""#), "{middle}");
assert_eq!(art(&large, 1000, true), art(&large, 1000, false));
}
/// Documents whose glyph refers to art across them, each one drawn the same from the `defs`
/// left after reducing as from the whole document.
#[test]
fn a_reduced_document_draws_the_glyph_as_the_whole_one_does() {
let other = r##"<g id="glyph8"><path fill="#123456" d="M0 0h900v-900z"/></g>"##;
let docs = [
// A gradient inside another glyph, inheriting from one in `defs`, under a fill.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph3" fill="#0f0"><linearGradient id="g" href="#base"/><path d="M0 0h10v-10z"/></g>
<defs><linearGradient id="base"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
<g id="glyph1"><path fill="url(#g)" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
// `<use>` by `href`, `xlink:href` and a prefix declared on the glyph's parent.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g xmlns:l="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/><path id="b" d="M0 0h300v-300z"/><path id="c" d="M0 0h7v-7z"/></defs>
<g id="glyph1"><use href="#a" xlink:href="#b" fill="#f00"/><use l:href="#b" x="400" fill="#0f0"/></g></g>{other}</svg>"##
),
// A sheet's rules: a `url()` they give, a gradient's chain, a class on another glyph's group.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><style><![CDATA[ .p {{ fill: url( '#g1' ) }} .warm > linearGradient stop, #x {{ stop-color: #f80 }} /* {{}}@ */ ]]></style>
<g id="glyph2" class="warm"><linearGradient id="g1" href="#g2"/><linearGradient id="g2"><stop offset="0"/><stop offset="1" stop-color="#00f"/></linearGradient></g>
<g id="glyph1"><path class="p" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
// Clip paths, masks, filters, markers and patterns, a cycle, the glyph using itself, a
// non-ASCII id.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="c"><rect width="300" height="300"/></clipPath>
<mask id="m"><rect width="500" height="500" fill="#fff"/></mask><filter id="f"><feGaussianBlur stdDeviation="2"/></filter>
<marker id="k" markerWidth="4" markerHeight="4"><circle r="2" fill="url(#pat)"/></marker>
<pattern id="pat" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5" fill="#0f0"/></pattern>
<linearGradient id="loop1" href="#loop2"/><linearGradient id="loop2" href="#loop1"><stop offset="0" stop-color="#f0f"/></linearGradient>
<linearGradient id="ü"><stop offset="0" stop-color="#ff0"/></linearGradient></defs>
<g id="glyph1"><path style="clip-path:url(#c);mask:URL(&quot;#m&quot;)" filter="url(#f)" marker-start="url(#k)" fill="url(#pat)" stroke="url(#loop1)" d="M0 0L300 300"/>
<rect fill="url(#ü)" width="9" height="9"/><use href="#glyph1"/></g>{other}</svg>"##
),
// A rule on the glyph's own parent, which it leaves either way; a quoted, spaced URL to
// an id with punctuation in it.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><style>.outer .p {{ fill: #f00 }} .outer > g {{ stroke-width: 9 }}</style>
<linearGradient id="a;b"><stop offset="0" stop-color="#0ff"/></linearGradient>
<g class="outer"><g id="glyph1"><path class="p" stroke='url( "#a;b" )' d="M0 0h500v-500z"/></g></g>{other}</svg>"##
),
// A pattern whose art takes its paint from the group holding it.
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="p2"><stop offset="0" stop-color="#f0f"/></linearGradient></defs>
<g fill="url(#p2)"><pattern id="pat" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5"/></pattern></g>
<g id="glyph1"><path fill="url(#pat)" d="M0 0h500v-500z"/></g>{other}</svg>"##
),
];
for doc in &docs {
let (reduced, whole) = (rewrite(doc, 1, true), rewrite(doc, 1, false));
assert!(reduced.len() < whole.len() && !reduced.contains("#123456"), "reduced: {reduced}");
assert_eq!(art(doc, 1, true), art(doc, 1, false), "{reduced}");
}
}
/// Whatever the reduction can't follow keeps the whole document in the `defs`.
#[test]
fn what_cant_be_followed_keeps_the_whole_document() {
let glyph = |defs: &str, art: &str| {
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">{defs}<g id="glyph1">{art}</g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
)
};
let gradient = r##"<linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient>"##;
let path = |fill: &str| format!(r##"<path fill="{fill}" d="M0 0h500v-500z"/>"##);
let docs = [
glyph("<style>path:nth-child(1) { fill: #f00 }</style>", &path("#000")),
glyph("<style>g + g path { fill: #f00 }</style>", &path("#000")),
glyph("<style>[fill] { stroke: #f00 }</style>", &path("#000")),
glyph("<style>@import url(x.css);</style>", &path("#000")),
glyph(r"<style>.a { fill: url(#g\31) }</style>", &path("#000")),
glyph("<style>path { fill: #f00 </style>", &path("#000")),
glyph(gradient, &path(r"url(#\67)")),
glyph(gradient, r#"<path style="fill:u\72l(#g)" d="M0 0h5v-5z"/>"#),
glyph(gradient, &path("url(#%67)")),
glyph(gradient, &path("url('#g)")),
glyph(gradient, &path("url(#g) url(#g x)")),
glyph(gradient, &path("url(#nothing)")),
glyph(gradient, &path("url(other.svg#g)")),
glyph(gradient, r##"<use href="other.svg#g"/>"##),
glyph(&format!("{gradient}{gradient}"), &path("url(#g)")),
glyph(&format!(r#"<g xml:base="x/">{gradient}</g>"#), &path("url(#g)")),
glyph(&format!("<text>{gradient}</text>"), &path("url(#g)")),
r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="outer"><g id="glyph1"><use href="#outer"/></g></g><g id="glyph2"><path d="M0 0h9v-9z"/></g></svg>"##
.to_string(),
r##"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY e "#f00">]><svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="&e;" d="M0 0h5v-5z"/></g><g id="glyph2"/></svg>"##
.to_string(),
];
for doc in &docs {
assert_eq!(rewrite(doc, 1, true), rewrite(doc, 1, false), "{doc}");
}
}
#[test]
fn edits_apply_inside_the_range_asked_for() {
let edits = vec![(0..1, "A".to_string()), (2..2, "B".into()), (3..5, String::new()), (4..6, "C".into())];
// An edit overlapping one already made is passed by; one not inside the range is not made.
assert_eq!(edited("0123456", 0..7, &edits).as_deref(), Some("A1B256"));
assert_eq!(edited("0123456", 2..5, &edits).as_deref(), Some("B2"));
assert_eq!(edited("0123456", 4..7, &edits).as_deref(), Some("C6"));
assert_eq!(edited("0123456", 1..2, &edits).as_deref(), Some("1B"));
}
/// Of an element's `href` and `xlink:href`, only the plain one is followed, as the importer
/// follows it: the other's element stays out, and one that isn't there doesn't keep the whole
/// document.
#[test]
fn only_the_link_the_importer_follows_is_kept() {
let doc = |xlink: &str| {
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/><path id="b" d="M0 0h300v-300z"/></defs>
<g id="glyph1"><use xlink:href="{xlink}" href="#a" fill="#f00"/><use xlink:href="#b" fill="#0f0"/></g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
)
};
for xlink in ["#nothing", "other.svg#b"] {
let doc = doc(xlink);
let reduced = rewrite(&doc, 1, true);
assert!(reduced.len() < rewrite(&doc, 1, false).len() && !reduced.contains("#123456"), "{reduced}");
assert_eq!(art(&doc, 1, true), art(&doc, 1, false));
}
let doc = doc("#b").replace(r##"<use xlink:href="#b" fill="#0f0"/>"##, "");
let reduced = rewrite(&doc, 1, true);
assert!(reduced.contains(r#"id="a""#) && !reduced.contains(r#"id="b""#), "{reduced}");
assert_eq!(art(&doc, 1, true), art(&doc, 1, false));
}
/// A glyph inside an element that gives a prefix (or the default namespace) another namespace
/// than the root does keeps its own after it leaves that element.
#[test]
fn a_glyph_keeps_its_namespaces_when_the_root_gives_them_others() {
let flat = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="http://www.w3.org/1999/xlink"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g id="glyph1"><use v:href="#a" fill="#f00"/></g><g id="glyph2"/></svg>"##;
let nested = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="urn:other"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g xmlns:v="http://www.w3.org/1999/xlink"><g id="glyph1"><use v:href="#a" fill="#f00"/></g></g><g id="glyph2"/></svg>"##;
// The glyph declaring the prefix itself keeps it as it is.
let declared = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:v="urn:other"><defs><path id="a" d="M0 0h100v-100z"/></defs>
<g xmlns:v="http://www.w3.org/1999/xlink"><g xmlns:v='http://www.w3.org/1999/xlink' id="glyph1"><use v:href="#a" fill="#f00"/></g></g><g id="glyph2"/></svg>"##;
for reduce in [true, false] {
assert_eq!(art(nested, 1, reduce), art(flat, 1, reduce), "{}", rewrite(nested, 1, reduce));
assert_eq!(art(declared, 1, reduce), art(flat, 1, reduce), "{}", rewrite(declared, 1, reduce));
}
assert_eq!(rewrite(declared, 1, true).matches("xmlns:v=").count(), 2);
// A path in another default namespace is no SVG path, out of that element too.
let other = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:s="http://www.w3.org/2000/svg">
<s:g xmlns="urn:other"><s:g id="glyph1"><s:path fill="#f00" d="M0 0h5v-5z"/><path fill="#0f0" d="M0 0h9v-9z"/></s:g></s:g><s:g id="glyph2"/></svg>"##;
let only = r##"<svg xmlns="http://www.w3.org/2000/svg"><g id="glyph1"><path fill="#f00" d="M0 0h5v-5z"/></g><g id="glyph2"/></svg>"##;
for reduce in [true, false] {
assert_eq!(art(other, 1, reduce), art(only, 1, reduce), "{}", rewrite(other, 1, reduce));
}
}
/// Many references to the same elements keep each of them once.
#[test]
fn repeated_references_keep_each_element_once() {
let uses: String = (0..2000).map(|i| format!(r##"<use href="#a" x="{i}"/><path fill="url(#g)" d="M{i} 0h1v-1z"/>"##)).collect();
let doc = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="g"><stop offset="0" stop-color="#f00"/></linearGradient>
<g id="a"><path fill="url(#g)" d="M0 0h5v-5z"/><use href="#b"/><use href="#b"/></g><path id="b" fill="url(#g)" d="M0 0h2v-2z"/></defs>
<g id="glyph1">{uses}</g><g id="glyph2"><path fill="#123456" d="M0 0h9v-9z"/></g></svg>"##
);
let reduced = rewrite(&doc, 1, true);
for id in ["g", "a", "b"] {
assert_eq!(reduced.matches(&format!(r#"id="{id}""#)).count(), 1, "{id}");
}
assert!(!reduced.contains("#123456"));
}
/// An empty document, or one without the glyph, has no art; one of exactly the cap reads, one a
/// byte larger doesn't.
#[test]
fn empty_and_capped_documents() {
assert!(glyph_art(b"", 1, 1000.0, Color::BLACK, None).is_none());
assert!(glyph_art(br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#, 1, 1000.0, Color::BLACK, None).is_none());
let doc = shared(20);
let at = doc.len() - "</svg>".len();
let padded = |len: u64| {
let pad = "x".repeat(len as usize - doc.len() - "<!---->".len());
format!("{}<!--{pad}-->{}", &doc[..at], &doc[at..])
};
let (full, over) = (padded(MAX_SVG_GLYPH_BYTES), padded(MAX_SVG_GLYPH_BYTES + 1));
assert_eq!(full.len() as u64, MAX_SVG_GLYPH_BYTES);
assert_eq!(art(&full, 3, true), art(&doc, 3, true));
assert!(glyph_art(over.as_bytes(), 3, 1000.0, Color::BLACK, None).is_none());
}
/// This thread's CPU time in seconds where the system reports it, else the time since a first
/// call.
fn cpu_seconds() -> f64 {
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok()) {
Some(ns) => ns / 1e9,
None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(),
}
}
/// The importer's time for 50 distinct glyphs of shared documents, read whole and reduced, the
/// two alternating in one process: `cargo test -p vectorcraft-svg --lib glyph::tests::timing --
/// --ignored --nocapture`.
#[test]
#[ignore = "timing, run by hand"]
fn timing() {
for n in [100, 500, 2000] {
let doc = shared(n);
let gids: Vec<u32> = (0..50).map(|i| (i * n / 50) as u32).collect();
let run = |reduce: bool| {
let t = cpu_seconds();
for g in &gids {
assert!(glyph_art_with(doc.as_bytes(), *g, 1000.0, Color::BLACK, None, reduce).is_some());
}
cpu_seconds() - t
};
run(false);
run(true);
let (mut whole, mut reduced) = (vec![], vec![]);
for round in 0..9 {
if round % 2 == 0 {
whole.push(run(false));
reduced.push(run(true));
} else {
reduced.push(run(true));
whole.push(run(false));
}
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::<Vec<_>>().join(" ");
println!("{n} glyphs, {} bytes: whole {} ms, reduced {} ms", doc.len(), ms(&whole), ms(&reduced));
println!("{n} glyphs: median whole {:.1} ms, reduced {:.1} ms", median(&mut whole) * 1e3, median(&mut reduced) * 1e3);
}
}
}
+36 -7
View File
@@ -241,13 +241,10 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() {
let svg = vectorcraft_svg::base64_encode(
br##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="#f00"/></svg>"##,
);
let image = |href: &str, xlink: &str| {
format!(
r##"<image width="500" height="500" href="data:image/{href};base64,{}" xlink:href="data:image/{xlink};base64,{}"/>"##,
if href == "png" { &png } else { &svg },
if xlink == "png" { &png } else { &svg }
)
};
let data = |kind: &str| format!("data:image/{kind};base64,{}", if kind == "png" { &png } else { &svg });
let image = |href: &str, xlink: &str| format!(r##"<image width="500" height="500" href="{}" xlink:href="{}"/>"##, data(href), data(xlink));
// The same, `xlink:href` written first.
let xlink_first = |href: &str, xlink: &str| format!(r##"<image width="500" height="500" xlink:href="{}" href="{}"/>"##, data(xlink), data(href));
let images = |inner: String| {
let doc = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="glyph1"><path d="M0 0h1v-1z"/>{inner}</g></svg>"##
@@ -258,6 +255,38 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() {
};
assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays");
assert_eq!(images(image("svg+xml", "png")), 0, "the document goes");
assert_eq!(images(xlink_first("png", "svg+xml")), 1, "the PNG stays, its link written last");
assert_eq!(images(xlink_first("svg+xml", "png")), 0, "the document goes, its link written last");
}
/// A glyph draws what it refers to wherever its document defines it: here a sheet's `url()` to a
/// gradient inside another glyph's element, which takes its stops from one in `defs`. The other
/// glyph's own art is not drawn.
#[test]
fn a_glyph_draws_what_it_refers_to_from_anywhere_in_its_document() {
let doc = r##"<svg xmlns="http://www.w3.org/2000/svg"><style>.p { fill: url(#g) }</style>
<defs><linearGradient id="stops"><stop offset="0" stop-color="#f00"/><stop offset="1" stop-color="#00f"/></linearGradient></defs>
<g id="glyph2"><linearGradient id="g" href="#stops"/><path fill="#0f0" d="M0 0h10v-10z"/></g>
<g id="glyph5"><path class="p" d="M0 0h500v-500z"/></g>
</svg>"##;
let fills = fills(&art(doc, 5).unwrap());
let stops = fills.iter().find_map(|p| match p {
Paint::Gradient(g) => Some(g.gradient.stops.iter().map(|s| s.color).collect::<Vec<_>>()),
_ => None,
});
assert_eq!(stops, Some(vec![Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)]), "{fills:?}");
assert!(!fills.contains(&Paint::solid(Color::rgb8(0, 255, 0))), "not the other glyph's art: {fills:?}");
}
/// A glyph in colors of its own doesn't use the text's because another glyph of its document does.
#[test]
fn another_glyphs_current_color_does_not_color_a_glyph() {
let doc = r##"<svg xmlns="http://www.w3.org/2000/svg">
<g id="glyph1"><path fill="#f00" d="M0 0h500v-500z"/></g>
<g id="glyph2"><path fill="currentColor" d="M0 0h500v-500z"/></g>
</svg>"##;
assert!(!glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1);
assert!(glyph_art(doc.as_bytes(), 2, 1000.0, BLUE, None).unwrap().1);
}
/// A glyph's `<a>` draws its art but keeps no link: outlined text must not export a
+31
View File
@@ -671,6 +671,37 @@ fn justification_spacing_and_glyph_scaling_are_drawn_in_place() {
}
}
/// Type on a path with Justification…'s Desired word or letter spacing or glyph scaling is outlined
/// with a warning, since a `<textPath>` places its characters one after the other at their own
/// advances. With the default Desired values it stays a `<textPath>`.
#[test]
fn justification_spacing_on_a_path_is_outlined() {
use vectorcraft_doc::JustificationOptions;
let doc = |j: JustificationOptions| {
let mut t = TextObject::point(Point::ZERO, "HO HO", style(12.0));
t.para.justification = j;
let mut line = BezPath::new();
line.move_to((20.0, 100.0));
line.line_to((280.0, 100.0));
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
let mut d = Document::new(300.0, 200.0);
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
vectorcraft_svg::export_full(&d, &ExportOptions::default(), None)
};
let out = doc(JustificationOptions::default());
assert!(out.svg.contains("<textPath") && out.warnings.is_empty(), "{:?}", out.warnings);
for j in [
JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() },
JustificationOptions { letter_spacing: [0.0, 50.0, 50.0], ..JustificationOptions::default() },
JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() },
] {
let out = doc(j);
assert!(!out.svg.contains("<textPath") && out.warnings.iter().any(|w| w.contains("Justification")), "{:?}", out.warnings);
}
}
/// Justified and Mojikumi lines whose characters a reader draws where the layout does are written
/// as before: a segment per style run, and per word on a justified line.
#[test]
+13 -2
View File
@@ -338,6 +338,12 @@ pub fn ai_with_entries_and_content(private: &[u8], page: &str, entries: &str, co
with_private(private, page, "AIPrivateData", entries, content)
}
/// [`ai_with_content`] with `streams` more in the dictionary of each private data stream
/// (`/Filter /Bogus `).
pub fn ai_with_private_streams(private: &[u8], page: &str, content: &str, streams: &str) -> Vec<u8> {
with_private_streams(private, page, "AIPrivateData", "", content, streams)
}
/// A PDF saved with Illustrator's editing data: [`ai`]'s file with the two streams under
/// `AIPDFPrivateData1` and `AIPDFPrivateData2`. These key names were seen in the PDF attached to
/// #868, and nothing else of that file is used; ExifTool's PDF tag table lists them too
@@ -354,6 +360,11 @@ pub fn pdf_with_content(private: &[u8], page: &str, content: &str) -> Vec<u8> {
/// The file of [`ai`] and [`pdf`], with `private` in the streams `{key}1` and `{key}2`, `entries`
/// more in the page dictionary and `content` more in its content stream's dictionary.
fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: &str) -> Vec<u8> {
with_private_streams(private, page, key, entries, content, "")
}
/// [`with_private`] with `streams` more in each private data stream's dictionary.
fn with_private_streams(private: &[u8], page: &str, key: &str, entries: &str, content: &str, streams: &str) -> Vec<u8> {
let (first, second) = private.split_at(private.len() / 2);
let stream = |part: &[u8], more: &str| {
let mut s = format!("<< /Length {} {more}>>\nstream\n", part.len()).into_bytes();
@@ -371,8 +382,8 @@ fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: &
)
.into_bytes(),
stream(page.as_bytes(), content),
stream(first, ""),
stream(second, ""),
stream(first, streams),
stream(second, streams),
];
let mut out = b"%PDF-1.5\n".to_vec();
let mut offsets = vec![];
+26 -1
View File
@@ -4,9 +4,10 @@ use super::flow::{list_markers, repeat_mark_glyph};
use super::region::in_range;
use super::{
Affine, ArcPath, BezPath, Ctx, GlyphBend, Justify, LineInfo, ListMarker, ParamCurve, PathAlign, PathData, PathEffect, PathEl, Point, Range,
SGlyph, Shape, TextObject, Vec2, style_metrics,
SGlyph, Shape, TextObject, Vec2, apply_desired, style_metrics,
};
use crate::fontdb::PathAlignHeights;
use std::collections::HashMap;
use unicode_bidi::{BidiClass, BidiInfo};
/// The distance along type on a path each glyph takes: its advance measured `spacing` points above
@@ -425,6 +426,25 @@ fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range<usize>, glyphs: &m
Some((g.byte, c))
}
/// Justification…: paragraph `pi`'s glyphs at its Desired word and letter spacing and glyph scaling
/// (vertical type is not glyph scaled), with the Desired Glyph Scaling of each glyph it scales put
/// in `scales` by byte offset. Type on a path is one line that is never justified to a width, so
/// Minimum and Maximum are not used.
fn set_desired(cx: &Ctx<'_>, t: &TextObject, pi: usize, glyphs: &mut [SGlyph], scales: &mut HashMap<usize, f64>) {
let flex = apply_desired(glyphs, &t.layout_justification(t.para_at(pi)), !cx.vertical);
scales.extend(glyphs.iter().zip(&flex).filter(|(_, f)| f.scale != 1.0).map(|(g, f)| (g.byte, f.scale)));
}
/// Records on the glyph just drawn for `g` the Desired Glyph Scaling it is drawn at (`scales`, by
/// byte offset). A list marker's glyphs (no length) share their paragraph's first byte and are not
/// scaled.
fn record_scale(cx: &mut Ctx<'_>, g: &SGlyph, scales: &HashMap<usize, f64>) {
let scale = if g.len > 0 { scales.get(&g.byte).copied() } else { None };
if let (Some(scale), Some(out)) = (scale, cx.out.glyphs.last_mut()) {
out.scale = scale;
}
}
/// Lay type on a path out along `path` (text space), between its brackets.
pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, path: &PathData) {
cx.out.on_path = true;
@@ -434,11 +454,15 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
let mut rtl = None;
let mut shaped = Vec::new();
let markers = list_markers(t, paras);
// The Desired Glyph Scaling each scaled glyph is drawn at, by its byte offset.
let mut scales = HashMap::new();
for (pi, pr) in paras.iter().enumerate() {
let text = cx.text;
let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(pr));
rtl.get_or_insert(is_rtl(bidi.as_ref()) && !cx.vertical);
let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref(), t.para_at(pi));
// Justification…, before anything measures the glyphs along the path.
set_desired(cx, t, pi, &mut glyphs, &mut scales);
// Bullets and numbers: a list paragraph's text starts after its marker here too, unless
// the paragraph continues from the frame before in its thread.
if pi > 0 || !t.first_para_continues {
@@ -727,6 +751,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
}
let at = cx.out.glyphs.len();
cx.emit(g, pre, origin, angle, g.adv, 0);
record_scale(cx, g, &scales);
let hidden = hide_before_open_path(cx, &ap, lead, at, s + step * 0.5, rise);
if !hidden && let Some(mark) = repeat.take_if(|&mut (byte, _)| g.len > 0 && g.byte == byte) {
cx.out.repeat_marks.push(mark);
+99
View File
@@ -64,6 +64,105 @@ fn desired_spacing_and_scaling_apply_to_every_line() {
assert!((at(&scaled, 2).advance - space).abs() < 1e-6, "word spaces aren't scaled");
}
/// Type on a straight open path `len` long, from the origin along x.
fn on_path(text: &str, len: f64, j: JustificationOptions) -> TextObject {
let mut t = point(text, j);
let mut line = kurbo::BezPath::new();
line.move_to((0.0, 0.0));
line.line_to((len, 0.0));
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
t
}
/// Desired values apply to type on a path as to point and area type: word spaces are that share of
/// the font's space, letters are followed by that share of a space, and glyphs are drawn that wide,
/// and the glyphs after a wider gap start further along the path.
#[test]
fn type_on_a_path_takes_desired_spacing_and_scaling() {
let plain = layout(db(), &on_path("ab cd", 1000.0, JustificationOptions::default()));
assert!(plain.on_path && !plain.overflow);
let space = at(&plain, 2).advance;
let a = at(&plain, 0).advance;
assert!(space > 0.0 && a > 0.0);
let words =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() }));
assert!((at(&words, 2).advance - 2.0 * space).abs() < 1e-6, "a word space at 200%");
assert!((at(&words, 1).origin.x - at(&plain, 1).origin.x).abs() < 1e-6, "the glyphs before it stay");
assert!((at(&words, 3).origin.x - at(&plain, 3).origin.x - space).abs() < 1e-6, "the glyphs after it start a space later");
let letters =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { letter_spacing: [0.0, 50.0, 50.0], ..JustificationOptions::default() }));
assert!((at(&letters, 0).advance - (a + 0.5 * space)).abs() < 1e-6, "half a space after a");
assert!((at(&letters, 1).advance - at(&plain, 1).advance).abs() < 1e-6, "no letter spacing before a word space");
assert!((at(&letters, 4).advance - at(&plain, 4).advance).abs() < 1e-6, "nor after the last letter");
let scaled =
layout(db(), &on_path("ab cd", 1000.0, JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() }));
assert!((at(&scaled, 0).advance - 1.5 * a).abs() < 1e-6, "advance at 150%");
assert!((width(at(&scaled, 0)) - 1.5 * width(at(&plain, 0))).abs() < 1e-6, "outline at 150%");
assert!((at(&scaled, 0).scale - 1.5).abs() < 1e-9 && at(&scaled, 2).scale == 1.0, "the glyph records its scaling");
assert!((at(&scaled, 2).advance - space).abs() < 1e-6, "word spaces aren't scaled");
}
/// A right-aligned line on a path is aligned by its length at the Desired values, and a line that
/// fits at 100% word spacing runs past the end of a path it no longer fits.
#[test]
fn type_on_a_path_is_aligned_and_fitted_at_desired_spacing() {
let plain = layout(db(), &on_path("ab cd", 1000.0, JustificationOptions::default()));
let space = at(&plain, 2).advance;
let end = |l: &TextLayout| at(l, 4).origin.x + at(l, 4).advance;
let wide = JustificationOptions { word_spacing: [0.0, 300.0, 300.0], ..JustificationOptions::default() };
let mut t = on_path("ab cd", 1000.0, wide.clone());
t.para.justify = Justify::Right;
let right = layout(db(), &t);
assert!((end(&right) - 1000.0).abs() < 1e-6, "the line ends at the path's end: {}", end(&right));
let mut t = on_path("ab cd", 1000.0, JustificationOptions::default());
t.para.justify = Justify::Right;
let right_plain = layout(db(), &t);
assert!((at(&right_plain, 0).origin.x - at(&right, 0).origin.x - 2.0 * space).abs() < 1e-6, "it starts two spaces earlier");
let len = end(&plain) + 0.5 * space;
assert!(!layout(db(), &on_path("ab cd", len, JustificationOptions::default())).overflow);
let over = layout(db(), &on_path("ab cd", len, wide));
assert!(over.overflow, "the wider word space no longer fits");
}
/// Vertical type on a path takes Desired word spacing but is not glyph scaled, as in area type;
/// a list marker before the text keeps its width.
#[test]
fn vertical_type_and_list_markers_on_a_path_are_not_glyph_scaled() {
let scaling = JustificationOptions { glyph_scaling: [50.0, 150.0, 200.0], ..JustificationOptions::default() };
let vertical = |j: JustificationOptions| {
let mut t = on_path("ab cd", 1000.0, j);
t.vertical = true;
layout(db(), &t)
};
let plain = vertical(JustificationOptions::default());
let scaled = vertical(scaling.clone());
assert!((at(&scaled, 0).advance - at(&plain, 0).advance).abs() < 1e-6, "vertical glyphs keep their advance");
assert!((width(at(&scaled, 0)) - width(at(&plain, 0))).abs() < 1e-6, "and their outline");
let words = vertical(JustificationOptions { word_spacing: [0.0, 200.0, 300.0], ..JustificationOptions::default() });
assert!((at(&words, 2).advance - 2.0 * at(&plain, 2).advance).abs() < 1e-6, "a vertical word space at 200%");
use vectorcraft_doc::text::{Bullet, ParaList};
let listed = |j: JustificationOptions| {
let mut t = on_path("ab cd", 1000.0, j);
t.para.list = Some(ParaList::bulleted(Bullet::Dot));
layout(db(), &t)
};
let (plain, scaled) = (listed(JustificationOptions::default()), listed(scaling));
let marker = |l: &TextLayout| -> Vec<f64> {
let m = l.markers.first().expect("a list marker");
l.glyphs.get(m.glyphs.clone()).unwrap_or_default().iter().map(|g| g.advance * g.scale).collect()
};
assert!(!marker(&plain).is_empty());
assert_eq!(marker(&scaled), marker(&plain), "the marker keeps its width");
// The marker's glyphs have the paragraph's first byte too, with no length.
let first = |l: &TextLayout| l.glyphs.iter().find(|g| g.byte == 0 && g.len > 0).map_or(0.0, |g| g.advance);
assert!(first(&plain) > 0.0 && (first(&scaled) - 1.5 * first(&plain)).abs() < 1e-6, "the text after it is scaled");
}
/// The line's text from a layout, one string per line.
fn lines(l: &TextLayout, text: &str) -> Vec<String> {
l.lines.iter().map(|li| text.get(li.start..li.end).unwrap_or_default().trim_end().to_string()).collect()
+22 -3
View File
@@ -1,6 +1,8 @@
//! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All
//! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's
//! submenu selects them. Tool gestures emit engine commands.
//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the
//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and
//! the All Tools drawer show it, as well as in Path Precision Tools' submenu.
pub mod anchor_eraser;
pub mod box3d;
@@ -18,7 +20,8 @@ pub mod trim;
use crate::{Tool, ToolInfo};
/// Path Precision Tools' tools, one flyout group.
/// Path Precision Tools' tools, one flyout group. Its Trim at Crossings Tool ([`trim::ID`]) is in
/// the Scissors tool's group instead.
pub const PATH_TOOLS: &[ToolInfo] = &[
ToolInfo { id: anchor_eraser::ID, label: "Anchor Eraser Brush", shortcut: None, icon: "dc-remove-brush" },
ToolInfo { id: extend_path::ID, label: "Extend Path Tool", shortcut: None, icon: "dc-arrow-extend" },
@@ -27,7 +30,6 @@ pub const PATH_TOOLS: &[ToolInfo] = &[
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" },
ToolInfo { id: trim::ID, label: "Trim at Crossings Tool", shortcut: None, icon: "dc-pf-trim" },
];
/// Smart Pen's tool, a flyout group of its own.
@@ -103,4 +105,21 @@ mod tests {
assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID));
assert!(create("pen").is_none() && heading("pen").is_none());
}
/// The Trim at Crossings Tool is the add-on tool in a built-in group: the Scissors tool's,
/// after the Knife, with no default shortcut, listed once, and still made by its add-on.
#[test]
fn trim_at_crossings_is_in_the_scissors_group_once() {
let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == trim::ID)).collect();
assert_eq!(groups.len(), 1);
let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect();
let knife = ids.iter().position(|id| *id == "knife").expect("the Knife's group");
assert!(ids.contains(&"scissors"));
assert_eq!(ids.get(knife + 1), Some(&trim::ID));
let info = crate::tool_info(trim::ID).expect("catalogued");
assert_eq!((info.label, info.shortcut, info.icon), ("Trim at Crossings Tool", None, "dc-pf-trim"));
assert_eq!(create(trim::ID).map(|tool| tool.id()), Some(trim::ID));
assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on");
assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1);
}
}
+3 -2
View File
@@ -258,7 +258,7 @@ impl Tool for TrimTool {
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
Cursor::Knife
}
}
@@ -287,7 +287,8 @@ mod tests {
let up = t.pointer(&cx, &ev(PointerKind::Up, 100.5, 100.0));
assert_eq!(up, vec![Action::Exec(COMMAND.into(), json!({"at": [100.0, 100.0], "tolerance": 2.0}))], "4 px at 200%");
assert!(!t.busy());
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Crosshair);
assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Knife, "the Knife's cursor, the blade's point on the pointer");
assert_eq!(Cursor::Knife.precise(), Cursor::Crosshair, "Use Precise Cursors shows the crosshair");
}
#[test]
+3
View File
@@ -68,6 +68,9 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[
t("eraser", "Eraser Tool", Some("Shift+E"), "tool-eraser"),
t("scissors", "Scissors Tool", Some("C"), "tool-scissors"),
t("knife", "Knife", None, "tool-knife"),
// Path Precision Tools' Trim at Crossings Tool, kept out of `addons::PATH_TOOLS` so that
// `all_tools` lists it once.
t(crate::addons::trim::ID, "Trim at Crossings Tool", None, "dc-pf-trim"),
t("mirrorCut", "Mirror & Cut Tool", None, "tool-mirror-cut"),
t("lineCut", "Line Cut Tool", None, "tool-line-cut"),
t("rectCut", "Rectangle Cut Tool", None, "tool-rect-cut"),
+1 -2
View File
@@ -139,7 +139,7 @@ pub enum Cursor {
PathEraser,
/// The Join tool.
Join,
/// The Knife tool.
/// The Knife tool and the Trim at Crossings Tool.
Knife,
/// The Shaper tool.
Shaper,
@@ -339,7 +339,6 @@ impl Cursor {
| Cursor::Smooth
| Cursor::PathEraser
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::Measure
| Cursor::ObjectsOnPath
+5 -1
View File
@@ -721,8 +721,12 @@ hotspot = "The tip."
[[cursor]]
id = "Knife"
group = "Drawing and editing tools"
shown_when = ["The Knife tool: a freehand drag cuts objects along the line."]
shown_when = [
"The Knife tool: a freehand drag cuts objects along the line.",
"The Trim at Crossings Tool: a click removes the stretch of path under the pointer between its crossings, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses.",
]
hotspot = "The blade's point."
look = "A knife pointing down-left: a white blade with a straight back and a curved edge, and a black handle."
[[cursor]]
id = "Scissors"
+116 -11
View File
@@ -67,6 +67,9 @@ pub struct DimensionTool {
snap: crate::guides::DrawSnap,
/// Where the next Linear pick lands, as last worked out for the pointer (for the overlays).
snapped: Option<(Point, Option<PointRef>)>,
/// Whether the last Linear pick worked out landed on the end of a line of a dimension already
/// drawn (shown as an anchor).
on_end: bool,
/// Whether the press under way began on an anchor a Linear click picks.
press_on_anchor: bool,
/// The second point clicked for the Linear dimension being placed, and where the pointer was
@@ -199,6 +202,89 @@ fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
best.map(|(_, at, r)| (at, r))
}
/// Where a pick at `p` lands on the artwork of the visible, unlocked dimensions already drawn,
/// with no link to it: the nearest end of one of their lines (dimension and extension lines)
/// within the anchor reach, as an anchor (`true`); else the nearest point of one of those lines
/// within 8 pixels (`false`). The end of an extension line next to the point it measures is not
/// an end here: it lies a few points off that point. Only with Smart Guides or Snap to Point on.
/// Bounded work, and the topmost dimension wins a tie, as in [`anchor_under`].
fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> {
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveNearest};
#[derive(Default)]
struct Best {
end: Option<(f64, Point)>,
line: Option<(f64, Point)>,
}
/// `measured`: a linear dimension's measured points and how far its extension lines start
/// from them.
fn lines(n: &Node, measured: Option<([Point; 2], f64)>, p: Point, reach: [f64; 2], budget: &mut usize, best: &mut Best) {
if *budget == 0 || !n.visible || n.locked {
return;
}
if let Some(path) = n.path_data() {
// Open subpaths only: the lines, not a filled arrowhead.
for sp in path.subpaths.iter().filter(|sp| !sp.closed) {
// An extension line starts at the offset from its measured point and runs straight
// away from it; the dimension line runs across that direction. With no offset its
// start is the measured point itself, and stays an end.
let extension_start = |a: Point, b: Point| {
measured.is_some_and(|(points, offset)| {
points.iter().any(|m| {
let (out, along) = (a - *m, b - a);
offset > 1e-6 && (out.hypot() - offset).abs() <= 1e-6 && out.dot(along) >= (1.0 - 1e-6) * out.hypot() * along.hypot()
})
})
};
let (Some(first), Some(last)) = (sp.anchors.first(), sp.anchors.last()) else { continue };
let skip_first = extension_start(first.p, last.p);
for a in [first, last].into_iter().skip(usize::from(skip_first)) {
let d = a.p.distance(p);
if d <= reach[0] && best.end.is_none_or(|(near, _)| d < near) {
best.end = Some((d, a.p));
}
}
for i in 0..sp.segment_count() {
if *budget == 0 {
return;
}
*budget -= 1;
let c = sp.segment(i);
let q = c.eval(c.nearest(p, 1e-4).t);
let d = q.distance(p);
if q.x.is_finite() && q.y.is_finite() && d <= reach[1] && best.line.is_none_or(|(near, _)| d < near) {
best.line = Some((d, q));
}
}
}
}
for c in n.children().into_iter().flatten().rev() {
lines(c, measured, p, reach, budget, best);
}
}
fn visit(n: &Node, p: Point, reach: [f64; 2], budget: &mut usize, best: &mut Best) {
if *budget == 0 || !n.visible || n.locked {
return;
}
*budget -= 1;
if let Some(d) = &n.extras().dimension {
let measured = (d.mode == DimensionMode::Linear).then_some(([d.a, d.b], d.options.extension_offset));
lines(n, measured, p, reach, budget, best);
return;
}
for c in n.children().into_iter().flatten().rev() {
visit(c, p, reach, budget, best);
}
}
if !(cx.smart_guides || cx.snap_to_point) {
return None;
}
let (reach, mut budget, mut best) = ([cx.tol(ANCHOR_REACH), cx.tol(8.0)], 20_000usize, Best::default());
for n in cx.doc.layers.iter().rev() {
visit(n, p, reach, &mut budget, &mut best);
}
best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false)))
}
/// The point of `edge` closest to `p`.
fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
@@ -239,12 +325,13 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb):
impl DimensionTool {
/// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as
/// a link to its path); else where Smart Guides put it (another object's anchor or centre, in
/// a link to its path), labeled "anchor"; else on the nearest end of a line of a dimension
/// already drawn, within the same reach (no link), also labeled "anchor"; else where Smart Guides put it (another object's anchor or centre, in
/// line with one, or for the second point square to a segment or grazing a curve from the
/// first with Snap to Perpendicular or Snap to Tangent on, or on a construction guide through
/// a first point picked on an anchor), its guides showing; else on the closest point of the
/// line under the pointer; else `p` itself. A first point not on an anchor has no
/// construction guides through it.
/// line under the pointer, of the art or of a dimension, labeled "path"; else `p` itself. A
/// first point not on an anchor has no construction guides through it.
/// A point the guides leave where the pointer is (right on a guide line) stays there, and with
/// Snap to Pixel or Snap to Grid on a point stays where they place it.
fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option<PointRef>) {
@@ -253,15 +340,31 @@ impl DimensionTool {
None => crate::guides::Leave::contact(*first),
});
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
self.on_end = false;
if let Some((point, reference)) = anchor_under(cx, p) {
self.snap.clear();
self.snap.label(point, "anchor");
return (point, Some(reference));
}
let drawn = on_dimensions(cx, p);
if let Some((q, true)) = drawn {
self.on_end = true;
self.snap.label(q, "anchor");
return (q, None);
}
if guided.distance(p) > 1e-9 || !self.snap.guides().is_empty() || cx.snap_to_pixel || cx.snap_to_grid {
return (guided, None);
}
// Not on an anchor or a guide: snap to the closest point of the line (#2432).
(pick(cx, p).and_then(|e| nearest_on(cx, &e, p)).unwrap_or(p), None)
// Not on an anchor or a guide: snap to the closest point of the line (#2432), of the art
// or of a dimension already drawn.
let art = pick(cx, p).and_then(|e| nearest_on(cx, &e, p));
let line = drawn.map(|(q, _)| q);
match art.into_iter().chain(line).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p))) {
Some(q) => {
self.snap.label(q, "path");
(q, None)
}
None => (p, None),
}
}
fn target(&self, cx: &ToolContext, p: Point) -> Option<Target> {
let edge = pick(cx, p)?;
@@ -384,6 +487,7 @@ impl DimensionTool {
self.pending = None;
self.press = None;
self.press_on_anchor = false;
self.on_end = false;
self.points.clear();
self.lines.clear();
self.dragging = false;
@@ -498,10 +602,11 @@ impl Tool for DimensionTool {
self.press = Some((ev.pos, None));
return self.preview(cx, ev.pos);
}
// A Linear press on an anchor picks the anchor unless it drags past the anchor's
// reach: moving a few pixels before the release does not drag out the dimension of
// a segment under the pointer.
self.press_on_anchor = self.kind == Kind::Linear && anchor_under(cx, ev.pos).is_some();
// A Linear press on an anchor, or on the end of a dimension's line, picks it unless
// it drags past the anchor's reach: moving a few pixels before the release does not
// drag out the dimension of a segment under the pointer.
self.press_on_anchor =
self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
self.press = Some((ev.pos, self.target(cx, ev.pos)));
vec![]
}
@@ -617,7 +722,7 @@ impl Tool for DimensionTool {
if let Some((q, reference)) = &snapped
&& (reference.is_some() || q.distance(self.at) > 1e-9)
{
let on_anchor = reference.is_some();
let on_anchor = reference.is_some() || self.on_end;
out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } });
}
if let Some((p, _)) = self.points.last() {
+39 -4
View File
@@ -25,8 +25,9 @@
//! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]).
//! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the
//! pointer ([`release_guide_at`]).
//! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which
//! drag together; a key object on a point moves with it) and, once a point is clicked, its
//! Direct Selection also edits a blend's spine: drag its points (Shift-click and, on a selected
//! blend, the marquee pick several, which drag together; a key object on a point moves with it)
//! and, once a point is clicked, its
//! handles; and the points of selected gradient meshes
//! and of mesh and warp envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several,
//! a click on a gradient mesh's line picks its two ends and one inside a patch the four points
@@ -192,7 +193,8 @@ pub struct DirectSelectionTool {
moved: Option<Vec2>,
/// The spine point last clicked (blend, anchor): its handles show and can be dragged.
spine: Option<(NodeId, usize)>,
/// Other points of that spine picked with it (Shift-click adds or takes one away); dragging
/// Other points of that spine picked with it (Shift-click adds or takes one away, and a
/// marquee picks those inside it); dragging
/// a picked point moves them all (#5285).
spine_more: Vec<usize>,
mesh: MeshEdit,
@@ -915,6 +917,10 @@ impl Tool for DirectSelectionTool {
if let Some(out) = self.press_hidden(cx, ev, p) {
return out;
}
// The spine points picked before stay picked while the marquee is drawn: its
// release replaces them (with Shift, toggles them), and Escape keeps them.
self.spine = held;
self.spine_more = if held.is_some() { more } else { vec![] };
self.state = State::Marquee { start: p, cur: p, toggle: ev.mods.shift, enclosed: false, whole: ev.mods.alt };
vec![]
}
@@ -1641,12 +1647,14 @@ impl DirectSelectionTool {
return vec![];
}
self.frame.clear();
(self.spine, self.spine_more) = (None, vec![]);
return vec![Action::Exec("select.none".into(), json!({}))];
}
// With Group Selection's enclosed marquee, the tool selects the objects inside it
// (members of groups too), each whole, as a click selects one; with an Alt-marquee, every
// object it touches, each whole.
if enclosed || whole {
(self.spine, self.spine_more) = (None, vec![]);
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline);
let editable = cx.doc.editable();
touched.retain(|id| editable(*id));
@@ -1702,6 +1710,33 @@ impl DirectSelectionTool {
}
}
}
// Direct Selection: the points of a selected blend's spine inside the rect are picked, on
// the topmost such blend; with Shift they are toggled. The blend stays selected. A plain
// marquee that holds none of them drops the points picked before.
let mut spined: Option<NodeId> = None;
if !self.group {
let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| {
let inside: BTreeSet<usize> = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect();
(!inside.is_empty()).then_some((id, inside))
});
match found {
Some((id, inside)) => {
let held = self.spine.filter(|(h, _)| toggle && *h == id);
let before: BTreeSet<usize> = held.map(|(_, a)| self.spine_more.iter().copied().chain([a]).collect()).unwrap_or_default();
let picked: BTreeSet<usize> = if toggle { before.symmetric_difference(&inside).copied().collect() } else { inside };
let focus = held.map(|(_, a)| a).filter(|a| picked.contains(a)).or_else(|| picked.last().copied());
self.spine = focus.map(|a| (id, a));
self.spine_more = picked.into_iter().filter(|a| Some(*a) != focus).collect();
spined = Some(id);
if !toggle {
sel.push((id, vec![]));
}
}
None if !toggle => (self.spine, self.spine_more) = (None, vec![]),
// With Shift, the blend holding the picked points stays selected with them.
None => spined = self.spine.map(|(id, _)| id),
}
}
let mut marked: BTreeMap<NodeId, BTreeSet<AnchorRef>> =
if toggle { self.frame_anchors(cx).into_iter().map(|(id, v)| (id, v.into_iter().collect())).collect() } else { BTreeMap::new() };
for (id, inside) in &framed {
@@ -1721,7 +1756,7 @@ impl DirectSelectionTool {
// the marquee touches them, as with the Selection tool (#927).
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) {
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) {
if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) {
sel.push((id, vec![]));
}
}
+131
View File
@@ -246,6 +246,137 @@ fn shift_click_picks_several_spine_points_which_drag_together() {
assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 0 && v.get("with").is_none()), "{a:?}");
}
/// [`blend_doc`] with a spine through (110, 310), (160, 310) and (210, 310).
fn blend_doc_with_three_spine_points() -> (vectorcraft_doc::Document, NodeId) {
let (mut d, g, _) = blend_doc();
let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(160.0, 310.0), Point::new(210.0, 310.0)], false);
let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") };
(spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![0, 2]);
(d, g)
}
/// A marquee drawn with Direct Selection from `from` to `to`, released.
fn spine_marquee(t: &mut DirectSelectionTool, cx: &ToolContext, from: (f64, f64), to: (f64, f64), mods: Mods) -> Vec<Action> {
assert_eq!(t.pointer(cx, &PointerEvent::new(PointerKind::Down, from.0, from.1).with_mods(mods)), vec![]);
t.pointer(cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1).with_mods(mods));
assert!(t.overlays(cx).iter().any(|o| matches!(o, Overlay::Marquee(_))), "a marquee");
t.pointer(cx, &PointerEvent::new(PointerKind::Up, to.0, to.1).with_mods(mods))
}
/// A Direct Selection marquee picks the points of a selected blend's spine inside it, which then
/// drag together, and keeps the blend selected; a marquee around none of them drops the picks.
#[test]
fn marquee_picks_selected_blend_spine_points_which_drag_together() {
let (d, g) = blend_doc_with_three_spine_points();
let mut s = Selection::default();
s.set([g]);
let p = paint();
let cx = cx(&d, &s, &p);
let filled = |t: &DirectSelectionTool| t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Anchor { filled: true, .. })).count();
let mut t = DirectSelectionTool::new(false);
// Around (160, 310) and (210, 310), the second on the rect's edge.
let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (160.0, 290.0), Mods::default());
assert!(
matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["mode"] == "set" && v["items"].as_array().is_some_and(|i| i.iter().any(|i| i["id"] == g.0))),
"the blend stays selected: {a:?}"
);
assert_eq!(filled(&t), 2, "both picked points show");
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0));
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 330.0));
assert_eq!(
a.last(),
Some(&Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": g.0, "anchor": 2, "x": 210.0, "y": 330.0, "with": [1]})))
);
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 330.0)), vec![Action::Commit]);
// A marquee around none of the points drops them.
spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), Mods::default());
assert_eq!((t.spine, filled(&t)), (None, 0));
}
/// With Shift, a Direct Selection marquee toggles the spine points inside it: a picked one leaves,
/// another joins, and those outside it keep their state; the blend is not toggled away.
#[test]
fn shift_marquee_toggles_selected_blend_spine_points() {
let (d, g) = blend_doc_with_three_spine_points();
let mut s = Selection::default();
s.set([g]);
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Mods::default() };
let mut t = DirectSelectionTool::new(false);
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0));
let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (150.0, 290.0), shift);
assert!(
matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))),
"the blend is not toggled: {a:?}"
);
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![]));
spine_marquee(&mut t, &cx, (130.0, 330.0), (90.0, 290.0), shift);
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0]));
// A Shift-marquee around none of them keeps them, and keeps the blend selected when it
// touches the blend's art.
spine_marquee(&mut t, &cx, (300.0, 330.0), (240.0, 290.0), shift);
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0]));
let a = spine_marquee(&mut t, &cx, (230.0, 330.0), (205.0, 315.0), shift);
assert!(
matches!(a.first(), Some(Action::Exec(c, v)) if c == "select.anchorsMany" && v["items"].as_array().is_some_and(|i| !i.iter().any(|i| i["id"] == g.0))),
"the blend is not toggled: {a:?}"
);
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![0]));
}
/// A Direct Selection marquee does not pick the spine points of a blend that is not selected, or
/// of a selected blend that is locked or hidden.
#[test]
fn marquee_skips_unselected_locked_and_hidden_blend_spines() {
let (d, g) = blend_doc_with_three_spine_points();
let p = paint();
let mut s = Selection::default();
let none = cx(&d, &s, &p);
let mut t = DirectSelectionTool::new(false);
spine_marquee(&mut t, &none, (230.0, 330.0), (150.0, 290.0), Mods::default());
assert_eq!(t.spine, None, "not selected");
s.set([g]);
for lock in [true, false] {
let mut d = d.clone();
let Some(n) = d.node_mut(g) else { panic!("blend") };
if lock {
n.locked = true;
} else {
n.visible = false;
}
let c = cx(&d, &s, &p);
let mut t = DirectSelectionTool::new(false);
spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default());
assert_eq!(t.spine, None, "locked: {lock}");
}
// The same marquee on the selected blend picks them.
let c = cx(&d, &s, &p);
let mut t = DirectSelectionTool::new(false);
spine_marquee(&mut t, &c, (230.0, 330.0), (150.0, 290.0), Mods::default());
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 2)), vec![1]));
}
/// Escape during a Direct Selection marquee cancels it and keeps the spine points picked before.
#[test]
fn escape_cancels_a_marquee_and_keeps_the_picked_spine_points() {
let (d, g) = blend_doc_with_three_spine_points();
let mut s = Selection::default();
s.set([g]);
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = DirectSelectionTool::new(false);
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 330.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 290.0));
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 290.0)), vec![]);
assert_eq!((t.spine, t.spine_more.clone()), (Some((g, 1)), vec![]));
assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Anchor { filled: true, .. })), "the picked point shows");
}
/// #1111: the Anchor Point tool bends a selected blend's straight spine; Direct Selection
/// reshapes a curved spine segment and leaves a straight one alone, as it does a path's.
#[test]
+11
View File
@@ -485,6 +485,17 @@ impl DrawSnap {
self.guides.clear();
}
/// Replace the guides with one label `text` at `p`, for a point a tool placed by a rule of its
/// own (an anchor or a path it found itself). The label uses the style of the targets the last
/// snap gathered. No label shows when Smart Guides or Anchor/Path Labels are off (Snap to Point
/// alone gathers targets without labels), or when the last snap gathered no targets.
pub(crate) fn label(&mut self, p: Point, text: &str) {
self.guides = match &self.targets {
Some((_, PointSnap { targets: Some((t, _)), .. })) => t.label(p, text).into_iter().collect(),
_ => vec![],
};
}
fn gather(&mut self, cx: &ToolContext, key: SnapKey) {
let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph));
self.targets = Some((Some(key), snap));
+1 -1
View File
@@ -509,7 +509,7 @@ impl Targets {
}
/// A label `text` at `p`, unless Anchor/Path Labels are off.
fn label(&self, p: Point, text: &str) -> Option<Overlay> {
pub(super) fn label(&self, p: Point, text: &str) -> Option<Overlay> {
self.style.labels.then(|| Overlay::Label { p, text: text.into(), color: self.style.color })
}
+21
View File
@@ -177,6 +177,27 @@ pub fn is_intertwine(n: &Node) -> bool {
matches!(n.kind, NodeKind::Intertwine { .. })
}
/// Why `n` can't be in an Intertwine group, if it can't: it is or holds an Intertwine group, a
/// Repeat, a graph or a Live Paint group (the help page's limits).
pub fn refused_member(n: &Node) -> Option<&'static str> {
let mut why = None;
n.walk(&mut |c| {
why = why.or(match &c.kind {
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
NodeKind::Repeat(_) => Some("a Repeat"),
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
NodeKind::Group { .. } if crate::builder::is_live_paint(c) => Some("a Live Paint group"),
_ => None,
});
});
why
}
/// Whether `id` is an Intertwine group or lies inside one.
pub fn in_intertwine(doc: &Document, id: NodeId) -> bool {
doc.ancestry(id).unwrap_or_default().iter().any(|a| doc.node(*a).is_some_and(is_intertwine))
}
// ---------- the tool ----------
/// The overlap areas of an Intertwine group, kept for the document revision they were found in.
+3 -2
View File
@@ -696,6 +696,7 @@ mod cursor_tests {
("pathEraser", Cursor::PathEraser),
("join", Cursor::Join),
("knife", Cursor::Knife),
(addons::trim::ID, Cursor::Knife),
("shaper", Cursor::Shaper),
("livePaintBucket", Cursor::LivePaintBucket),
("measure", Cursor::Measure),
@@ -713,10 +714,10 @@ mod cursor_tests {
assert_eq!(cursor_of(id), c, "{id}");
assert_eq!(c.precise(), Cursor::Crosshair, "{id}");
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. The
// Live Paint Bucket's bucket is drawn.
// Live Paint Bucket's bucket and the Knife's knife are drawn.
let stand_in = match id {
"mesh" => Some(Cursor::PenAdd),
"blobBrush" | "eraser" | "livePaintBucket" => None,
"blobBrush" | "eraser" | "livePaintBucket" | "knife" | addons::trim::ID => None,
_ => Some(Cursor::Crosshair),
};
assert_eq!(c.stand_in(), stand_in, "{id}");
+35 -15
View File
@@ -206,14 +206,14 @@ enum DistanceTo {
}
/// Distance Guides: with Smart Guides and Smart Guides → Invoke Distance Guides on, something
/// selected and Alt held (`m`), the object under `p` unless it is selected, or over no object the
/// artboard `p` is on.
/// selected and Alt held (`m`), the object under `p` unless it or selected art inside it is under
/// `p` ([`selected_under`]), or over no object the artboard `p` is on.
fn distance_target(cx: &ToolContext, p: Point, m: Mods) -> Option<DistanceTo> {
if !(cx.smart_guides && cx.distance_guides && m.alt) || cx.selection.objects.is_empty() {
return None;
}
match hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| h.top_object(cx.isolation)) {
Some(id) => (!cx.selection.contains(id)).then_some(DistanceTo::Object(id)),
match hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| (h.top_object(cx.isolation), h)) {
Some((id, h)) => selected_under(cx, &h, id).is_none().then_some(DistanceTo::Object(id)),
None => cx.doc.artboard_at(p).map(DistanceTo::Artboard),
}
}
@@ -686,12 +686,16 @@ impl SelectionTool {
return None;
}
let reach = cx.tol(HOVER_REACH);
let under = hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| h.top_object(cx.isolation));
let hit = hit_test(cx.doc, p, cx.selection_hit_options());
let under = hit.as_ref().map(|h| h.top_object(cx.isolation));
let nearest = |points: &mut dyn Iterator<Item = Point>| {
points.filter(|q| q.distance(p) <= reach).min_by(|a, b| a.distance(p).total_cmp(&b.distance(p)))
};
// A press on an unselected object selects it alone: the selected ones stay behind.
let selected = if under.is_none_or(|u| cx.selection.contains(u)) { &cx.selection.objects[..] } else { &[] };
// A press on an unselected object selects it alone: the selected ones stay behind. A press
// on selected art inside it keeps the selection, and that art is the object grabbed.
let kept = hit.as_ref().zip(under).and_then(|(h, u)| selected_under(cx, h, u));
let under = kept.or(under);
let selected = if hit.is_none() || kept.is_some() { &cx.selection.objects[..] } else { &[] };
with_object_bounds(cx, |bounds| {
under.into_iter().chain(selected.iter().copied()).find_map(|id| {
let n = cx.doc.node(id)?;
@@ -1008,10 +1012,12 @@ impl Tool for SelectionTool {
let (mut deselect, mut key, mut exclude) = (None, None, None);
if m.shift {
(deselect, exclude) = shift_press(cx, &h, top, &mut out);
} else if !cx.selection.contains(top) {
} else if let Some(picked) = selected_under(cx, &h, top) {
if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt {
key = Some(picked);
}
} else {
out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] })));
} else if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt {
key = Some(top);
}
// Grabbed by no anchor or centre, a press on a path's stroke or beside its
// edge holds the path there, and that point of it snaps (#3701).
@@ -1324,7 +1330,7 @@ impl Tool for SelectionTool {
return Cursor::Move;
}
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
if cx.selection.contains(h.top_object(cx.isolation)) || m.alt {
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
return Cursor::Move;
}
return Cursor::Arrow;
@@ -1341,16 +1347,30 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option<NodeId> {
stack.get(next).or(stack.first()).copied()
}
/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object out of the selection
/// when it is released, and a Shift-drag moves the selection, constrained. On an object of the
/// The selected object a press on `h` lands on: `top` when it is selected, else the outermost
/// object selected whole between it and the art under the pointer, such as members of a group
/// picked with Group Selection. A press there keeps the selection and a drag moves it (#8047). A
/// member with only some anchors or segments selected does not count: the press selects `top`.
fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option<NodeId> {
if cx.selection.contains(top) {
return Some(top);
}
let whole = |id: NodeId| cx.selection.contains(id) && cx.selection.partial(id).is_none() && !cx.selection.segments.contains_key(&id);
let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default());
below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id))
}
/// A Shift-press on `top` (hit by `h`): a Shift-click takes a selected object, or the selected art
/// inside it that the press lands on ([`selected_under`]), out of the selection when it is
/// released, and a Shift-drag moves the selection, constrained. On an object of the
/// Global Edit that is highlighted, the release leaves that object out of the edit instead, and a
/// drag selects `top` when it starts. Returns the object to deselect and the object to leave out
/// on release (with `top`); adds to `out` the action that selects `top` at once.
fn shift_press(cx: &ToolContext, h: &Hit, top: NodeId, out: &mut Vec<Action>) -> (Option<NodeId>, Option<(NodeId, NodeId)>) {
if let Some(member) = global_edit_member(cx, h) {
(None, Some((member, top)))
} else if cx.selection.contains(top) {
(Some(top), None)
} else if let Some(picked) = selected_under(cx, h, top) {
(Some(picked), None)
} else {
out.push(Action::Exec("select.toggle".into(), json!({ "id": top.0 })));
(None, None)
+61
View File
@@ -2665,3 +2665,64 @@ fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() {
assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]);
assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]);
}
/// Objects selected inside a group (with Group Selection, say) stay selected when the Selection
/// tool presses on one of them: the press shows the move pointer and a drag moves only them, not
/// the group around them. A press on a member that is not selected still selects the whole group.
#[test]
fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
use vectorcraft_doc::{Appearance, Document, Node};
use vectorcraft_geom::shapes;
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let (outer, inner, a, b, c) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
let path = |id: NodeId, x: f64| Node::path(id, shapes::rectangle(Rect::new(x, 100.0, x + 50.0, 150.0)), Appearance::default_art());
d.insert(Some(l), 0, Node::group(outer, vec![])).unwrap();
d.insert(Some(outer), 0, Node::group(inner, vec![])).unwrap();
d.insert(Some(inner), 0, path(a, 100.0)).unwrap();
d.insert(Some(inner), 1, path(b, 200.0)).unwrap();
d.insert(Some(outer), 1, path(c, 300.0)).unwrap();
let p = paint();
let is_select = |out: &[Action]| out.iter().any(|a| matches!(a, Action::Exec(id, _) if id.starts_with("select.")));
for picked in [vec![a], vec![a, b], vec![inner]] {
let mut s = Selection::default();
s.set(picked.iter().copied());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "{picked:?}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "{picked:?}: {drag:?}");
// Shift: a drag moves the selected members, constrained, and a click takes the member
// pressed (or the selected group holding it) out of the selection, not the outer group.
let shift = |kind, x, y| ev(kind, x, y).with_mods(Mods { shift: true, ..Mods::default() });
let mut t = SelectionTool::default();
let down = t.pointer(&c, &shift(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "Shift, {picked:?}: {down:?}");
let drag = t.pointer(&c, &shift(PointerKind::Drag, 145.0, 125.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(c, _) if c == "object.transform")), "Shift, {picked:?}: {drag:?}");
let mut t = SelectionTool::default();
t.pointer(&c, &shift(PointerKind::Down, 125.0, 125.0));
let up = t.pointer(&c, &shift(PointerKind::Up, 125.0, 125.0));
assert_eq!(up, vec![Action::Exec("select.toggle".into(), json!({"id": picked[0].0}))], "Shift-click, {picked:?}");
// Alt over a selected member measures no Distance Guides to the group holding it.
let mut t = SelectionTool::default();
t.pointer(&c, &alt(PointerKind::Move, 125.0, 125.0));
assert!(distances(&t, &c).0.is_empty(), "Alt over a selected member, {picked:?}");
}
// A member that is not selected: the press selects the outermost group.
let mut s = Selection::default();
s.set([a]);
let c = cx(&d, &s, &p);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 325.0, 125.0));
assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]);
// A member with only some anchors selected (a Direct Selection marquee) is not selected whole:
// the press selects the outermost group, as before.
let mut s = Selection::default();
s.set([a]);
s.anchors.insert(a, [(0, 0)].into_iter().collect());
let c = cx(&d, &s, &p);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert_eq!(down, vec![Action::Exec("select.set".into(), json!({"ids": [outer.0]}))]);
}
+71 -1
View File
@@ -16,6 +16,9 @@
//!
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
//! the open dialog (`brushKeyColor` UI request) and switches back.
//!
//! Escape ends either pick without sampling and switches back to that tool. With neither pick
//! armed, Escape is left to the application.
use std::collections::HashSet;
@@ -28,7 +31,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
use super::paint_owner;
use crate::params::color_json;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
#[derive(Default)]
pub struct EyedropperTool {
@@ -530,6 +533,38 @@ impl Tool for EyedropperTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
Cursor::Eyedropper
}
/// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the
/// tool that armed it.
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape || !self.picking() {
return vec![];
}
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
self.brush_key_color = false;
vec![Action::SwitchTool(back)]
}
/// A dropped press (a long or canceled touch) leaves an armed pick waiting for its click.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
vec![]
}
/// Escape is the tool's while a pick is armed, so it switches back and ends nothing else.
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
key == ToolKey::Escape && self.picking()
}
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.picking()
}
}
impl EyedropperTool {
/// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)?
fn picking(&self) -> bool {
self.stop.is_some() || self.brush_key_color
}
}
#[cfg(test)]
@@ -619,6 +654,41 @@ mod tests {
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only");
}
/// #8024: Escape ends a gradient stop's pick and a Key Color pick without sampling and
/// switches back; the plain Eyedropper leaves Escape alone.
#[test]
fn escape_ends_a_pick_and_switches_back() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let mut cx = cx(&d, &s, &p);
cx.gradient_stop = Some(1);
let none = Mods::default();
let mut t = EyedropperTool::default();
assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx), "nothing armed");
assert!(t.key(&cx, ToolKey::Escape, none).is_empty());
t.set_option("stop", &json!("gradient"));
assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx));
assert!(!t.claims_key(&cx, ToolKey::Enter));
assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves the pick armed");
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("gradient".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(!t.claims_key(&cx, ToolKey::Escape) && t.key(&cx, ToolKey::Escape, none).is_empty(), "one cancel only");
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0));
assert!(!a.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("stop").is_some())), "no stop sample after the cancel: {a:?}");
t.set_option("brushKeyColor", &json!(true));
t.set_option("stop", &json!("paintbrush"));
assert!(t.claims_key(&cx, ToolKey::Escape));
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("paintbrush".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
// A Key Color pick with no tool to return to goes back to the Selection tool.
t.set_option("brushKeyColor", &json!(true));
assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("selection".into())]);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
}
#[test]
fn brush_key_color_samples_into_the_dialog_then_switches_back() {
let (d, _) = doc_with_rect();
+23 -10
View File
@@ -4,8 +4,9 @@
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; the list is kept until the document changes.
//! with a Select button; each document's list is kept until that document changes.
use std::collections::HashMap;
use std::sync::{Arc, Weak};
use egui::{Align, Layout, Sense, Ui, vec2};
@@ -31,7 +32,7 @@ pub const ROLES: &[(&str, &str)] =
/// Where the panel keeps the last `addon.packaging.roles` answer (panel state).
const STATE: &str = "fold-lines";
/// Where the panel keeps the last check (panel state).
/// Where the panel keeps the last check of each document (panel state, a [`Checks`]).
const CHECKED: &str = "fold-lines-check";
/// Object › Plug-ins › Packaging Tools.
@@ -103,6 +104,10 @@ impl Checked {
}
}
/// The last check of each document, by the document's id. The checks are shared, so reading the
/// map for a frame copies no issue lists.
type Checks = HashMap<u64, Arc<Checked>>;
/// The active document's [`DocKey`].
fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc)))
@@ -110,11 +115,17 @@ fn doc_key(app: &VectorcraftApp) -> Option<DocKey> {
/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept
/// in `ctx` for the panel.
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Checked> {
fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option<Arc<Checked>> {
let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?;
let checked = Checked::of(doc_key(app)?, &r);
let key = doc_key(app)?;
let uid = key.0;
let checked = Arc::new(Checked::of(key, &r));
app.status(checked.summary());
set_pstate(ctx, CHECKED, checked.clone());
let mut checks: Checks = pstate(ctx, CHECKED);
// A check of a document that has since changed or closed can never be shown again.
checks.retain(|_, c| c.key.as_ref().is_some_and(|(_, doc)| doc.strong_count() > 0));
checks.insert(uid, Arc::clone(&checked));
set_pstate(ctx, CHECKED, checks);
Some(checked)
}
@@ -130,11 +141,13 @@ pub(crate) fn check(app: &mut VectorcraftApp, p: Value) {
}
/// The last check of the active document, while the document has not changed since.
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Checked> {
let checked: Checked = pstate(ctx, CHECKED);
let same = match (&checked.key, doc_key(app)) {
(Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(&current),
_ => false,
fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option<Arc<Checked>> {
let (now, current) = doc_key(app)?;
let mut checks: Checks = pstate(ctx, CHECKED);
let checked = checks.remove(&now)?;
let same = match &checked.key {
Some((uid, doc)) => *uid == now && doc.ptr_eq(&current),
None => false,
};
same.then_some(checked)
}
@@ -212,6 +212,28 @@ fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() {
assert!(text.contains("No issues found.") && text.contains("Panels: 2, hinges: 1, errors: 0, warnings: 0"), "{text}");
}
#[test]
fn each_document_keeps_its_own_check() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _) = blank();
let ctx = egui::Context::default();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
// A second document, checked too: it has no cut lines.
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let text = frames(&mut app, &ctx, Some("Check"));
assert!(text.contains("No cut lines are in the document.") && !text.contains("A cut line ends"), "{text}");
// Back on the first document, unchanged since its check: its issues are still listed.
assert!(app.session.set_active(0));
let text = frames(&mut app, &ctx, None);
assert!(text.contains("A cut line ends without meeting another cut line."), "{text}");
assert!(text.contains("Panels: 2, hinges: 1, errors: 1, warnings: 0"), "{text}");
// And the second document's check stays its own.
assert!(app.session.set_active(1));
let text = frames(&mut app, &ctx, None);
assert!(text.contains("No cut lines are in the document.") && !text.contains("A cut line ends"), "{text}");
}
#[test]
fn issues_and_the_summary_show_in_the_interface_language() {
let (mut app, _) = blank();
@@ -25,6 +25,7 @@ fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() {
("Trim at Crossings Tool", "trimAtCrossings"),
] {
let e = under(label).expect(label);
assert_eq!(vectorcraft_tools::tool_info(tool).map(|t| t.label), Some(label), "the toolbar's label");
assert_eq!((e.command.as_deref(), &e.params), (Some("tool.select"), &json!({ "tool": tool })));
menus::invoke(&mut app, "tool.select", e.params.clone());
assert_eq!(app.session.tool_id(), tool);
+2 -1
View File
@@ -127,6 +127,8 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
// The system has no tip outline to go round: its crosshair aims as well.
Cursor::BlobBrush | Cursor::Eraser => C::Crosshair,
Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge => C::Crosshair,
// The system has no knife: its crosshair aims at the blade's point.
Cursor::Knife => C::Crosshair,
// Not drawn yet: the cursor each borrows.
Cursor::Lasso
| Cursor::MagicWand
@@ -135,7 +137,6 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
| Cursor::Smooth
| Cursor::PathEraser
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::Measure
| Cursor::PrintTiling
+1 -5
View File
@@ -22,11 +22,7 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool {
/// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour,
/// a gradient's stops or a mesh's points, which Recolor Artwork can change.
pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool {
ids.iter().filter_map(|id| doc.node(*id)).any(|n| {
let mut found = false;
vectorcraft_doc::swatches::node_colors(n, &mut |_, _| found = true);
found
})
ids.iter().filter_map(|id| doc.node(*id)).any(vectorcraft_doc::swatches::node_has_colors)
}
/// The bounds of the artboards the Artboard tool has selected ([`crate::panels::artboards::picked`]).
+22
View File
@@ -11228,6 +11228,28 @@ fn the_task_bar_recolors_coloured_art() {
assert!(app.ui.dialog.is_none(), "no Recolor button without colours");
}
/// Recolor Artwork shows in the bars when any selected object has a color, whichever of them it is,
/// and not for an empty selection or ids that are gone.
#[test]
fn has_colors_looks_at_every_selected_object() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let mut rect = |x: i32| {
vectorcraft_doc::NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap())
};
let (blank, colored) = (rect(10), rect(80));
s.execute("paint.setFill", &json!({"ids": [blank.0], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [blank.0], "none": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [colored.0], "color": "#cc3322"})).unwrap();
let doc = &s.active().unwrap().doc;
let gone = vectorcraft_doc::NodeId(u64::MAX);
assert!(!has_colors(doc, &[]), "nothing selected");
assert!(!has_colors(doc, &[gone]), "an id that is gone");
assert!(!has_colors(doc, &[blank, gone]));
assert!(has_colors(doc, &[blank, colored]), "the color is on the second object");
assert!(has_colors(doc, &[colored, blank, gone]), "the color is on the first object");
}
/// The Contextual Task Bar's Lock button locks the selected member in isolation mode and the
/// selected group outside isolation mode.
#[test]
+18
View File
@@ -468,6 +468,23 @@ fn paint_brush(p: &mut Ink, o: Pos2) {
}
}
/// The Knife and the Trim at Crossings Tool: a knife, the blade's point on the hotspot, the white
/// blade with its straight back and curved edge, then the black handle running up-right.
fn knife(p: &mut Ink, o: Pos2) {
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
let blade = vec![at(0.0, 0.0), at(11.0, -2.5), at(11.0, 3.0), at(6.0, 2.8), at(2.5, 1.6)];
let handle = vec![at(11.0, -2.0), at(20.0, -1.8), at(21.0, 0.2), at(20.0, 2.2), at(11.0, 2.5)];
// Both halos first, so neither covers the other's outline.
for part in [&blade, &handle] {
p.add(Shape::closed_line(part.clone(), Stroke::new(3.0, HALO)));
}
for (part, fill) in [(blade, HALO), (handle, INK)] {
p.add(Shape::convex_polygon(part.clone(), fill, Stroke::NONE));
p.add(Shape::closed_line(part, Stroke::new(1.0, INK)));
}
}
/// Live Paint Selection: the solid arrow with a badge at its lower right saying what a click
/// selects: a filled square over a face ([`Cursor::LivePaintSelectFace`]), a short line between two
/// anchor marks over an edge ([`Cursor::LivePaintSelectEdge`]), an x where it selects nothing.
@@ -732,6 +749,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::LivePaintBucket => paint_bucket(ink, p, false),
Cursor::LivePaintBucketFace => paint_bucket(ink, p, true),
Cursor::LivePaintBucketEdge => paint_brush(ink, p),
Cursor::Knife => knife(ink, p),
Cursor::LivePaintSelectFace | Cursor::LivePaintSelectEdge | Cursor::LivePaintSelectOutside => live_paint_select(ink, p, c),
Cursor::Hand => hand(ink, p, false),
Cursor::HandGrab => hand(ink, p, true),
+28
View File
@@ -336,6 +336,34 @@ fn the_live_paint_bucket_shows_a_bucket_or_a_brush() {
}
}
/// The Knife's cursor, which the Trim at Crossings Tool shows too, is drawn, not the crosshair: a
/// knife with the blade's point on the hotspot, the white blade, then the black handle up-right.
#[test]
fn the_knife_shows_a_knife_with_its_point_on_the_hotspot() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, knife, brush) = (img(Cursor::Crosshair), img(Cursor::Knife), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(at(&knife, 0.0, 0.0)[3] > 0, "the point covers the hotspot at {ppp}");
assert!(white(at(&knife, 8.0, 0.5)), "the white blade at {ppp}");
assert!(inked(at(&knife, 16.0, 0.2)), "the black handle at {ppp}");
assert!(!inked(at(&knife, -4.0, 0.0)), "nothing beyond the point at {ppp}");
assert!(Cursor::Knife.stand_in().is_none(), "the Knife is drawn");
assert_ne!(knife, cross, "the Knife is not the crosshair at {ppp}");
assert_ne!(knife, brush, "the Knife is not the Live Paint brush at {ppp}");
assert_eq!(rasterize(Cursor::Knife.precise(), ppp).as_ref(), Some(&cross), "with Use Precise Cursors at {ppp}");
}
}
/// Live Paint Selection's cursors are the solid arrow, its tip on the hotspot, with a badge at its
/// lower right: a filled square over a face, a line between two anchor marks over an edge, and an x
/// where a click selects nothing.
+6
View File
@@ -704,6 +704,12 @@ pub fn cancel(app: &mut VectorcraftApp) {
script_run::notice_cancel(app, &d);
}
missing_links::cancelled(app, &d);
// Find Font's next open starts with an empty replacement search.
if d.kind == "findFont"
&& let Some(ctx) = app.ui_ctx.clone()
{
crate::find_font::clear_search(&ctx);
}
// Toolbar-only Flare options start no preview and must not cancel a gesture
// that was already active before opening them. The generic parameter dialog has a spec
// without a preview, yet previews some commands (Grid Repeat Options) when asked to.
@@ -204,6 +204,27 @@ fn brush_key_color_eyedropper_updates_the_open_dialog() {
assert_eq!(app.session.tool_id(), back);
}
/// #8024: the first Escape ends the Key Color pick and returns to the tool that armed it, leaving
/// Brush Options open with its Key Color; a new press then cancels the dialog.
#[test]
fn escape_ends_the_key_color_pick_and_leaves_brush_options_open() {
let (mut app, ctx) = (app(), ctx());
app.select_tool("paintbrush");
app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap();
set(&mut app, json!({"colorization": "hueShift"}));
let before = app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned());
app.select_tool("eyedropper");
app.session.set_tool_option("brushKeyColor", &json!(true));
app.session.set_tool_option("stop", &json!("paintbrush"));
frame(&ctx, &mut app, vec![], "");
escape(&ctx, &mut app);
assert!(app.ui.dialog.is_some(), "Brush Options stays open");
assert_eq!(app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()), before, "the Key Color stays");
assert_eq!(app.session.tool_id(), "paintbrush");
escape(&ctx, &mut app);
assert!(app.ui.dialog.is_none(), "a new press cancels Brush Options");
}
#[test]
fn art_options_set_width_scale_direction_flips_and_colorization() {
let mut app = app();
+62 -1
View File
@@ -398,6 +398,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
})
.or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)})))
.or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d)));
let corner_radius = if d.kind == "roundedRectangle" { Some(rounded_radius(app, d)?) } else { None };
let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0));
let (bx, by) = box_origin(d);
let (id, params) = match d.kind.as_str() {
@@ -462,7 +463,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
}
_ => (
"shape.rectangle",
json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "radius": d.f64("radius", 0.0)}),
json!({
"x": bx,
"y": by,
"width": d.f64("width", 100.0),
"height": d.f64("height", 100.0),
"radius": corner_radius.unwrap_or_else(|| d.f64("radius", 0.0)),
}),
),
};
// On the active plane while the perspective grid shows, sized in plane units from the click;
@@ -484,9 +491,21 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if let Some(options) = options {
app.run("tool.setOption", json!({"tool": d.kind, "values": options}))?;
}
// The radius of the rounded rectangle drawn is General › Corner Radius from then on.
if let Some(r) = corner_radius.filter(|r| *r != app.session.prefs.corner_radius) {
app.run("prefs.set", json!({"key": "cornerRadius", "value": r}))?;
}
Ok(result)
}
/// The Rounded Rectangle dialog's radius in points, checked as General › Corner Radius checks it
/// (an error leaves the dialog open and draws nothing). Without the field, the preference.
fn rounded_radius(app: &VectorcraftApp, d: &Dialog) -> Result<f64, String> {
let r = if d.fields.contains_key("radius") { d.f64("radius", f64::NAN) } else { app.session.prefs.corner_radius };
vectorcraft_engine::cmd::prefscmds::validate("cornerRadius", &json!(r))?;
Ok(r)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -524,6 +543,48 @@ mod tests {
assert_eq!(box_origin(&fields(true)), (80.0, 40.0));
}
/// The Rounded Rectangle click dialog opens on General › Corner Radius, and OK makes the radius
/// typed (in any unit) that preference: the next dialog and the tool's next drag use it.
#[test]
fn rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.run("tool.select", json!({"tool": "roundedRectangle"})).unwrap();
app.run("prefs.set", json!({"key": "cornerRadius", "value": 20})).unwrap();
super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0}));
let d = app.ui.dialog.as_mut().expect("Rounded Rectangle dialog");
assert_eq!((d.kind.as_str(), d.f64("radius", 0.0)), ("roundedRectangle", 20.0));
d.fields.insert("radius".into(), json!("0.5 in"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let n = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].clone();
assert_eq!(crate::panels::corner_radius(&app, &n), Some(36.0));
assert_eq!(app.session.prefs.corner_radius, 36.0);
assert_eq!(app.session.tool_options_of("roundedRectangle")["cornerRadius"], json!(36.0));
super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0}));
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0);
}
/// A radius General › Corner Radius would refuse leaves the dialog open, draws nothing and
/// keeps the preference.
#[test]
fn rounded_rectangle_click_dialog_refuses_a_radius_out_of_range() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let before = app.session.prefs.corner_radius;
for bad in [json!(-1), json!(1297), json!("19 in"), json!("wide")] {
super::super::open_tool_dialog(&mut app, "roundedRectangle", json!({"x": 40.0, "y": 60.0}));
app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), bad.clone());
assert!(super::super::confirm(&mut app).is_err(), "{bad}");
assert!(app.ui.dialog.is_some(), "{bad}");
assert!(app.session.doc().unwrap().doc.layers[0].children().unwrap().is_empty(), "{bad}");
assert_eq!(app.session.prefs.corner_radius, before, "{bad}");
app.ui.dialog = None;
}
}
/// Turn the link on or off as its button or `ui.dialog.set` does, then apply it as the form
/// does on its next frame; what [`link_changed`] returned.
fn turn(d: &mut Dialog, on: bool) -> Option<bool> {
+5 -1
View File
@@ -18,7 +18,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
kind,
json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}),
),
"roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})),
// The radius starts at General › Corner Radius, which OK sets to the radius typed.
"roundedRectangle" => {
let radius = format!("{} pt", app.session.prefs.corner_radius);
Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": radius}))
}
"polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})),
"star" => {
Dialog::new(kind, json!({"x": x, "y": y, "radius1": "50 pt", "radius2": "25 pt", "points": app.session.tool_options_of(kind)["points"]}))
+51 -4
View File
@@ -629,8 +629,56 @@ fn drop_targets_follow_the_buttons_edges() {
assert_eq!(drop_target(&[], pos2(0.0, 0.0), 1), (None, Place::Before));
}
/// The add-ons' tools are in neither toolbar as they ship: the drawer lists them under their
/// add-on's heading, and they can be added from there.
/// The Trim at Crossings Tool is in the Scissors tool's flyout in both toolbars, after the Knife,
/// once in the All Tools drawer and in Keyboard Shortcuts' list, with no shortcut; Reset Toolbar
/// keeps it there.
#[test]
fn trim_at_crossings_is_in_the_scissors_flyout() {
let mut app = app();
let trim = vectorcraft_tools::addons::trim::ID;
for advanced in [false, true] {
if advanced {
app.run("window.toolbarAdvanced", json!({})).unwrap();
}
let s = slots(&app);
let slot = slot_of(&app, "scissors").map(|i| s[i].clone()).expect("a Scissors slot");
let knife = slot.iter().position(|id| *id == "knife").expect("the Knife beside the Scissors");
assert_eq!(slot.get(knife + 1), Some(&trim), "advanced: {advanced}");
assert_eq!(s.iter().filter(|ids| ids.contains(&trim)).count(), 1, "advanced: {advanced}");
}
assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == trim).count(), 1, "listed once in the drawer");
assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == trim).count(), 1, "listed once for Keyboard Shortcuts");
assert_eq!(vectorcraft_tools::tool_info(trim).map(|t| (t.label, t.shortcut)), Some(("Trim at Crossings Tool", None)));
app.run("tool.select", json!({"tool": trim})).unwrap();
assert_eq!(app.session.tool_id(), trim);
let shown = slot_of(&app, trim).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i]));
assert_eq!(shown, Some(trim), "the slot's button shows the tool once chosen");
app.run("toolbar.removeTool", json!({"tool": trim})).unwrap();
assert!(slot_of(&app, trim).is_none(), "it can be taken out");
app.run("toolbar.reset", json!({})).unwrap();
let after_reset = slot_of(&app, "scissors").map(|i| slots(&app)[i].contains(&trim));
assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back");
}
/// A toolbar edited and saved before the Trim at Crossings Tool joined the Scissors group keeps
/// its saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it.
#[test]
fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() {
let mut app = app();
let trim = vectorcraft_tools::addons::trim::ID;
let saved = ToolbarCategory { name: Some("Draw".into()), slots: vec![["eraser", "scissors", "knife"].iter().map(|id| id.to_string()).collect()] };
app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None };
app.ui = std::mem::take(&mut app.ui).sanitized();
assert_eq!(slots(&app), [["eraser", "scissors", "knife"]]);
assert!(slot_of(&app, trim).is_none());
app.run("toolbar.reset", json!({})).unwrap();
let slot = slot_of(&app, "scissors").map(|i| slots(&app)[i].clone());
assert!(slot.is_some_and(|s| s.contains(&trim)), "Reset Toolbar adds it");
}
/// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the
/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can
/// be added from there.
#[test]
fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let mut app = app();
@@ -649,7 +697,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
"cornerTool",
"slideAnchor",
"sharedEdge",
"trimAtCrossings",
"smartPen",
enclosing,
contour,
@@ -666,7 +713,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let listed = |id: &str| {
sections().iter().find(|(_, tools)| tools.iter().any(|t| t.id == id)).map(|(h, tools)| (*h, tools.iter().map(|t| t.id).collect::<Vec<_>>()))
};
assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..8].to_vec())));
assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec())));
assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"])));
assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing])));
assert_eq!(listed(contour), Some(("Contour", vec![contour])));
+153 -5
View File
@@ -261,7 +261,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
}
/// Forget the replacement search: the next open starts with an empty one.
fn clear_search(ctx: &egui::Context) {
pub(crate) fn clear_search(ctx: &egui::Context) {
let (source_key, query_id) = (egui::Id::unique("ff-search-source"), egui::Id::unique("ff-search"));
ctx.data_mut(|m| {
m.remove::<String>(source_key);
@@ -286,6 +286,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let mut close = false;
let mut find_in_folder = false;
let mut act: Option<&str> = None;
// Escape over an open dropdown list closes only the list, which closes itself while it is drawn.
let popup_open = egui::Popup::is_any_open(ctx);
// The replacement-font search, kept in egui memory: cleared when the dialog closes, and when
// the source changes.
let source_key = egui::Id::unique("ff-search-source");
@@ -421,16 +423,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
Err(e) => app.ui.status = e,
}
}
if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
if close || (!popup_open && crate::shortcuts::pressed_anew(ctx, egui::Key::Escape)) {
app.ui.dialog = None;
// The next open starts with an empty search.
clear_search(ctx);
} else if app.ui.dialog.is_some() {
app.ui.dialog = Some(d);
}
// Missing Fonts takes the dialog's place, searching the folder picked.
if find_in_folder && let Err(e) = app.run("ui.findFontsInFolder", json!({})) {
app.ui.status = e;
// Missing Fonts takes the dialog's place, searching the folder picked; the next Find Font
// starts with an empty search.
if find_in_folder {
match app.run("ui.findFontsInFolder", json!({})) {
Ok(_) => clear_search(ctx),
Err(e) => app.ui.status = e,
}
}
}
@@ -1012,6 +1018,148 @@ mod tests {
assert_eq!(ctx.data(|m| m.get_temp::<String>(source_id)), None, "the source it was typed under is gone");
}
/// A context with the app's fonts and theme that the app knows as its own, for [`app_frame`].
fn app_ctx(app: &mut VectorcraftApp) -> egui::Context {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx, Default::default());
app.ui_ctx = Some(ctx.clone());
ctx
}
/// One 1200 × 900 frame with `events` through the app's key handling and then the dialogs, as
/// the app runs them; the center of the text `label` if the frame shows it.
fn app_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, label: &str) -> Option<egui::Pos2> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0));
let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
crate::shortcuts::handle(app, ui.ctx());
crate::dialogs::show(app, ui.ctx());
});
out.textures_delta.clear();
out.shapes.iter().find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(egui::Rect::from_min_size(t.pos, t.galley.size()).center()),
_ => None,
})
}
/// Clicks the text `label` through [`app_frame`].
fn app_click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) {
app_frame(ctx, app, vec![], label);
let at = app_frame(ctx, app, vec![], label).unwrap_or_else(|| panic!("no {label:?} shown"));
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
app_frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)], label);
app_frame(ctx, app, vec![button(false)], label);
app_frame(ctx, app, vec![], label);
}
/// An Escape key event: pressed, or let go.
fn escape_key(pressed: bool, repeat: bool) -> egui::Event {
egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Default::default() }
}
/// Presses and lets go of Escape through [`app_frame`].
fn app_escape(ctx: &egui::Context, app: &mut VectorcraftApp) {
app_frame(ctx, app, vec![escape_key(true, false)], "");
app_frame(ctx, app, vec![escape_key(false, false)], "");
}
/// Types `query` into the replacement search under the dialog's source, as the search field
/// keeps it.
fn seed_search(ctx: &egui::Context, app: &VectorcraftApp, query: &str) {
let source = app.ui.dialog.as_ref().expect("Find Font is open").str("replaceFrom");
ctx.data_mut(|m| {
m.insert_temp(egui::Id::unique("ff-search-source"), source);
m.insert_temp(egui::Id::unique("ff-search"), query.to_string());
});
}
/// The replacement search and the source it was typed under, as egui memory keeps them.
fn search_state(ctx: &egui::Context) -> (Option<String>, Option<String>) {
ctx.data(|m| (m.get_temp::<String>(egui::Id::unique("ff-search")), m.get_temp::<String>(egui::Id::unique("ff-search-source"))))
}
/// Escape with Replace With Font From's or Find In's list open closes only the list: Find Font
/// stays open with its source and its search, holding Escape down leaves it open, and the next
/// press closes it and forgets the search.
#[test]
fn escape_over_an_open_dropdown_closes_only_the_dropdown() {
for current in ["System", "Document"] {
let mut app = two_font_document();
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
app_click(&ctx, &mut app, current);
assert!(egui::Popup::is_any_open(&ctx), "{current}: the list is open");
app_frame(&ctx, &mut app, vec![escape_key(true, false)], "");
for _ in 0..3 {
app_frame(&ctx, &mut app, vec![escape_key(true, true)], "");
}
app_frame(&ctx, &mut app, vec![escape_key(false, false)], "");
assert!(!egui::Popup::is_any_open(&ctx), "{current}: Escape closes the list");
let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{current}: Find Font stays open"));
assert_eq!((d.kind.as_str(), d.str("replaceFrom"), d.str("findIn")), ("findFont", "system".into(), "document".into()), "{current}");
assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "{current}: the search is kept");
app_escape(&ctx, &mut app);
assert!(app.ui.dialog.is_none(), "{current}: the next Escape closes Find Font");
assert_eq!(search_state(&ctx), (None, None), "{current}: closing forgets the search");
}
}
/// Escape and Done, through the app's key handling, each close Find Font and forget the
/// replacement search and its source.
#[test]
fn escape_and_done_through_the_app_clear_the_replacement_search() {
for how in ["Escape", "Done"] {
let mut app = two_font_document();
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
if how == "Escape" {
app_escape(&ctx, &mut app);
} else {
app_click(&ctx, &mut app, "Done");
}
assert!(app.ui.dialog.is_none(), "{how} closes Find Font");
assert_eq!(search_state(&ctx), (None, None), "{how} forgets the search");
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
assert_eq!(search_state(&ctx), (Some(String::new()), Some("system".into())), "{how}: the next open starts with an empty search");
}
}
/// Find in Folder… that opens Missing Fonts forgets Find Font's search; with no folder picked,
/// Find Font stays open with its search.
#[test]
fn find_in_folder_forgets_the_search_once_missing_fonts_opens() {
let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder-search")).unwrap();
for picks in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
app.session.search_threads = Some(1);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
let picked = picks.then(|| dir.to_string_lossy().into_owned());
app.services.pick_folder = Some(Box::new(move || picked.clone()));
let ctx = app_ctx(&mut app);
open(&mut app);
app_frame(&ctx, &mut app, vec![], "");
seed_search(&ctx, &app, "inter");
app_click(&ctx, &mut app, "Find in Folder…");
let kind = app.ui.dialog.as_ref().map(|d| d.kind.clone());
if picks {
assert_eq!(kind.as_deref(), Some(crate::dialogs::missing_fonts::KIND), "Missing Fonts takes Find Font's place");
assert_eq!(search_state(&ctx), (None, None), "the search is forgotten");
crate::dialogs::cancel(&mut app);
} else {
assert_eq!(kind.as_deref(), Some("findFont"), "with no folder picked, Find Font stays open");
assert_eq!(search_state(&ctx), (Some("inter".into()), Some("system".into())), "and keeps its search");
}
}
}
/// The wheel over the rows scrolls them, and leaves the document's font list where it was: two
/// lists, two scrollbars.
#[test]
+7 -7
View File
@@ -354,7 +354,7 @@ font-technology Variable Променливи
Built-in presets are read-only: New… starts an editable copy. Вградените предварителни настройки са само за четене: „Ново…“ създава редактируемо копие.
Built-in presets don't change: New makes a copy you can edit. Вградените предварителни настройки не се променят: „Ново“ създава копие за редактиране.
Built-in presets don't change: New… starts an editable copy. Вградените предварителни настройки не се променят: „Ново…“ създава редактируемо копие.
Bulge… Издуване…
Bulge… Изпъкване…
Bullet Булет
Bullets Булети
Bullets and Numbering Булети и номериране
@@ -1485,7 +1485,7 @@ font-technology Variable Променливи
Guides & Grid Водачи и мрежа
H Spacing: Хоризонтално разстояние:
H: Х:
Hair Space Тънък интервал
Hair Space Най-тънък интервал
Hand Tool Инструмент „Ръка“
Hand-Drawn Ръчно рисувани
Painted and Sketched Рисувани и скицирани
@@ -2994,7 +2994,7 @@ digits Malayalam Малаялам
Opening it left out what VectorCraft can't read yet ({what}), so replacing it loses that for good. Save under another name to keep it. Отварянето му пропусна това, което VectorCraft все още не може да прочете ({what}), така че замяната му го губи завинаги. Запазете под друго име, за да го запазите.
“{name}” already exists. Replace it? „{name}“ вече съществува. Да бъде ли заменен?
The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. Името в панела за запазване беше „{typed}“, а VectorCraft добави разширението на типа файл. Замяната на файла презаписва съдържанието му.
Revolve… Завъртане…
Revolve… Завъртане около ос…
RGB Color RGB цвят
Right Вдясно
Right Grid: Дясна мрежа:
@@ -3831,7 +3831,7 @@ digits Malayalam Малаялам
Reverse Traps Обратни застъпвания
Precision Точност
Remove Redundant Points Премахване на излишните точки
Trim Изрязване
Trim Подрязване
Trim mark weight: Дебелина на маркировките за изрязване:
Trim marks Маркировки за изрязване
Trim View Изглед на изрязване
@@ -5168,7 +5168,7 @@ effect Soft Меко
On Both Sides От двете страни
Short Кратко
Full Width Пълна ширина
Distort Изкривяване
Distort Деформиране
Diffuse Glow… Дифузно светещ…
Glass… Стъкло…
Ocean Ripple… Океански вълнички…
@@ -5770,8 +5770,8 @@ lighting Light Светлина
x Height Височина на x
▾ Default Actions ▾ Действия по подразбиране
⚠ {chord} was already used by {names} — it has been removed there. Внимание: Комбинацията {chord} вече се използва от {names} — премахната е там.
@id file.close file.close
@id pathfinder.add pathfinder.add
@id file.close Затваряне
@id pathfinder.add Обединяване
@msg give corners of the path: anchors between two straight sides дай ъглите на пътя: опорни точки между две прави страни
@msg this kind of brush has no options dialog yet този вид четка засега няма диалогов прозорец с настройки
@plural {n} PR|{n} PRs {n} PR|{n} PR-а
Can't render this file because it is too large.
+1 -1
View File
@@ -384,7 +384,7 @@
Insert Whitespace Character Umetni znak razmaka
Em Space Široki razmak (em)
En Space Polu-široki razmak (en)
Hair Space Tanki razmak
Hair Space Najtanji razmak
Sixth Space Šestina razmaka
Thin Space Tanki razmak
Nonbreaking Space Neprelomivi razmak
Can't render this file because it contains an unexpected character in line 2 and column 73.
+20 -1
View File
@@ -5036,7 +5036,7 @@ digits Malayalam Malaiàlam
Triangle Triangle
Triangle (open) Triangle (obert)
Triangle to Bar Triangle a barra
Trim Retalla
Trim Poda
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Retalla la geometria coberta en expandir l’aparença. La previsualització en directe manté tota la superfície. Les pintures transparents i les superfícies que superen els límits de visibilitat conserven totes les cares.
Trim mark weight: Gruix de les marques de retall:
Trim marks Marques de retall
@@ -6441,6 +6441,25 @@ liquify-list-end {0}, {1} {0} i {1}
@msg a 3D effect on a group's fill or stroke draws nothing un efecte 3D al farciment o al traç d’un grup no dibuixa res
@msg a 3D effect on a group's fill or stroke draws nothing to export un efecte 3D al farciment o al traç d’un grup no dibuixa res per exportar
@msg The 3D object is too complex to export L’objecte 3D és massa complex per exportar-lo
@msg give one <filter> element indica un element <filter>
@msg the <filter> element needs an id, the filter's name l’element <filter> necessita un id, el nom del filtre
@msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG té com a màxim {MAX_NAME} caràcters
@msg <{_1}> isn't an element of an SVG filter <{_1}> no és un element d’un filtre SVG
@msg an SVG filter has no event attributes such as {_1} un filtre SVG no té atributs d’esdeveniment com ara {_1}
@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs les imatges d’un filtre SVG són URL data: en PNG, JPEG, GIF o WebP
@msg the SVG filter isn't valid XML: {e} el filtre SVG no és un XML vàlid: {e}
@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves de feTurbulence és com a màxim {MAX_OCTAVES}
@msg {what} is at most {max} {what} és com a màxim {max}
@msg feConvolveMatrix's order order de feConvolveMatrix
@msg feMorphology's radius radius de feMorphology
@msg a blur's stdDeviation stdDeviation d’un desenfocament
@msg the SVG filter has no primitives el filtre SVG no té primitives
@msg an SVG filter has at most {MAX_PRIMITIVES} primitives un filtre SVG té com a màxim {MAX_PRIMITIVES} primitives
@msg the SVG filter is too large once its attributes are written out el filtre SVG és massa gran un cop escrits els seus atributs
@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all les imatges d’un filtre SVG tenen com a màxim {MAX_IMAGE_PIXELS} píxels en total
@msg the SVG filter can't be drawn: check its primitives and their inputs no es pot dibuixar el filtre SVG: comprova’n les primitives i les seves entrades
@msg an SVG filter's elements nest at most {MAX_DEPTH} deep els elements d’un filtre SVG s’imbriquen com a màxim {MAX_DEPTH} nivells
@msg an SVG filter is at most {_1} KB un filtre SVG ocupa com a màxim {_1} KB
@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objecte no té cap efecte 3D (Extrudeix i bisella, Revoluciona, Infla o Gira)
@msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` ha de ser un objecte que només contingui `mode`, amb el valor shaded o wireframe
@msg its 3D effect builds no solid el seu efecte 3D no construeix cap sòlid
Can't render this file because it contains an unexpected character in line 2 and column 73.

Some files were not shown because too many files have changed in this diff Show More