Merge main into feat/proof-setup-customize

This commit is contained in:
dotCooCoo committed 2026-11-18 01:42:37 -08:00
commit 98e38b4bdd
298 files changed
+16482 -1221

No files matched your search

+1
View File
@@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | |
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
+1
View File
@@ -141,6 +141,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="7.5"/><circle cx="4.5" cy="12" r="1.6" fill="currentColor"/><circle cx="19.5" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="4.5" r="1.6" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 386 B

+98 -6
View File
@@ -9,7 +9,6 @@
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
use vectorcraft_color::Paint;
use vectorcraft_doc::{Node, StrokeLayer};
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
@@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option<BezPath> {
Some(bp)
}
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec<Node> {
/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and
/// barrel rotation turn that spread in the path's local frame. Original path corners are included
/// in the samples so a turn is not rounded away by the pose sampling interval.
fn posed_bristle_track(
t: &Track,
d: f64,
trim0: f64,
trim1: f64,
size: f64,
stroke: &StrokeLayer,
varies: bool,
) -> Option<(BezPath, Vec<(f64, f64)>)> {
let l = t.len();
let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l));
if s1 - s0 < 1e-6 {
return None;
}
let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 };
let mut positions: Vec<f64> = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect();
positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1));
positions.sort_by(f64::total_cmp);
positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let mut path = BezPath::new();
// Distance along the posed strand -> fraction along the original, untrimmed path.
let mut source = Vec::with_capacity(positions.len());
let mut previous: Option<Point> = None;
let mut distance = 0.0;
for (i, s) in positions.into_iter().enumerate() {
let pen = PenAt::of(stroke, s / l);
let pressure = pen.control(Variation::Pressure).unwrap_or(0.5);
let tilt = pen.control(Variation::Tilt).unwrap_or(0.5);
let bearing = pen.control(Variation::Bearing).unwrap_or(0.5);
let rotation = pen.control(Variation::Rotation).unwrap_or(0.5);
let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt);
let angle = std::f64::consts::TAU * (bearing + rotation - 1.0);
let p = t.map(s + spread * angle.sin(), spread * angle.cos());
if i == 0 {
path.move_to(p)
} else {
path.line_to(p)
}
if let Some(previous) = previous {
distance += previous.distance(p);
}
source.push((distance, s / l));
previous = Some(p);
}
Some((path, source))
}
fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 {
let next = source.partition_point(|(d, _)| *d < distance);
if next == 0 {
return source.first().map_or(0.0, |(_, f)| *f);
}
if next >= source.len() {
return source.last().map_or(1.0, |(_, f)| *f);
}
let (d0, f0) = source[next - 1];
let (d1, f1) = source[next];
if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) }
}
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
let mut rng = Rng::new(seed_of(bp, name));
let size = b.size.max(0.1) * weight;
let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize;
@@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0;
let ragged = b.length.clamp(25.0, 300.0) / 100.0;
let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32;
let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some();
let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6));
let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points));
let pose_varies = pressure_varies
|| stroke.tilt.as_ref().is_some_and(|p| varies(&p.points))
|| stroke.bearing.as_ref().is_some_and(|p| varies(&p.points))
|| stroke.rotation.as_ref().is_some_and(|p| varies(&p.points));
let mut out = vec![];
for t in tracks(bp, tolerance(size)) {
let l = t.len();
@@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let edge = 1.0 - lane.abs();
let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8;
let (t0, t1) = (trim(&mut rng), trim(&mut rng));
let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue };
let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3));
let sp = if posed {
posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies)
} else {
offset_track(&t, off, t0, t1).map(|path| (path, Vec::new()))
};
let Some((sp, source)) = sp else { continue };
let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2);
let nib = Nib::new(0.0, 1.0, w);
let subs: Vec<SubPath> = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect();
let subs: Vec<SubPath> = tracks(&sp, tolerance(w))
.iter()
.flat_map(|tt| {
if posed {
sweep(
tt,
&|f| {
let original_fraction = source_fraction(&source, f * tt.len());
let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5);
Nib::new(0.0, 1.0, w * (0.5 + pressure))
},
pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)),
)
} else {
let nib = Nib::new(0.0, 1.0, w);
sweep(tt, &|_| nib, None)
}
})
.collect();
if subs.is_empty() {
continue;
}
let mut n = filled(PathData::new(subs), paint);
let mut n = filled(PathData::new(subs), &stroke.paint);
n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0);
out.push(n);
}
+9 -1
View File
@@ -1084,7 +1084,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
let mut out = match &brush.kind {
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
@@ -1245,6 +1245,14 @@ pub fn has_brush(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
}
/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes
/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so
/// the profile does not change what such a stroke draws. A stroke without a brush, or one that
/// names a brush `lib` lacks, draws a plain stroke, which follows the profile.
pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool {
stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name))
}
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
+80
View File
@@ -827,6 +827,86 @@ fn bristle_makes_translucent_strands() {
assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}");
}
#[test]
fn bristle_pen_pressure_changes_its_footprint() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let render = |pressure| {
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) };
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
};
let light = render(0.0);
let heavy = render(1.0);
assert_eq!(light.len(), heavy.len());
assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8);
}
#[test]
fn bristle_pen_pressure_is_sampled_along_the_stroke() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s);
let mut points = Vec::new();
for n in &out {
all_points(n, &mut points);
}
let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
assert!(late > early * 1.4, "spread along stroke: {early} -> {late}");
}
#[test]
fn trimmed_bristle_strands_read_pressure_where_they_begin() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) };
let render = |points| {
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) };
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s)
};
let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]);
let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]);
assert_eq!(ramp.len(), neutral.len());
let start = |n: &Node| {
let anchors = &n.path_data().unwrap().subpaths[0].anchors;
let first = anchors[0].p;
let opposite = anchors[anchors.len() - 16].p;
(first.x, (first.y - opposite.y).abs())
};
let mut checked = false;
for (ramp, neutral) in ramp.iter().zip(&neutral) {
let (x, width) = start(ramp);
if x < 12.0 {
continue;
}
let (_, neutral_width) = start(neutral);
let expected = 0.5 + x / 80.0;
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
checked = true;
}
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
}
#[test]
fn bristle_pen_orientation_changes_its_footprint() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let render = |tilt, bearing, rotation| {
let flat = |x| vec![(0.0, x), (1.0, x)];
let s = StrokeLayer {
tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }),
bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }),
rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }),
..stroke(1.0)
};
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
};
let neutral = bounds(&render(0.5, 0.0, 0.0)).height();
let flat = bounds(&render(1.0, 0.0, 0.0)).height();
let upright = bounds(&render(0.0, 0.0, 0.0)).height();
let bearing = bounds(&render(0.5, 90.0, 0.0)).height();
let rotation = bounds(&render(0.5, 0.0, 90.0)).height();
assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}");
assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}");
assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}");
}
#[test]
fn tints_colorization_uses_stroke_colour() {
let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
+33 -6
View File
@@ -7,6 +7,8 @@
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
//! effects once for all of them.
//!
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
@@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6;
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
/// layers, guides and hidden objects are left out.
pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default())
}
/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as
/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied
/// once for all the drawings.
pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result<Vec<DxfOutput>, String> {
export_drawings_with(doc, opts, drawings, bake_for_drawings)
}
/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when
/// nothing changes.
fn bake_for_drawings(doc: &Document) -> Option<Document> {
// Symbols' art is placed without clipping, as the scene places it.
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
vectorcraft_effects::bake_document_placing_symbols(doc, false, layers)
}
/// [`export_drawings`] with `bake` applying the live effects.
fn export_drawings_with(
doc: &Document,
opts: &DxfOptions,
drawings: &[(Rect, bool)],
bake: impl Fn(&Document) -> Option<Document>,
) -> Result<Vec<DxfOutput>, String> {
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
}
let r = opts.region;
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
return Err("the export region is not finite".into());
}
// Symbols' art is placed without clipping, as the scene places it.
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
if drawings.is_empty() {
return Ok(vec![]);
}
let baked = bake(doc);
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect())
}
#[cfg(test)]
+198
View File
@@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() {
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
}
}
/// One drawing written by applying the live effects for it alone and walking the result, as each
/// drawing of a multi-drawing export was written before [`export_drawings`].
fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput {
let baked = crate::bake_for_drawings(doc);
crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run()
}
/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes.
type Written = (Vec<u8>, Vec<(String, Vec<u8>)>, Vec<String>, Vec<String>);
/// Every field of a written drawing, for comparing two.
fn written(out: &DxfOutput) -> Written {
let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect();
(out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone())
}
/// A Transform effect that moves its object `x` pt right.
fn moved_by(mut n: Node, x: f64) -> Node {
n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true });
n
}
/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect
/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image.
fn drawings_doc() -> Document {
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
2,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[0u8, 128, 255, 255].repeat(4),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
faint.opacity = 0.5;
faint.blend = vectorcraft_color::BlendMode::Multiply;
let im = ImageObject {
key: "raster-1".into(),
width: 2,
height: 2,
xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
});
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d
}
#[test]
fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() {
let d = drawings_doc();
assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply");
// The left and right halves cropped, the whole page uncropped, and a region off the page.
let drawings = [
(Rect::new(0.0, 0.0, 100.0, 100.0), true),
(Rect::new(100.0, 0.0, 200.0, 100.0), true),
(Rect::new(0.0, 0.0, 200.0, 100.0), false),
(Rect::new(300.0, 0.0, 400.0, 100.0), true),
];
// With every option, and with images and hatches left out (which adds setting notes).
let all_in = opts(&d);
for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] {
let bakes = std::cell::Cell::new(0);
let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| {
bakes.set(bakes.get() + 1);
crate::bake_for_drawings(doc)
})
.unwrap();
assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing");
assert_eq!(outs.len(), drawings.len());
for ((region, crop), out) in drawings.iter().zip(&outs) {
let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() });
assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}");
let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap();
assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}");
}
let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect();
assert_eq!(public, outs.iter().map(written).collect::<Vec<_>>());
// The halves hold different art, the left half a line with losses, and the region off the
// page nothing.
assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty());
assert_ne!(outs[0].bytes, outs[1].bytes);
assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty());
if o.include_images {
assert_eq!(outs[2].images.len(), 1);
} else {
assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty());
}
}
}
#[test]
fn drawings_are_checked_before_the_live_effects_are_applied() {
let d = drawings_doc();
let o = opts(&d);
let bakes = std::cell::Cell::new(0);
let count = |doc: &Document| {
bakes.set(bakes.get() + 1);
crate::bake_for_drawings(doc)
};
let page = (d.artboards[0].rect, false);
let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false);
assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite");
let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err();
assert!(e.starts_with("scale must be a number"), "{e}");
assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty());
assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none");
}
/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`.
fn thread_cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by
/// drawing with the effects applied for each (as before [`export_drawings`]) and with
/// [`export_drawings`], alternating, seven times each, and check that both write the same
/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of
/// wall-clock time.
/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn dxf_artboards_bake_perf() {
const BOARDS: usize = 8;
let mut d = Document::new(200.0 * BOARDS as f64, 200.0);
let layer = d.layers[0].id;
let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
let mut art = vec![];
for i in 0..50 {
let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0);
art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5)));
}
let mut cell = Node::group(d.alloc_id(), art);
cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"})));
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) });
for b in 0..BOARDS {
let x0 = 200.0 * b as f64;
for i in 0..250 {
let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0);
let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5);
let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i});
n.appearance.effects.push(effect("distort.roughen", params));
d.insert(Some(layer), usize::MAX, n).unwrap();
}
for i in 0..20 {
let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0));
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf });
d.insert(Some(layer), usize::MAX, instance).unwrap();
}
}
let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() };
let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect();
let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::<Vec<_>>();
let after = || export_drawings(&d, &o, &drawings).unwrap();
let time = |f: &dyn Fn() -> Vec<DxfOutput>| {
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
let outs = f();
let wall = wall.elapsed().as_secs_f64() * 1000.0;
let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6);
(outs, cpu, wall)
};
let (mut runs_before, mut runs_after) = (vec![], vec![]);
for _ in 0..7 {
let (a, cpu_a, wall_a) = time(&before);
let (b, cpu_b, wall_b) = time(&after);
assert_eq!(a.len(), BOARDS);
assert_eq!(a.iter().map(written).collect::<Vec<_>>(), b.iter().map(written).collect::<Vec<_>>(), "both write the same drawings");
runs_before.push((cpu_a, wall_a));
runs_after.push((cpu_b, wall_b));
}
let median = |runs: &[(Option<f64>, f64)], cpu: bool| {
let mut v: Vec<f64> = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect();
v.sort_by(f64::total_cmp);
v.get(v.len() / 2).copied()
};
for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] {
println!(
"{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}",
median(runs, true),
median(runs, false)
);
}
}
+14 -3
View File
@@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 {
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper
/// as the media white point; the colorimetric Lab → CMYK table without black-point
/// compensation, the perceptual and saturation ones with it); a profile the user
/// loaded is the file it came from. Cached.
pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new());
@@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
let bytes: Arc<[u8]> = if name == GRAY {
icc::encode(&icc::gray_profile(name))?
} else if BUILTIN_CMYK.contains(&name) {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
// The perceptual and saturation tables map the shadows with black-point compensation; the
// colorimetric table is the inverse of the CMYK → Lab table, without it.
let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?;
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?;
let paper = match &cms.cmyk {
CmykSpace::Generic(g) => g.paper_xyz(),
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
};
let to_lab = |c| cms.cmyk_to_lab(c);
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
+5
View File
@@ -133,6 +133,11 @@ pub struct GenericCmyk {
}
impl GenericCmyk {
/// Absolute XYZ (D50) of the paper.
pub fn paper_xyz(&self) -> [f32; 3] {
self.paper_xyz
}
pub fn new(params: GenericCmykParams) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
+26 -12
View File
@@ -446,11 +446,20 @@ const B2A_GRID: usize = 17;
const GAMUT_GRID: usize = 9;
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped,
/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the
/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag.
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
/// TIFF that embedded one, #2707).
pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
/// the ICC-absolute colorimetric intent reproduces.
pub(super) fn cmyk_profile(
name: &str,
paper: [f32; 3],
to_lab: impl Fn([f32; 4]) -> lab::Lab,
mapped: impl Fn(lab::Lab) -> [f32; 4],
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
) -> ColorProfile {
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
@@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
let l = to_lab(cmyk);
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
}
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
for i in 0..B2A_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
}
let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| {
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
for i in 0..B2A_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
}
b2a
};
let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric));
// Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut.
let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3));
for i in 0..GAMUT_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID));
let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0);
gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX });
gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX });
}
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| {
@@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
})
};
let a2b = table(4, 3, A2B_GRID, a2b);
let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped);
let b2a = table(3, 4, B2A_GRID, b2a);
let gamut = table(3, 1, GAMUT_GRID, gamut);
let mut p = ColorProfile::default();
@@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
p.pcs = DataColorSpace::Lab;
p.rendering_intent = RenderingIntent::RelativeColorimetric;
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
p.media_white_point = Some(p.white_point);
p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])));
p.lut_a_to_b_perceptual = Some(a2b.clone());
p.lut_a_to_b_saturation = Some(a2b.clone());
p.lut_a_to_b_colorimetric = Some(a2b);
p.lut_b_to_a_perceptual = Some(b2a.clone());
p.lut_b_to_a_saturation = Some(b2a.clone());
p.lut_b_to_a_perceptual = Some(b2a_mapped.clone());
p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
+59 -7
View File
@@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() {
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
}
// And back: an in-gamut colour separates to about the same inks.
let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
// And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is
// the colorimetric inverse of the CMYK → Lab table, with no black-point compensation.
for inks in [
[0.1, 0.6, 0.8, 0.0],
[0.5, 0.1, 0.3, 0.1],
[0.3, 0.3, 0.3, 0.2],
[0.05, 0.05, 0.4, 0.0],
[0.4, 0.3, 0.3, 0.6],
[0.6, 0.5, 0.5, 0.4],
[0.2, 0.2, 0.2, 0.8],
[0.0, 0.0, 0.0, 0.5],
] {
let srgb = cms.cmyk_to_srgb(inks, false);
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again));
assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})");
}
// The perceptual table keeps black-point compensation: source black separates to inks
// that print the press's black point, as the CMS separates it with compensation.
let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap();
let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap();
let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]);
let de = delta_e2000(printed(&want), printed(&got));
assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want));
}
}
#[test]
fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() {
// CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto
// RGB, which holds every color these profiles print, so no display gamut clips the inks.
// Inks that print outside sRGB come back to inks that print the same color.
for name in BUILTIN_CMYK {
let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap();
for inks in
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]]
{
let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap();
let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]]));
// Within the ΔE of 3 that the gamut tag counts as reproduced.
assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})");
}
}
}
#[test]
fn cmyk_profiles_carry_their_paper_as_the_media_white() {
let generic = generic::swop_like();
let p = parse(&icc_bytes(GENERIC_CMYK).unwrap());
let white = p.media_white_point.unwrap();
let paper = lab::lab_to_xyz(generic.paper);
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}");
}
}
@@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
let rich = [0.75, 0.68, 0.67, 0.9];
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the
// profile's Lab → CMYK table carries no compensation of its own).
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}");
// The screen shows what an sRGB conversion writes, compensated alike.
let srgb = |bpc| {
let c = icc_cmyk(bpc);
+5
View File
@@ -143,6 +143,11 @@ impl Appearance {
pub fn fill_paint(&self) -> Paint {
self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None)
}
/// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this
/// includes lower fills in the stack; zero opacity still counts for selecting its geometry.
pub fn has_visible_fill(&self) -> bool {
self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none()))
}
pub fn stroke_paint(&self) -> Paint {
self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None)
}
+156 -79
View File
@@ -82,8 +82,9 @@ impl Default for HitOptions {
}
}
/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a
/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the
/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
/// patterns in the document it is given.
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
@@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) {
let _ = IMAGE_PAINT.set(f);
}
/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
/// nothing is registered.
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
/// The shapes that [`ImagePaint`] gives for one object.
type Painted = Vec<(BezPath, FillRule, AppearanceItem)>;
/// The shapes that the image or symbol instance `n` paints with its geometry effects
/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of
/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured
/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`,
/// its swatches or color groups, or the
/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or
/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]).
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc<Painted> {
let Some(f) = IMAGE_PAINT.get() else { return Rc::default() };
let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty());
let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else {
return Rc::new(f(doc, n));
};
let inputs = live_inputs();
if let Some(painted) = kept(&PAINTED, d, n, inputs) {
return painted;
}
#[cfg(test)]
PAINT_EVALUATED.with(|c| c.set(c.get() + 1));
let painted = Rc::new(f(doc, n));
if !symbols_hold_images(d) {
let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len()));
keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT);
}
painted
}
/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can
/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep
/// the shapes of an instance then.
fn symbols_hold_images(doc: &Document) -> bool {
let mut image = false;
doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_))));
image
}
/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every
/// hover measures each instance whose fill or stroke has a geometry effect.
const PAINT_KEPT: usize = 64;
thread_local! {
/// The shapes [`image_paint`] keeps, the latest first.
static PAINTED: RefCell<Vec<Evaluated<Painted>>> = const { RefCell::new(Vec::new()) };
}
#[cfg(test)]
thread_local! {
/// How many symbol instances [`image_paint`] measured on this thread.
static PAINT_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
@@ -127,21 +176,72 @@ fn live_inputs() -> u64 {
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
/// and its [`art_size`].
struct EvaluatedLive {
/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its
/// document's symbols (by name and art), patterns, swatches and color groups, the document data
/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they
/// were, the result and its size.
struct Evaluated<T> {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
unknown: crate::Shared<serde_json::Map<String, serde_json::Value>>,
inputs: u64,
art: Rc<Vec<Node>>,
art: Rc<T>,
size: usize,
}
impl EvaluatedLive {
/// The evaluations kept on this thread in one store, the latest first.
type Store<T> = std::thread::LocalKey<RefCell<Vec<Evaluated<T>>>>;
/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front.
fn kept<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64) -> Option<Rc<T>> {
store.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
let e = kept.remove(i);
let art = e.art.clone();
kept.insert(0, e);
Some(art)
})
}
/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front
/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most.
/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns
/// hold a placed document ([`holds_placed`]).
fn keep<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64, art: &Rc<T>, size: usize, most: usize) {
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
return;
}
let e = Evaluated::new(doc, n, inputs, art, size);
store.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(most);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
}
impl<T> Evaluated<T> {
/// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now.
fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc<T>, size: usize) -> Self {
Self {
node: n.clone(),
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
unknown: doc.unknown.clone(),
inputs,
art: art.clone(),
size,
}
}
/// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now?
fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool {
self.inputs == inputs
@@ -151,6 +251,7 @@ impl EvaluatedLive {
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
&& self.unknown == doc.unknown
}
}
@@ -158,8 +259,9 @@ impl EvaluatedLive {
/// envelope's stroke band hits it again and again, and an envelope can hold a blend.
const LIVE_KEPT: usize = 4;
/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than
/// this is not kept.
/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the
/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not
/// kept.
const LIVE_KEPT_SIZE: usize = 250_000;
/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths.
@@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool {
thread_local! {
/// The evaluations [`live_art`] keeps, the latest first.
static EVALUATED: RefCell<Vec<EvaluatedLive>> = const { RefCell::new(Vec::new()) };
static EVALUATED: RefCell<Vec<Evaluated<Vec<Node>>>> = const { RefCell::new(Vec::new()) };
}
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice
/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the
/// [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
let e = kept.remove(i);
let art = e.art.clone();
kept.insert(0, e);
Some(art)
});
if let Some(art) = kept {
if let Some(art) = kept(&EVALUATED, doc, n, inputs) {
return art;
}
#[cfg(test)]
LIVE_EVALUATED.with(|c| c.set(c.get() + 1));
let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n)));
let size = art_size(&art);
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive {
node: n.clone(),
symbols,
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT);
art
}
@@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) {
/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and
/// the box round everything that art can paint.
struct EvaluatedDrawn {
of: EvaluatedLive,
of: Evaluated<Vec<Node>>,
reach: Option<Rect>,
}
@@ -310,7 +383,8 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated
/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a
/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the
/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and
/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the
/// [`LiveInputs`] have changed since, and
/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new
/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is
/// kept alone.
@@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>
let art = Rc::new(art.into_iter().collect::<Vec<_>>());
let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n)));
if !holds_placed(doc, n) {
let of = EvaluatedLive {
node: n.clone(),
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
let of = Evaluated::new(doc, n, inputs, &art, size);
DRAWN.with_borrow_mut(|(kept, total)| {
if let Some(old) = kept.remove(&n.id) {
*total = total.saturating_sub(old.of.size);
@@ -607,9 +672,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
// Each round leaves out the objects found so far (and everything inside them).
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
// Each round leaves out the objects found so far (and everything inside them). `found` holds
// the same ids as `tops`, which keeps their order.
let mut found: HashSet<NodeId> = tops.iter().copied().collect();
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) {
if !found.insert(top) {
break;
}
tops.push(top);
@@ -1290,8 +1357,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a
/// miter or square cap, so the caller falls back to the full stroke check there.
/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the
/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit,
/// while Miter and Square can extend beyond it.
fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> {
if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 {
return None;
@@ -1349,6 +1417,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let has_fill = n.appearance.has_visible_fill();
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
@@ -1361,7 +1430,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
let mut strokes = n.appearance.painted_strokes();
if !opt.outline
&& n.appearance.fill().is_none_or(|f| f.paint.is_none())
&& !has_fill
&& let Some(s) = strokes.next()
&& strokes.next().is_none()
&& s.align == StrokeAlign::Center
@@ -1376,10 +1445,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
path,
p,
s.width / 2.0 + opt.tol,
if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 },
if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 },
)
{
if hit {
if hit && !near_decoration {
return Some(HitKind::Stroke);
}
if !near_decoration {
@@ -1390,8 +1459,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
}
let filled = !n.appearance.fill_paint().is_none();
if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) {
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
return Some(HitKind::Fill);
}
None
@@ -1412,7 +1480,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
return Some(HitKind::Outline);
}
(!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -1436,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if opt.outline {
return None;
}
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
hit_painted(n, p, opt, symbols)
}
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A symbol instance is hit within its bounds, and outside them where its art paints
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
// ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape
// the art it draws ([`image_paint`]) except in outline mode. In the art of another instance
// walked outside that instance's bounds, it is hit only where its own art paints
// ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => {
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
instance_art_hit(n, p, opt, symbols)
instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) })
}
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
@@ -1478,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
}
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
/// stroke along its shape, a fill inside it except with Selection by Path Only.
fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
}
/// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path
/// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and
/// type on a path's path, drawn through `n`'s perspective projection if it has one.
+279 -2
View File
@@ -1262,6 +1262,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
assert_eq!(evaluated(), before + 2);
}
/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
/// (320, 20); nothing for anything else.
fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
}
_ => vec![],
}
}
/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once,
/// and again only after the instance or the symbols change.
#[test]
fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() {
set_image_paint(painted_far_away);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
let inst = d.alloc_id();
let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY });
n.appearance = Appearance::default_art().into();
let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
n.appearance.items[0].effects_mut().push(offset);
d.insert(Some(l), 0, n).unwrap();
let measured = || PAINT_EVALUATED.with(std::cell::Cell::get);
let before = measured();
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf);
assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints");
assert_eq!(at(&d, 500.0), None);
assert_eq!(at(&d, 10.0), Some(inst));
assert_eq!(measured(), before + 1);
d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12});
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 2, "a changed instance is measured again");
let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3, "changed symbols measure it again");
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3);
// An image's pixels change when its file is read again, so with one in a symbol's art every
// click measures the instance.
let xf = vectorcraft_geom::Affine::IDENTITY;
let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None };
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(at(&d, 310.0), Some(inst));
assert!(measured() >= before + 5, "each click measures it: {}", measured() - before);
}
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
/// ([`LiveInputs`]) are as they were.
#[test]
@@ -1274,19 +1328,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
fn kept_evaluation(d: &Document, n: &Node) -> Evaluated<Vec<Node>> {
Evaluated {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
unknown: d.unknown.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place
/// the symbol's art, and the document keeps them apart from the symbols.
#[test]
fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]}));
assert!(!e.is_of(&d, &n, 7));
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
@@ -1823,6 +1890,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
}
}
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
break;
}
tops.push(top);
}
tops
}
/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod
/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the
/// document, the group and its members, topmost first.
fn isolated_stack(count: u32) -> (Document, NodeId, Vec<NodeId>) {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
let below = square(&mut d, 0.0);
d.insert(Some(l), usize::MAX, below).unwrap();
let members: Vec<Node> = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect();
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
let g = d.alloc_id();
d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
for x in [0.0, 100.0] {
let above = square(&mut d, x);
d.insert(Some(l), usize::MAX, above).unwrap();
}
ids.reverse();
(d, g, ids)
}
/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above
/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where
/// only the art around the group lies.
#[test]
fn select_behind_in_isolation_lists_a_large_stack_once() {
let (d, g, ids) = isolated_stack(40);
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
assert_eq!(at(47.5, Some(g)), ids);
assert_eq!(at(47.5, Some(g)).iter().collect::<HashSet<_>>().len(), 40, "no object twice");
assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below");
// At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within
// the tolerance): `ids[k]` is member 39 - k.
let left: Vec<NodeId> = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect();
assert_eq!(left.len(), 20);
assert_eq!(at(17.5, Some(g)), left);
assert!(at(125.0, Some(g)).is_empty(), "only the square around the group");
assert_eq!(at(125.0, None).len(), 1);
let isolated = HitOptions { scope: Some(g), ..HitOptions::default() };
let p = Point::new(47.5, 25.0);
assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first");
let (d, g, clip, art) = masked_square(false);
let isolated = HitOptions { scope: Some(g), ..SELECTING };
for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] {
let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]);
assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}");
}
assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides");
assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline");
}
/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden
/// and locked objects), each object in turn isolated, and each list started with some of the
/// objects already found: the set lookup returns what the ordered-list lookup returns, field for
/// field.
#[test]
fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() {
let mut seed = 0x2545_f491_u32;
let mut next = move |n: u32| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed % n
};
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
for _ in 0..2 + next(5) {
let id = d.alloc_id();
let rect = |next: &mut dyn FnMut(u32) -> u32| {
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)))
};
let mut n = match next(if depth < 3 { 9 } else { 4 }) {
4 | 5 => Node::group(id, Vec::new()),
6 => {
let mut g = Node::group(id, Vec::new());
g.set_clips(true);
g
}
7 => {
let content =
(0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect();
Node::new(
id,
NodeKind::Envelope {
content,
kind: Box::new(crate::live::EnvelopeKind::Warp {
style: "arc".to_string(),
bend: 0.0,
h: 0.0,
v: 0.0,
horizontal: true,
version: 0,
}),
fidelity: 100.0,
editing: next(2) == 0,
options: Default::default(),
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
},
)
}
_ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }),
};
n.visible = next(8) != 0;
n.locked = next(8) == 0;
let group = matches!(n.kind, NodeKind::Group { .. });
d.insert(Some(parent), usize::MAX, n).unwrap();
if group {
fill(d, id, depth + 1, next);
}
}
}
let mut compared = 0;
for round in 0..60 {
let mut d = Document::new(120.0, 120.0);
let layer = d.layers[0].id;
fill(&mut d, layer, 0, &mut next);
let mut scopes = vec![None];
d.walk(|n| {
if n.id != layer {
scopes.push(Some(n.id));
}
});
for _ in 0..6 {
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
for &scope in &scopes {
let opt = HitOptions { scope, ..opt };
let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]);
let context = format!("round {round}, {p:?}, {opt:?}");
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}");
if scope.is_some() {
assert_eq!(objects_at(&d, p, opt, scope), want, "{context}");
}
for found in 1..want.len() {
let start = want[..found].to_vec();
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found");
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found");
}
compared += usize::from(!want.is_empty());
}
}
}
assert!(compared > 500, "only {compared} non-empty lists compared");
}
/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup
/// against the ordered-list lookup, alternating the two in one process:
/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn select_behind_isolation_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())
}
type Lookup = fn(&Document, Point, HitOptions, Option<NodeId>, Vec<NodeId>) -> Vec<NodeId>;
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
let p = Point::new(47.5, 25.0);
for count in [200, 1_000] {
let (d, g, ids) = isolated_stack(count);
let opt = HitOptions { scope: Some(g), ..HitOptions::default() };
assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids);
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids);
// The time per call of `f`: batches of calls double until one takes at least 100 ms.
let per_call = |f: Lookup| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![]));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 20 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(objects_at_repeated_after_by_list));
new.push(per_call(objects_at_repeated_after));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, n) = (old[3], new[3]);
println!(
"{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs",
o.0 / 1e6,
o.1,
n.0 / 1e6,
n.1
);
}
}
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
/// one instance and 100 pt lower by an instance in a group.
+218 -10
View File
@@ -117,6 +117,29 @@ impl Document {
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
self.resolve_inline_art_since(None, layout).changed
}
/// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved,
/// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the
/// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the
/// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then
/// still measures the same, the type in the layer trees that are the same nodes as `last`'s
/// already has these bounds: only the other layer trees are checked, in the same order, and
/// the document and the ids returned are those of the full pass. Otherwise, or without `last`,
/// the full pass runs.
pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass {
if let Some((last, kept)) = last
&& self.same_inline_inputs(last, kept)
{
let measured = Measured(RefCell::new(kept.0.clone()));
let mut changed = vec![];
let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed);
for (i, layer) in layers {
self.layers[i] = layer;
}
return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true };
}
let mut out = vec![];
let mut unused = vec![];
let graph = InlineGraph::of(self);
@@ -147,10 +170,44 @@ impl Document {
}
}
}
out
InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false }
}
/// Whether the type in this document's layer trees that are the same nodes as `last`'s already
/// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]).
fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool {
self.symbols.len() == last.symbols.len()
&& self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& self.graph_designs.len() == last.graph_designs.len()
&& self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& self.patterns.len() == last.patterns.len()
&& self
.patterns
.iter()
.zip(&last.patterns)
.all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y)))
&& crate::Shared::ptr_eq(&self.unknown, &last.unknown)
&& kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b)
}
}
/// What a pass of [`Document::resolve_inline_art_since`] did.
#[derive(Debug)]
pub struct InlinePass {
/// The ids of the texts in the layers that changed, in the order the full pass finds them.
pub changed: Vec<NodeId>,
/// The bounds the pass gave the inline graphics of each symbol name, for the next pass.
pub measured: InlineMeasured,
/// Whether only the layer trees that differ from the last resolved document's were checked.
pub partial: bool,
}
/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each
/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the
/// pass before it measured, so the names of all the type in the document stay listed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InlineMeasured(HashMap<String, Option<Rect>>);
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
@@ -185,6 +242,22 @@ fn resolve_tree(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
resolve_since(None, n, bounds, layout, changed)
}
/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was
/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same
/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node
/// of the tree is visited.
fn resolve_since(
old: Option<&Node>,
n: &mut Arc<Node>,
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
#[cfg(test)]
tests::VISITS.with(|v| v.set(v.get() + 1));
let mut copied = false;
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
let node = Arc::make_mut(n);
@@ -196,17 +269,17 @@ fn resolve_tree(
}
copied = true;
}
let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art);
let mask = n.extras().mask.as_deref().and_then(|m| {
let mut art = m.art.clone();
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
});
let mut kids = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut c = c.clone();
if resolve_tree(&mut c, bounds, layout, changed) {
kids.push((i, c));
if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) {
return None;
}
}
let mut art = m.art.clone();
let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o);
resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art)
});
let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice));
let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed);
if mask.is_none() && kids.is_empty() {
return copied;
}
@@ -224,6 +297,35 @@ fn resolve_tree(
true
}
/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list
/// before an edit) that has its id, found at the same position or else by id, and skips those that
/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new
/// node of each tree that changed.
fn resolve_kids(
old: Option<&[Arc<Node>]>,
kids: &[Arc<Node>],
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> Vec<(usize, Arc<Node>)> {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
let mut out = vec![];
for (i, c) in kids.iter().enumerate() {
let o = old.and_then(|old| match old.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
});
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
continue;
}
let mut c = c.clone();
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
out.push((i, c));
}
}
out
}
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
/// A symbol is first asked for after its own type is resolved (the pass goes in
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
@@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles {
mod tests {
use super::*;
thread_local! {
/// How many nodes [`resolve_since`] has visited on this thread.
pub(super) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes visited since the last call.
fn visits() -> usize {
VISITS.with(|v| v.replace(0))
}
/// A copy of `d` resolved by the full pass, and the ids that pass returns.
fn fully_resolved(d: &Document) -> (Document, Vec<NodeId>) {
let mut full = d.clone();
let ids = full.resolve_inline_art_with(&mut |_| {});
(full, ids)
}
/// The children of the layer at `i`, for an edit.
fn layer_kids(d: &mut Document, i: usize) -> &mut Vec<Arc<Node>> {
match Arc::make_mut(&mut d.layers[i]).children_mut() {
Some(kids) => kids,
None => panic!("layer {i} is a group"),
}
}
/// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing
/// `S` in the opacity mask of the second.
fn many_groups() -> Document {
let mut d = Document::new(500.0, 500.0);
let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
symbol(&mut d, "S", vec![square]);
for _ in 0..50 {
let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect();
let group = Node::group(d.alloc_id(), kids);
d.layers.push(Arc::new(group));
}
let t = showing(&mut d, "S");
layer_kids(&mut d, 0).push(t);
let masked = showing(&mut d, "S");
Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true)));
d
}
#[test]
fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() {
let mut d = many_groups();
let first = d.resolve_inline_art_since(None, &mut |_| {});
assert!(!first.partial);
assert_eq!(first.changed.len(), 2);
let last = d.clone();
visits();
let _ = fully_resolved(&d);
let full_visits = visits();
// The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the
// second group's opacity mask new type: its 20 squares stay the same nodes.
let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0));
layer_kids(&mut d, 30)[5] = moved;
let added = showing(&mut d, "S");
layer_kids(&mut d, 40).push(added.clone());
let mask_type = showing(&mut d, "S");
if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
m.art = mask_type.clone();
}
let (want, ids) = fully_resolved(&d);
assert_eq!(ids, [mask_type.id, added.id]);
visits();
let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {});
let partial_visits = visits();
assert!(pass.partial);
assert_eq!(pass.changed, ids);
assert_eq!(d, want);
// The three changed groups, the mask's new type, the moved square and the added type.
assert_eq!(partial_visits, 6);
assert!(full_visits > 1000, "{full_visits}");
assert_eq!(pass.measured, first.measured);
}
#[test]
fn changed_symbols_or_symbol_sizes_take_the_full_pass() {
let mut d = many_groups();
let mut pass = d.resolve_inline_art_since(None, &mut |_| {});
// A natural size for S, its art unchanged.
let last = d.clone();
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] }));
let (want, ids) = fully_resolved(&d);
assert_eq!(ids.len(), 2);
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
assert!(!pass.partial);
assert_eq!((&d, &pass.changed), (&want, &ids));
// New art for S.
let last = d.clone();
let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0));
d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger]));
let (want, ids) = fully_resolved(&d);
assert_eq!(ids.len(), 2);
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
assert!(!pass.partial);
assert_eq!((&d, &pass.changed), (&want, &ids));
// A measurement that no longer holds, with the same symbols and foreign data.
let last = d.clone();
let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))]));
pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {});
assert!(!pass.partial);
assert!(pass.changed.is_empty());
}
/// The position of each node in `order`.
fn positions(order: &[usize]) -> Vec<usize> {
let mut at = vec![0; order.len()];
+1 -1
View File
@@ -31,7 +31,7 @@ mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_pixel_aligned;
mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{
+2 -1
View File
@@ -66,7 +66,8 @@ pub use expand::{
use mesh::grid_eval;
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
pub use warp::{
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net,
warp_point, warp_version,
};
#[cfg(test)]
+63 -1
View File
@@ -508,6 +508,17 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
}
/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position.
pub fn map_handles_within(
path: &PathData,
max_piece: f64,
max: usize,
f: impl Fn(Point) -> Point,
handle: impl Fn(Point, Point) -> Point,
) -> PathData {
map_pieces_within(path, max_piece, max, &f, handle)
}
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
@@ -553,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po
let c = seg_cubic(sp, i);
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
for j in 0..k {
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
// Evaluating an unchanged curve can overflow even when its control points are finite.
let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) };
if let Some(last) = res.last_mut() {
last.h_out = handle(sub.p0, sub.p1);
}
@@ -613,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> {
}
out
}
#[cfg(test)]
mod handle_tests {
use super::*;
#[test]
fn an_unsplit_curve_keeps_its_finite_control_points() {
let start = Point::new(1e308, 0.0);
let end = Point::new(1.03e308, 0.0);
let path = PathData::new(vec![SubPath::new(
vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)],
false,
)]);
assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path);
}
#[test]
fn rounded_samples_preserve_a_smooth_interior_join() {
let center = Point::new(1e16, 0.0);
let path = PathData::new(vec![SubPath::new(
vec![
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)),
Anchor::with_handles(
center,
center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0),
center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0),
),
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)),
],
false,
)]);
let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1));
let join = &mapped.subpaths[0].anchors[1];
let incoming = join.p - join.h_in;
let outgoing = join.h_out - join.p;
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
assert!(incoming.dot(outgoing) > 0.0);
}
#[test]
fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() {
for x in [1e16, 1e16 + 2.0, -1e16] {
for offset in [-6.0, -2.0, 2.0, 6.0] {
let p = Point::new(x, 0.0);
let h = Point::new(x + offset, 0.0);
assert_eq!(mapped_handle(&|point| point, p, h), h);
}
}
}
}
+42
View File
@@ -179,6 +179,48 @@ impl LiveShape {
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
}
}
/// A line's length in the document, from its first end to its second. None for other shapes.
pub fn line_length(&self) -> Option<f64> {
let LiveShape::Line { a, b } = self else { return None };
Some((*b - *a).hypot())
}
/// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the
/// direction from its first end to its second (the Rotate field's sense). 0 for a line whose
/// ends meet. None for other shapes.
pub fn line_angle(&self) -> Option<f64> {
let LiveShape::Line { a, b } = self else { return None };
if a == b {
return Some(0.0);
}
// No −0° or 360° from rounding: a line drawn left to right reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
}
/// Make a line `len` long (0 or more), keeping its first end in place and its direction, or
/// pointing it to the right when its ends meet.
pub fn set_line_length(&mut self, len: f64) {
let LiveShape::Line { a, b } = self else { return };
if !len.is_finite() || len < 0.0 {
return;
}
let now = (*b - *a).hypot();
*b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) };
}
/// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line
/// whose ends meet stays as it is.
pub fn set_line_angle(&mut self, angle: f64) {
let LiveShape::Line { a, b } = self else { return };
let half = (*b - *a).hypot() / 2.0;
if !angle.is_finite() || half <= 0.0 {
return;
}
let mid = a.midpoint(*b);
let t = angle.to_radians();
// The page's y axis points down, so a counterclockwise angle goes up the page.
let (dx, dy) = (half * t.cos(), -half * t.sin());
*a = Point::new(mid.x - dx, mid.y - dy);
*b = Point::new(mid.x + dx, mid.y + dy);
}
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
pub fn make_sides_equal(&mut self) {
+21 -13
View File
@@ -216,8 +216,10 @@ impl Node {
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
/// takes in where its spine can put its keys and steps.
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the
/// shapes their art paints with the geometry effects of their own fill or stroke
/// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys
/// and steps.
pub fn reach_bounds(&self) -> Option<Rect> {
self.reach(None)
}
@@ -254,14 +256,8 @@ impl Node {
.map(|b| b.inflate(o, o))
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
// the farthest it can reach from its shape.
NodeKind::Image(_) => {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
// The frame and each shape the image's own fills and strokes paint.
NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols),
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -272,13 +268,15 @@ impl Node {
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
// The live geometry effects of the clipping paths in the art can draw it past its box.
// The live geometry effects of the clipping paths in the art can draw it past its box,
// and the box takes in each shape the art paints with the geometry effects of the
// instance's own fill or stroke.
NodeKind::SymbolInstance { symbol, xf } => {
let Some((s, art, region)) = symbols.and_then(|s| {
let a = s.art(symbol)?;
Some((s, a, a.reshaped?))
}) else {
return self.visual(symbols);
return self.with_own_paint(self.visual(symbols), symbols);
};
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
let placed = if moves_only(*xf) && map.is_none() {
@@ -294,12 +292,22 @@ impl Node {
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
};
let o = self.appearance.outset();
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols)
}
_ => self.visual(symbols),
}
}
/// `start` grown by each shape the node's own fills and strokes paint
/// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its
/// shape.
fn with_own_paint(&self, start: Option<Rect>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
+73 -1
View File
@@ -187,8 +187,9 @@ impl Document {
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
/// visited once even when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
@@ -844,6 +845,77 @@ mod tests {
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
/// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
let Some(node) = d.node(id) else { continue };
if let Some((new, count)) = map_node(node, &mut g)
&& let Some(slot) = d.node_mut(id)
{
*slot = new;
n += count;
}
}
n
}
#[test]
fn mapping_within_ids_matches_a_search_of_the_ids() {
// Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
// rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
let mut d = Document::new(100.0, 100.0);
let first = d.layers[0].id;
let second = d.alloc_id();
d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
let rect = |d: &mut Document, i: u8| {
let id = d.alloc_id();
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
(id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
};
let (r1, n1) = rect(&mut d, 1);
let (r2, n2) = rect(&mut d, 2);
let (r3, n3) = rect(&mut d, 3);
let (r4, n4) = rect(&mut d, 4);
let (r5, n5) = rect(&mut d, 5);
let (inner, outer) = (d.alloc_id(), d.alloc_id());
let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
d.insert(Some(first), usize::MAX, outer_node).unwrap();
d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
let missing = NodeId(u64::MAX);
let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
// Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
let mut lists: Vec<Vec<NodeId>> = vec![vec![]];
let mut shorter: Vec<Vec<NodeId>> = vec![vec![]];
for _ in 0..3 {
shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
lists.extend(shorter.iter().cloned());
}
assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
for ids in &lists {
// A callback that changes every paint it visits, so a paint visited twice counts twice.
let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
let mut d = d.clone();
let mut visits = vec![];
let n = map(&mut d, ids, &mut |c, s, t| {
visits.push((*c, s.clone(), *t));
*s = Some(format!("{}", visits.len()));
*t *= 0.5;
true
});
(n, visits, d.layers)
};
let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
assert_eq!(by_set, by_search, "{ids:?}");
}
}
/// 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| {
+5 -9
View File
@@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
use crate::distort::{transform_move, transform_offsets};
use crate::group::{has_own_paint, paints};
use crate::reshape::{
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text,
paint_type_clip, reshape_leaves,
};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
@@ -502,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
{
return None;
}
let (bp, rule) = crate::clip_outline(first)?;
let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
(*r, *clipping) = (rule, true);
}
clip.name = first.name.clone();
clip.visible = first.visible;
let clip = clip_region_path(first)?;
let paint = first.clip_paint();
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
// then given ids of their own.
@@ -532,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
return Some(m);
};
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
knockout_inside(&mut m, &mut inner);
match &mut m.kind {
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
*children = vec![Arc::new(inner), stroke];
+5 -2
View File
@@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let mut shadowed = type_node(55);
shadowed.opacity = 0.5;
shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({})));
// Type that clips a group is outlined as the plain outlines it clips by.
// Type that clips a group is outlined as a plain path of the region it clips by.
let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true });
g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]);
@@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let b = o.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap();
assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}");
assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}");
// The region is copied with the type.
let b = clipped.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
}
#[test]
+7 -1
View File
@@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}",
json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}),
),
g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})),
g(
"distort.twist",
"Twist…",
DT,
"{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.",
json!({"angle": 10.0}),
),
g(
"distort.zigZag",
"Zig Zag…",
+34 -4
View File
@@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat
use vectorcraft_pathops::addons::pathtools::insert_at;
use crate::util::{
catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
};
fn diag(b: Rect) -> f64 {
@@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
/// the rotation's directional derivative, including each side of the outer circle.
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
if ang == 0.0 {
@@ -336,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
}
let c = b.center();
let r = diag(b) / 2.0;
let half = Vec2::new(b.width() * 0.5, b.height() * 0.5);
let boundary = move |p: Point, length: f64| {
if length == r {
return true;
}
if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r {
return false;
}
// A bounds-relative distance identifies boundary points affected by center rounding.
(Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r
};
let f = move |q: Point| {
let d = q - c;
let t = (1.0 - d.hypot() / r).max(0.0);
let length = d.hypot();
let t = (1.0 - length / r).max(0.0);
// y runs down, so a positive turn is clockwise on the page.
let a = ang * t;
if a == 0.0 {
return q;
}
let (s, co) = a.sin_cos();
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
};
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
map_smooth_within(path, piece, max, f)
map_handles_within(path, piece, max, f, |p, h| {
let v = h - p;
if !v.hypot().is_finite() {
return f(p);
}
let d = p - c;
let length = d.hypot();
let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 };
// The clamped rotation has different inward and outward derivatives at the circle.
let inside = if boundary(p, length) { radial < 0.0 } else { length < r };
let gradient = if inside { -ang / r * radial } else { 0.0 };
let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient };
let a = ang * (1.0 - length / r).max(0.0);
let (s, co) = a.sin_cos();
f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co)
})
}
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
+34 -8
View File
@@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
// Every path of the outline art, at any depth, is drawn inside the object's opacity
// and blend mode. A symbol's art comes with the live objects and the instances of
// other symbols inside it given as their art, and the type inside it outlined, so the
// art has nothing left for `hook` to give.
// art has nothing left for `hook` to give. Its fills and strokes carry the geometry
// effects of the instance's active fill and stroke, as the canvas draws them.
if let Some(h) = hook
&& let Some(art) = h(n)
{
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
@@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
}
}
/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and
/// the instances of other symbols inside it given as their art
/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry
/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]).
fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
let drawn = |m: &Node| {
let mut a = hook(m)?;
crate::reshape::add_instance_row_effects(doc, m, &mut a);
Some(a)
};
crate::reshape::symbol_art_with(art, &drawn, nodes, symbol)
}
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
/// not Normal.
fn within(l: &mut Node, n: &Node) {
@@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
}
},
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
// inside it outlined, reshaped as one piece, as the renderer draws it.
// inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes
// of the art then carry the geometry effects of the instance's active fill and stroke.
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
members_as_drawn(doc, &mut art);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
@@ -703,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
}
fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
// A clip group whose clipping type's strokes paint around it is outlined as that clip
// group: the strokes outside the clip add nothing.
if let Some(inner) = crate::reshape::painted_clip_inner(n) {
return members(doc, inner, out);
}
// A clip group shows its members only inside its clipping path: its outline is that
// region, not the clipped members' own shapes, which may reach far outside it (#7289).
if n.clips() {
@@ -884,14 +906,18 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
if paint {
let shapes = member_shapes(doc, &m);
let bounds = m.geometric_bounds();
// A clip group whose clipping type paints strokes is now a group of a clip group and those
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
// that clip group. Such groups among the members are measured as their clip groups.
let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some();
let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m));
let art =
|items: &[AppearanceItem]| -> Vec<Arc<Node>> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() };
let (below, above) = m.appearance.split_contents();
let (below, above) = (art(below), art(above));
let at = usize::from(m.clips());
if let Some(ch) = m.children_mut() {
let at = usize::from(wrapped || m.clips());
let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) };
if let Some(ch) = target.and_then(Node::children_mut) {
let at = at.min(ch.len());
ch.splice(at..at, below);
ch.extend(above);
+194 -44
View File
@@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
@@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced {
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
/// the image's pixels in `doc` when the image does not hold them.
/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry
/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint
/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect
/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when
/// the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
}
let Some(art) = reshape(doc, n, None) else { return vec![] };
let mut out = vec![];
art.walk(&mut |c| {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
});
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
let mut budget = SYMBOL_ART_MAX_NODES;
instance_paint(doc, n, 1, &mut budget, &mut out);
return out;
}
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return out;
}
let Some(art) = reshape(doc, n, None) else { return out };
art.walk(&mut |c| push_painted(doc, c, &mut out));
out
}
/// The shapes that the fills and strokes of path or compound path `c` paint, each with the
/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects.
fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
}
/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of
/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it,
/// each with its own geometry effects and those of each fill and stroke applied
/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of
/// the groups and layers in the art paint and the results of their Pathfinder effects
/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the
/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn.
/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of
/// Shaper groups add nothing, and neither does an instance more than
/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured
/// so far past `budget`.
fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) {
return;
}
let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return };
let count = sym.art.count() as u64;
if count > *budget {
return;
}
*budget -= count;
let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return };
painted_in(doc, &art, depth, budget, out);
}
/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep.
fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) {
// One path for each fill and stroke, its effects applied.
Some(pieces) => painted_in(doc, &pieces, depth, budget, out),
None => push_painted(doc, n, out),
},
NodeKind::Path { .. } => {}
NodeKind::Image(_) => out.extend(image_paint(doc, n)),
NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out),
_ if n.clips() => {}
_ => {
// A Pathfinder effect paints its result, not the members it combines.
let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten();
let g = evaluated.as_ref().unwrap_or(n);
if g.clips() {
return;
}
// A Shaper group's first member holds its original shapes, which are not drawn. The
// group's own fills and strokes can be painted before it, so it is found by its id.
let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten();
for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) {
painted_in(doc, c, depth, budget, out);
}
}
}
}
/// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one
/// path per run, and all of them as one.
pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::BezPath) {
@@ -954,6 +1023,74 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option<Node> {
Some(Node { visible: t.visible, ..o })
}
/// Clipping path `clip` of a clip group as a clipping path of the region it clips to
/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry
/// effects of its fills and strokes reshape what they paint and leave that region as it is.
/// `None` when it has nothing to clip by.
pub(crate) fn clip_region_path(clip: &Node) -> Option<Node> {
let (bp, rule) = crate::clip_outline(clip)?;
let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind {
(*r, *clipping) = (rule, true);
}
p.name = clip.name.clone();
p.visible = clip.visible;
Some(p)
}
/// Knockout Group for clip group `m` turned into a group around `inner`, a clip group of its
/// members, and its clipping path's strokes: `inner` takes `m`'s setting, so the clipped art knocks
/// out as before, and `m` is set Off so the strokes paint over it, as the renderer draws them. A
/// neutral `m` stays neutral, so both take the setting of the groups around them.
pub(crate) fn knockout_inside(m: &mut Node, inner: &mut Node) {
inner.knockout = m.knockout;
if m.knockout != vectorcraft_doc::Knockout::Neutral {
m.knockout = vectorcraft_doc::Knockout::Off;
}
}
/// The clip group in `n` when `n` is a group or layer that [`paint_type_clip`] made of a clip
/// group and its clipping type's strokes: a group that does not clip whose first member is a clip
/// group with `n`'s id and whose second member has the id of that clip group's clipping path. The
/// clip group's region is what `n` stands for, as the clip group it was made from: the strokes
/// paint outside it and add nothing to its outline ([`crate::member_shapes`]) or its bounds
/// ([`clip_bounds`]).
pub(crate) fn painted_clip_inner(n: &Node) -> Option<&Node> {
if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
return None;
}
let [inner, stroke, ..] = n.children()?.as_slice() else { return None };
let clip = inner.children()?.first()?;
(inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner)
}
/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that
/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type
/// outside the clip do not widen them.
pub(crate) fn clip_bounds(n: &Node) -> Option<Rect> {
fn holds(n: &Node) -> bool {
painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c))
}
fn unwrap(n: &mut Node) {
if let Some(inner) = painted_clip_inner(n) {
let mut inner = inner.clone();
inner.visible = n.visible;
*n = inner;
}
for c in n.children_mut().into_iter().flatten() {
if holds(c) {
unwrap(Arc::make_mut(c));
}
}
}
if !holds(n) {
return n.geometric_bounds();
}
let mut probe = n.clone();
unwrap(&mut probe);
probe.geometric_bounds()
}
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
@@ -981,32 +1118,41 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
}
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
/// they are. Hidden type paints nothing.
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: a path of the region the type
/// clips to clips ([`clip_region_path`]), its fills as art ([`as_art`]) paint behind the clipped
/// art inside the clip, and its strokes as art paint over it, outside the clip. Each part is the
/// type's art with only those fills or strokes, their own geometry effects applied. With strokes,
/// `n` becomes a group (keeping its id, name, visibility and transparency) that holds a clip group
/// of the clipping path, the fills and the other members, with `n`'s id, then the strokes; a
/// clipping layer keeps its ruler guides last. [`knockout_inside`] sets the Knockout Group of both,
/// and [`painted_clip_inner`] finds that clip group. The other members stay as they are. Hidden
/// type paints nothing.
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
let Some(first) = n.children().and_then(|ch| ch.first()).filter(|_| n.clips()) else { return };
if !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
return;
}
let paint = first.clip_paint();
if paint.fill.is_none() && paint.stroke.is_none() {
return;
}
let Some(clip) = clipping_text_outline(first) else { return };
let Some(clip) = clip_region_path(first) else { return };
let art = |part: Option<Node>| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
let members: Vec<Arc<Node>> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
let stroke = art(paint.stroke);
let (fill, stroke) = (art(paint.fill), art(paint.stroke));
let id = n.id;
match (&mut n.kind, stroke) {
(NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
(NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
*children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
*clip = false;
}
_ => {}
let Some(ch) = n.children_mut() else { return };
let Some(slot) = ch.first_mut() else { return };
*slot = Arc::new(clip);
if let Some(fill) = fill {
ch.insert(1, fill);
}
let Some(stroke) = stroke else { return };
let guides = ch.split_off(Node::guide_run_start(ch));
let mut inner = Node::new(id, NodeKind::Group { children: std::mem::take(ch), clip: true });
knockout_inside(n, &mut inner);
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut n.kind {
*children = [Arc::new(inner), stroke].into_iter().chain(guides).collect();
*clip = false;
}
}
@@ -1822,7 +1968,7 @@ impl Step<'_> {
if !groups.is_empty() {
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
}
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art));
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
Ran { kept: !kept_ids.is_empty(), took, masks, short, whole }
}
@@ -3247,6 +3393,9 @@ fn group_marks(
NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false),
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
// A clip group whose clipping type's strokes paint around it is measured as that clip
// group: the strokes outside the clip do not widen it ([`clip_bounds`]).
let clip = *clip || painted_clip_inner(n).is_some();
let skip = children.len().saturating_sub(n.editing_children().len());
let (mut bounds, mut held) = (None, false);
for (i, c) in children.iter().enumerate() {
@@ -3257,7 +3406,7 @@ fn group_marks(
}
at.pop();
// Only members measured in the bounds hold the group's gradients in place.
let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) };
if counts {
bounds = vectorcraft_geom::union_opt(bounds, b);
held |= h;
@@ -3473,16 +3622,17 @@ impl WarpedImages {
/// The geometric bounds of `art` as it draws after the effects so far: each image this table
/// lists measured by the pieces the warps and moves it took would cut it into, when the art
/// has room for them ([`cut_warped_images`]).
/// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip
/// are left out ([`clip_bounds`]).
pub(crate) fn bounds(&self, art: &Node) -> Option<Rect> {
if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) {
return art.geometric_bounds();
return clip_bounds(art);
}
// The pieces the images would be cut into now: each group of pieces is shown or hidden as
// its image is, and hidden objects are left out of a layer's bounds.
let mut probe = art.clone();
restore_warped_images(&mut probe, self, true);
probe.geometric_bounds()
clip_bounds(&probe)
}
/// The geometric bounds of image `n`: when this table lists it, measured by the pieces the
+109
View File
@@ -1708,6 +1708,115 @@ fn twist_joins_its_pieces_smoothly() {
}
}
#[test]
fn twist_boundary_handles_follow_the_inward_tangent() {
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
for angle in [90.0_f64, 400.0, -720.0] {
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
let anchors = &out.subpaths[0].anchors;
let start = anchors.first().unwrap();
let end = anchors.last().unwrap();
assert_eq!(start.p, Point::new(40.0, 30.0));
assert_eq!(end.p, Point::new(60.0, 30.0));
for (actual, expected) in [
(start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())),
(end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())),
] {
assert!(actual.hypot() > 1e-9);
let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs();
assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees");
}
}
}
#[test]
fn twist_large_coordinate_joins_preserve_boundary_sides() {
use vectorcraft_geom::Anchor;
let center = 1e16;
for offset in [32.0, 64.0] {
let p = Point::new(center + offset, 0.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(p.x - 18.0, 0.0)),
Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)),
Anchor::corner(Point::new(p.x + 18.0, 0.0)),
],
false,
));
let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3);
let join = &out.subpaths[0].anchors[1];
if offset == 64.0 {
assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0));
let actual = join.h_in - join.p;
let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2);
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
assert!(error < 1e-9, "{actual:?}");
} else {
let incoming = join.p - join.h_in;
let outgoing = join.h_out - join.p;
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
assert!(incoming.dot(outgoing) > 0.0);
}
}
}
#[test]
fn twist_fractional_boundary_handles_use_each_sides_derivative() {
use vectorcraft_geom::Anchor;
for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] {
for x in [bounds.x0, bounds.x1] {
for angle in [90.0_f64, 400.0, -720.0] {
let p = Point::new(x, 30.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(x - 3.0 * step, 30.0)),
Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)),
Anchor::corner(Point::new(x + 3.0 * step, 30.0)),
],
false,
));
let out = crate::distort::twist(&line, bounds, angle, 3);
assert!(
out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()),
"x={x} angle={angle}: {:?}",
out.subpaths[0].anchors
);
let join = &out.subpaths[0].anchors[1];
assert!(join.p.distance(p) < 1e-10, "{:?}", join.p);
let a = angle.to_radians();
let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] };
for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) {
let expected = vectorcraft_geom::Vec2::new(dx, dy);
let error = actual.cross(expected).atan2(actual.dot(expected)).abs();
assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]);
}
}
}
}
let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0);
let center = bounds.center();
let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false));
let out = crate::distort::twist(&line, bounds, 90.0, 3);
assert_eq!(out.subpaths[0].anchors[1].p, center);
let bounds = Rect::new(0.0, 30.0, 2e16, 30.0);
let p = Point::new(bounds.x1 - 8.0, 30.0);
let line = PathData::single(SubPath::new(
vec![
Anchor::corner(Point::new(p.x - 12.0, p.y)),
Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)),
Anchor::corner(Point::new(p.x + 12.0, p.y)),
],
false,
));
let out = crate::distort::twist(&line, bounds, 90.0, 3);
let join = &out.subpaths[0].anchors[1];
assert!(join.p.y - p.y > 10.0, "{:?}", join.p);
assert!(join.h_out.y - join.p.y < -4.0, "{join:?}");
}
#[test]
fn twist_fixes_the_outer_circle_and_rotates_inside() {
let out = run("distort.twist", json!({"angle": 0}), &square());
+334
View File
@@ -543,3 +543,337 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() {
assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0));
}
}
fn blue() -> Paint {
Paint::solid(Color::rgb(0.0, 0.0, 1.0))
}
fn green() -> Paint {
Paint::solid(Color::rgb(0.0, 1.0, 0.0))
}
/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3
/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and
/// stroked green 2 pt wide when `stroke`.
fn painted_type(id: u64, fill: bool, stroke: bool) -> Node {
use vectorcraft_doc::text::{CharStyle, TextObject};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
static FONT: std::sync::Once = std::sync::Once::new();
FONT.call_once(|| {
vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds"));
});
let style = CharStyle {
font_family: HEIGHT_FAMILY.into(),
size: 40.0,
fill: if fill { blue() } else { Paint::None },
stroke: if stroke { green() } else { Paint::None },
stroke_width: 2.0,
..Default::default()
};
Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style))))
}
/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke?
fn paints(n: &Node, fill: bool) -> bool {
use vectorcraft_doc::AppearanceItem;
let own = n.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => fill && f.paint == blue(),
AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0,
});
own || n.children().into_iter().flatten().any(|c| paints(c, fill))
}
/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of
/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the
/// green stroke art right after the clip group (over it, outside the clip), and whether a green
/// stroke paints inside the clip group.
type Painted = (Rect, Option<Rect>, Option<Rect>, bool);
fn painted_clip(n: &Node) -> Option<Painted> {
let ch = n.children()?;
for (i, c) in ch.iter().enumerate() {
if let NodeKind::Group { children, clip: true } = &c.kind {
let region = clip_outline(children.first()?)?.0.bounding_box();
let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds());
let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds());
let inside = children.iter().skip(1).any(|m| paints(m, false));
return Some((region, fill, stroke, inside));
}
if let Some(found) = painted_clip(c) {
return Some(found);
}
}
None
}
fn near_rect(a: Rect, b: Rect) -> bool {
(a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5
}
#[test]
fn painted_clipping_type_survives_enclosing_geometry_effect() {
// Type that paints a fill, a stroke, both or neither clips a red square, in a group whose
// Transform (moving everything 10 pt down, beside other type that stays type in the export) or
// Offset Path reshapes its members: the canvas and the export keep the type's fill as art
// behind the square inside the clip and its stroke as art over the clip group, both reshaped
// with the clip.
let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box();
assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}");
let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))];
for effect in effects {
for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] {
let clipped = clip_group(2, painted_type(3, fill, stroke));
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]);
outer.appearance.effects.push(effect.clone());
let canvas = crate::evaluate_container(None, &outer).unwrap();
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer).unwrap();
let baked = bake_document(&d).unwrap();
let exported = baked.layers.iter().find_map(|l| painted_clip(l));
for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] {
let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id);
let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group"));
if effect.id == "distort.transform" {
assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}");
} else {
let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0);
assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt");
}
assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}");
assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}");
assert!(!inside, "{case}: the stroke paints outside the clip");
for art in fills.into_iter().chain(strokes) {
assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}");
}
}
}
}
}
/// The group in `n` that holds a clip group and then the green stroke art of its clipping type,
/// with that clip group.
fn stroke_wrapper(n: &Node) -> Option<(&Node, &Node)> {
let ch = n.children()?;
if let [inner, stroke, ..] = ch.as_slice()
&& matches!(inner.kind, NodeKind::Group { clip: true, .. })
&& !n.clips()
&& paints(stroke, false)
{
return Some((n, inner));
}
ch.iter().find_map(|c| stroke_wrapper(c))
}
#[test]
fn clipping_type_strokes_paint_over_a_knockout_clip_group() {
// A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its
// clipped art knocks out as the clip group says, and the type's stroke paints over it without
// knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's
// Transform around it, or by its own Offset Path.
use vectorcraft_doc::Knockout;
for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] {
for own in [false, true] {
let mut ty = painted_type(3, true, true);
if own {
ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1})));
}
let mut clipped = clip_group(2, ty);
clipped.knockout = knockout;
let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]);
if !own {
outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10})));
}
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer.clone()).unwrap();
let baked = bake_document(&d).unwrap();
let canvas = if own { None } else { crate::evaluate_container(None, &outer) };
let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l));
for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] {
if own && what == "canvas" {
continue;
}
let case = format!("{what}, own effect {own}, knockout {knockout:?}");
let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip"));
assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before");
assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art");
}
}
}
}
#[test]
fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() {
// A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that
// strokes: the group's fill still paints inside the clip, and the type's stroke over it.
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
let mut group = clip_group(2, painted_type(3, false, true));
group.appearance =
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &group).unwrap();
let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap();
assert!(strokes.is_some() && !inside, "{canvas:?}");
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow));
assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}");
assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}");
}
#[test]
fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() {
// A clip group with an unplaced linear gradient fill of its own and an Offset Path effect,
// clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient
// spans the region the clipping path clips to.
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut ty = painted_type(3, false, false);
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
let mut group = clip_group(2, ty);
group.appearance =
Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &group).unwrap();
let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") };
let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") };
let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box();
let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() {
Paint::Gradient(g) => g.geom,
_ => None,
});
let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}"));
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}");
}
#[test]
fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() {
// A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect
// (moving everything 10 pt down, or scaling it to half its width around its middle) holds a
// clip group clipped by type whose stroke has a Transform effect moving it 60 pt right,
// outside the clip. On the canvas and in the export, the clip region is the type's glyphs
// reshaped by the group's effect, and the group's fill paints that region alone, its gradient
// spanning it: the moved stroke adds nothing to the region, the fill or the box the group's
// effect scales around.
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0));
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut ty = painted_type(3, false, false);
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
let live = clip_outline(&ty).expect("the type clips").0.bounding_box();
let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0);
// Scaled to half its width around the middle of the clip, which the stroke does not move.
let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0);
let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1);
// The group's own fill art: every object outside the clip groups whose own fill is `paint`.
fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) {
let mine = n.appearance.items.iter().any(|i| match (i, paint) {
(vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)),
(vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p,
_ => false,
});
if mine {
out.push(n);
}
for c in n.children().into_iter().flatten().filter(|c| !c.clips()) {
own_fills(c, paint, out);
}
}
let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)];
for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) {
let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]);
outer.appearance =
Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into();
let canvas = crate::evaluate_container(None, &outer).unwrap();
let mut d = Document::new(400.0, 400.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, outer).unwrap();
let baked = bake_document(&d).unwrap();
let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group");
for (what, art) in [("canvas", &canvas), ("export", &*exported)] {
let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" });
let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}"));
assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}");
let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art"));
assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}");
let mut fills = vec![];
own_fills(art, &paint, &mut fills);
assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}");
let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap();
assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}");
if let Paint::Gradient(_) = paint {
for fill in fills {
let geom = match fill.appearance.fill_paint() {
Paint::Gradient(g) => g.geom,
_ => None,
};
let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}"));
let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x));
assert!(
(left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5,
"{case}: the gradient {geom:?} spans the clip {region:?}"
);
}
}
}
}
}
#[test]
fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() {
// A clip group with a placed linear gradient fill of its own, in a group with Free Distort,
// clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip:
// the gradient moves and scales from the clip's bounds, as for the same clip group whose type
// does not stroke. The moved stroke adds nothing to those bounds.
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
fn placed_geom(n: &Node) -> Option<vectorcraft_color::GradientGeom> {
if let Paint::Gradient(g) = n.appearance.fill_paint()
&& g.geom.is_some()
{
return g.geom;
}
n.children().into_iter().flatten().find_map(|c| placed_geom(c))
}
let ends = |stroke: bool| {
let mut ty = painted_type(3, false, false);
if stroke {
ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into();
for item in &mut ty.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(s) = item {
s.effects.push(fx("distort.transform", json!({"moveH": 60})));
}
}
}
let mut group = clip_group(2, ty);
group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]);
let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
outer.appearance.effects.push(fx("distort.freeDistort", corners));
let canvas = crate::evaluate_container(None, &outer).unwrap();
if stroke {
assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}");
}
placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}"))
};
let (plain, stroked) = (ends(false), ends(true));
assert!(
plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5,
"the gradient {stroked:?} follows the clip as {plain:?} does"
);
}
+1 -1
View File
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
/// segments into pieces within an anchor budget.
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces};
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
@@ -0,0 +1,154 @@
//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a
//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of
//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with
//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`,
//! the loop the command used before, copied here) and in one pass (`new`), side by side in one
//! process: first the whole command, then the selection step alone. Each case checks that both give
//! the same selection and reply before it is timed.
//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by
//! every run of `old` and of `new`.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::HashSet;
use std::hint::black_box;
use std::time::Instant;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
use vectorcraft_engine::Session;
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
fn median(ms: &[f64]) -> f64 {
let mut ms = ms.to_vec();
ms.sort_by(f64::total_cmp);
ms[ms.len() / 2]
}
/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares).
fn squares(n: usize) -> (Document, NodeId, Vec<NodeId>) {
let mut doc = Document::new(1600.0, 1200.0);
let layer = doc.layers[0].id;
let ids = (0..n)
.map(|i| {
let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)];
let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true));
let id = doc.alloc_id();
doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap();
id
})
.collect();
(doc, layer, ids)
}
/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or
/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`].
fn old_command(s: &mut Session, layer: NodeId) -> Value {
let st = s.doc().unwrap();
let ids = st.doc.node(layer).unwrap().layer_art(true);
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let rows = st.layer_rows.clone();
s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap();
let st = s.doc_mut().unwrap();
st.layer_rows = rows;
json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() })
}
fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) {
for i in ids {
if all_selected { sel.remove(*i) } else { sel.add(*i) }
}
}
fn new_command(s: &mut Session, layer: NodeId) -> Value {
s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap()
}
/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state.
fn time<S>(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec<f64>, Vec<f64>) {
let run = |s: &mut S, f: &dyn Fn(&mut S)| {
let t = Instant::now();
f(s);
t.elapsed().as_secs_f64() * 1000.0
};
let (mut olds, mut news) = (Vec::new(), Vec::new());
for _ in 0..iters() {
let mut s = prepare();
olds.push(run(&mut s, &old));
black_box(&s);
let mut s = prepare();
news.push(run(&mut s, &new));
black_box(&s);
}
(olds, news)
}
fn row(name: &str, (old, new): (Vec<f64>, Vec<f64>)) {
let (o, n) = (median(&old), median(&new));
let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::<Vec<_>>().join(" ");
println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9));
println!(" old runs: {}", list(&old));
println!(" new runs: {}", list(&new));
}
fn main() {
println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup");
for n in [2_000usize, 20_000, 50_000] {
println!("{n} objects");
let (doc, layer, ids) = squares(n);
let mut s = Session::new();
s.add_document(doc, None);
let mut all = Selection::default();
all.set(ids.iter().copied());
let mut half = Selection::default();
half.set(ids.iter().copied().step_by(2));
for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] {
let reset = |s: &mut Session| {
let st = s.doc_mut().unwrap();
st.selection = start.clone();
st.layer_rows.clear();
};
// Both ways give the same selection and reply.
reset(&mut s);
let old_reply = old_command(&mut s, layer);
let old_sel = s.doc().unwrap().selection.clone();
reset(&mut s);
let new_reply = new_command(&mut s, layer);
assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection");
assert_eq!(new_reply, old_reply, "{name}: the same reply");
let (mut olds, mut news) = (Vec::new(), Vec::new());
for _ in 0..iters() {
for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] {
reset(&mut s);
let t = Instant::now();
black_box(f(&mut s, layer));
ms.push(t.elapsed().as_secs_f64() * 1000.0);
}
}
row(&format!("command, {name}"), (olds, news));
// The selection step alone, on a copy of the starting selection.
let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true);
let selected: HashSet<NodeId> = start.objects.iter().copied().collect();
let all_selected = art.iter().all(|i| selected.contains(i));
let new_step = |sel: &mut Selection| {
if all_selected {
sel.remove_all(art.iter().copied());
} else {
sel.add_all(art.iter().copied());
}
};
let (mut a, mut b) = (start.clone(), start.clone());
old_step(&mut a, &art, all_selected);
new_step(&mut b);
assert_eq!(a, b, "{name}: the same selection step");
row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step));
}
}
}
+217
View File
@@ -0,0 +1,217 @@
//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time
//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used
//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and
//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and
//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to.
//! For each it times two ways of finding the selected objects that no other selected object holds: a
//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids
//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both
//! give the same count, visit the same paints in the same order and leave the same document as
//! `map_solid_paints_in` before it times them.
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10
//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs
//! everything, in ms; elsewhere they are wall times.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::{HashMap, HashSet};
use std::hint::black_box;
use std::sync::Arc;
use std::time::Instant;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
/// The colors the rectangles use, each with a swatch to link to.
const COLORS: usize = 50;
/// The calls in each timed run; a row gives the time of one call.
const REPS: usize = 10;
/// A way of finding the ids that no other listed id holds.
type Roots = fn(&Document, &[NodeId]) -> Vec<NodeId>;
/// A way of applying a link function to the paints of the listed ids, returning the count changed.
type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a;
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
fn median(mut ms: Vec<f64>) -> f64 {
ms.sort_by(f64::total_cmp);
ms[ms.len() / 2]
}
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
fn thread_cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
fn measure(f: impl FnOnce()) -> f64 {
match thread_cpu_ns() {
Some(start) => {
f();
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
}
None => {
let t = Instant::now();
f();
t.elapsed().as_secs_f64() * 1000.0
}
}
}
/// Color `i` of [`COLORS`]: each has its own red value.
fn color(i: usize) -> Color {
Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25)
}
/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models.
fn red_bits(c: &Color) -> u32 {
match c {
Color::Rgb { r, .. } => r.to_bits(),
_ => u32::MAX,
}
}
/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor.
fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect()
}
/// [`roots_by_search`] with each ancestor looked up in a set of the ids.
fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect()
}
/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed
/// paint put in place: the work of `map_solid_paints_in`.
fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize {
let mut n = 0;
for id in roots(d, ids) {
let Some(mut node) = d.node(id).cloned() else { continue };
let count = map_node_solid_paints(&mut node, f);
if count > 0
&& let Some(slot) = d.node_mut(id)
{
*slot = node;
n += count;
}
}
n
}
/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global
/// swatches, recording each paint visited. Returns the count and the visits.
fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option<String>)>) {
let names: HashMap<u32, String> = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect();
let mut visits = vec![];
let n = map(d, ids, &mut |c, s, _| {
visits.push((*c, s.clone()));
match names.get(&red_bits(c)) {
Some(name) if s.is_none() => {
*s = Some(name.clone());
true
}
_ => false,
}
});
(n, visits)
}
fn rect(d: &mut Document, i: usize) -> Arc<Node> {
let id = d.alloc_id();
let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0);
let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0));
let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0);
Arc::new(Node::path(id, r, a))
}
/// `n` rectangles in the first layer, all selected.
fn flat(n: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(1600.0, 1200.0);
let l = d.layers[0].id;
let mut ids = vec![];
for i in 0..n {
let node = rect(&mut d, i);
ids.push(node.id);
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap();
}
(d, ids)
}
/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with
/// `groups` the two groups above each of them too, listed first.
fn nested(groups: bool) -> (Document, Vec<NodeId>) {
let mut d = Document::new(1600.0, 1200.0);
let l = d.layers[0].id;
let (mut outer_ids, mut leaves) = (vec![], vec![]);
for g in 0..1_000 {
let rects: Vec<Arc<Node>> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect();
leaves.extend(rects.iter().map(|r| r.id));
let inner = Node::group(d.alloc_id(), rects);
let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]);
if groups {
outer_ids.extend([outer.id, inner.id]);
}
d.insert(Some(l), usize::MAX, outer).unwrap();
}
outer_ids.extend(leaves);
(d, outer_ids)
}
fn bench(name: &str, (doc, ids): (Document, Vec<NodeId>)) {
let mut shipped = doc.clone();
let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f));
for roots in [roots_by_search as Roots, roots_by_set] {
let mut d = doc.clone();
let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f));
assert_eq!(got, want, "{name}: the same count and visits");
assert_eq!(d.layers, shipped.layers, "{name}: the same document");
}
let (mut old, mut new, mut real) = (vec![], vec![], vec![]);
let timed = |map: &mut Map| {
let mut docs = vec![doc.clone(); REPS];
measure(|| {
for d in &mut docs {
black_box(link(d, black_box(&ids), &mut *map));
}
}) / REPS as f64
};
for i in 0..iters() {
let run = |roots: Roots, out: &mut Vec<f64>| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f)));
if i % 2 == 0 {
run(roots_by_search, &mut old);
run(roots_by_set, &mut new);
} else {
run(roots_by_set, &mut new);
run(roots_by_search, &mut old);
}
real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f)));
}
let (old, new, real) = (median(old), median(new), median(real));
println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new);
}
fn main() {
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
println!(
" {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}",
"document",
"ids",
"linked",
format!("search, {unit}"),
format!("set, {unit}"),
format!("shipped, {unit}"),
"speedup"
);
bench("2,000 rectangles in one layer", flat(2_000));
bench("20,000 rectangles in one layer", flat(20_000));
bench("5,000 rectangles in 1,000 groups of groups", nested(false));
bench("the same with the 2,000 groups listed first", nested(true));
}
@@ -0,0 +1,146 @@
//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set`
//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For
//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and
//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole
//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named.
//! The whole-command rows include the document copy the command makes for undo; each run is undone
//! before the next, outside the timed part.
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times
//! and gives the time of one.
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::HashSet;
use std::hint::black_box;
use std::time::Instant;
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_engine::Session;
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
fn iters() -> usize {
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
}
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
fn cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
fn ms(f: impl FnOnce()) -> f64 {
let (cpu, wall) = (cpu_ns(), Instant::now());
f();
match (cpu, cpu_ns()) {
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
_ => wall.elapsed().as_secs_f64() * 1000.0,
}
}
fn median(mut v: Vec<f64>) -> f64 {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
}
/// `n` 10 pt squares in one group, and the squares' ids in stacking order.
fn document(n: usize) -> (Document, NodeId, Vec<NodeId>) {
let mut b = DocBuilder::new(4000.0, 4000.0);
let kids: Vec<_> = (0..n)
.map(|i| {
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
})
.collect();
let leaves = kids.iter().map(|k| k.id).collect();
let group = b.group(kids, false);
(b.build(), group, leaves)
}
/// The merge that checks each leaf against the growing list.
fn listed(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
for id in leaves {
if !out.contains(&id) {
out.push(id);
}
}
out
}
/// The merge that checks each leaf against a set seeded with `out`.
fn with_set(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> {
let mut seen: HashSet<NodeId> = out.iter().copied().collect();
for id in leaves {
if seen.insert(id) {
out.push(id);
}
}
out
}
fn row(name: &str, ms: f64) {
println!(" {name:<52} {ms:>10.3} ms");
}
/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part.
fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 {
let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "weight": 3});
let runs = (0..iters())
.map(|_| {
let mut r = Value::Null;
let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap()));
assert_eq!(r["objects"], n, "{r}");
s.execute("edit.undo", &json!({})).unwrap();
t
})
.collect();
median(runs)
}
fn bench(n: usize) {
println!("{n} paths in one group");
let (doc, group, leaves) = document(n);
// Each run merges `reps` times, on copies made before the clock starts, and gives the time of one.
let reps = (1_000_000 / n).max(1);
let time = |f: fn(Vec<NodeId>, Vec<NodeId>) -> Vec<NodeId>| -> (f64, Vec<NodeId>) {
let mut last = Vec::new();
let runs = (0..iters())
.map(|_| {
let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| leaves.clone()).collect();
let mut done = Vec::with_capacity(reps);
let t = ms(|| {
for input in &mut work {
done.push(f(Vec::new(), black_box(std::mem::take(input))));
}
});
last = done.pop().unwrap();
t / reps as f64
})
.collect();
(median(runs), last)
};
let (old, a) = time(listed);
let (new, b) = time(with_set);
assert_eq!(a, b, "both merges give the same list");
assert_eq!(a, leaves);
row("target merge, list search", old);
row("target merge, set", new);
println!(" {:<52} {:>10.1}x", "ratio", old / new);
let mut s = Session::new();
s.add_document(doc, None);
row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n));
row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n));
}
fn main() {
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
for n in [2_000, 10_000, 20_000] {
bench(n);
}
}
+1 -1
View File
@@ -826,7 +826,7 @@ pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
+8 -1
View File
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Separations Preview",
[],
None,
"{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
"{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}",
always,
separations
),
@@ -1064,6 +1064,13 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(n) = text_param(p, "only", C)? {
v.separations = Some(vec![check(n)?]);
}
// The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already
// shows alone among the active document's plates.
if let Some(n) = text_param(p, "soloToggle", C)? {
let n = check(n)?;
let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n]));
v.separations = Some(if alone { all.clone() } else { vec![n] });
}
if let Some(n) = text_param(p, "toggle", C)? {
let n = check(n)?;
let vis = v.separations.get_or_insert_with(|| all.clone());
+15 -17
View File
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
/// undo step, named as an Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let [a, b, c] = points;
let (center, radius) = shapes::circle_through(a, b, c)
let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
@@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
fn three_points(v: &Value) -> Option<[Point; 3]> {
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
/// finite numbers.
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
};
match v.as_array().map(Vec::as_slice) {
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
match v.as_array() {
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
_ => None,
}
}
/// The positions of the selected anchor points, when there are exactly three. They are counted as
/// The positions of the selected anchor points, when there are two or three. They are counted as
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
let st = s.doc()?;
if st.selection.segments.values().any(|set| !set.is_empty()) {
return Ok(None);
@@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
return Ok(None);
}
}
Ok(match points.as_slice() {
&[a, b, c] => Some([a, b, c]),
_ => None,
})
Ok(matches!(points.len(), 2 | 3).then_some(points))
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
+88 -12
View File
@@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
use super::{
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req,
};
use crate::EngineError;
@@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Width Point",
[],
None,
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed",
"{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed",
has_doc,
width_point_set
),
@@ -214,6 +214,15 @@ fn uniform() -> WidthProfile {
/// Width points closer than this (in t) are at the same place: a discontinuous point.
const SAME_T: f64 = 1e-6;
/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a`
/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s
/// place. None when `a` is out of range or not such an incoming half.
pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option<usize> {
let t = points.get(a)?.0;
let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect();
(at == [a, a + 1]).then_some(a + 1)
}
/// The stroke of `id` that width point commands edit (a compound path's for its members).
fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> {
let id = stroke_owner(d, id);
@@ -265,9 +274,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below:
}
/// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest
/// points at other positions either side change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) {
let t = points[i].0;
/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after)
/// change in proportion (by the same amount from zero).
fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) {
let scale = |v: f64, o: f64, n: f64| {
let width = if o > 1e-9 {
let product = v * n;
@@ -284,8 +293,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6
};
width.max(0.0)
};
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T);
let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]);
let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]);
for j in before.into_iter().chain(after) {
let q = &mut points[j];
(q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2));
@@ -303,6 +312,46 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
}
}
/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to
/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With
/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point.
/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after
/// with the outgoing half, once each. → the index of the point (its incoming half).
fn set_pair(
points: &mut Vec<(f64, f64, f64)>,
(i, inc): (usize, (f64, f64, f64)),
(j, out): (usize, (f64, f64, f64)),
adjust: bool,
single: Option<bool>,
) -> Result<usize> {
const C: &str = "stroke.widthPoint.set";
if width_point_pair(points, i) != Some(j) {
return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point"));
}
let at = points[i].0;
let (old_in, old_out) = (points[i], points[j]);
if (old_in.0 - inc.0).abs() > SAME_T {
return Err(bad(C, "a discontinuous width point keeps its place"));
}
let (new_in, new_out) = match single {
None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)),
Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)),
Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)),
};
// Both halves measure their neighbors from the point's place, so a point within SAME_T of the
// outgoing half but not of that place is the point after the pair.
if adjust {
adjust_adjoining(points, i, at, old_in, new_in, [true, false]);
adjust_adjoining(points, j, at, old_out, new_out, [false, true]);
}
points[i] = new_in;
points[j] = new_out;
if single.is_some() {
points.remove(j);
}
Ok(i)
}
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "stroke.widthPoint.set";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
@@ -312,6 +361,25 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "left/right must be non-negative widths"));
}
let adjust = switch_or(p, "adjustAdjoining", false, C)?;
let single = match text_param(p, "single", C)? {
None => None,
Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"),
Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")),
};
// The outgoing half of a discontinuous point: its index and side widths (points).
// `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`.
let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let out = match p.get("outIndex") {
None | Some(Value::Null) if single.is_none() && !out_widths => None,
_ => {
let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?;
let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?);
if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 {
return Err(bad(C, "left/right must be non-negative widths"));
}
Some((j, l, r))
}
};
// When the profile comes out as it was, within a rounding error (1e-9), the document and its undo
// history stay as they are.
let mut pos = 0;
@@ -324,11 +392,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width factors must be finite"));
}
let mut prof = st.profile.take().unwrap_or_else(uniform);
pos = match point_index(p, &prof, C)? {
Some(i) => {
pos = match (point_index(p, &prof, C)?, out) {
(None, Some(_)) => return Err(bad(C, "missing index")),
(Some(i), Some((j, l, r))) => {
let out = (t, l / half, r / half);
if !out.1.is_finite() || !out.2.is_finite() {
return Err(bad(C, "width factors must be finite"));
}
set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)?
}
(Some(i), None) => {
let old = prof.points[i];
if adjust {
adjust_adjoining(&mut prof.points, i, old, pt);
adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]);
}
if (old.0 - t).abs() <= SAME_T {
// Widths only: it keeps its place (and its side of a discontinuous point).
@@ -339,12 +415,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
place(&mut prof.points, pt, old.0 < t)
}
}
None => {
(None, None) => {
let old = adjust.then(|| prof.at(t));
prof.points.retain(|q| (q.0 - t).abs() > SAME_T);
let i = place(&mut prof.points, pt, true);
if let Some((left, right)) = old {
adjust_adjoining(&mut prof.points, i, (t, left, right), pt);
adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]);
}
i
}
+1 -1
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+24 -19
View File
@@ -213,7 +213,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
let filled = switch_or(p, "fill", false, C)?;
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "connect needs extend"));
}
if let Some(ext) = extend {
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("end")) => false,
@@ -238,26 +242,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
};
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// A stroke that ends on an open end of another path connects the two: (that path, its last
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
// It is checked before a stroke of one point returns, so a bad `connect` is refused there too.
let connect = match p.get("connect").filter(|v| !v.is_null()) {
Some(cn) => {
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
@@ -280,6 +267,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
None => None,
};
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
return Ok(json!({ "id": id.0 }));
}
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
// Left out, an extending stroke that ends within four Fidelities of the path's other end
+98 -17
View File
@@ -6,6 +6,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use super::clipboard::SwatchChoices;
use super::{
@@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
Ok(())
}
/// The document state that commands also change without an undo step: the perspective grid's view
/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its
/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each
/// undo and redo step keeps it as the document on its other side had it
/// ([`crate::HistoryEntry::unrecorded`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Unrecorded {
grid: vectorcraft_doc::GridPrefs,
export_settings: serde_json::Map<String, Value>,
brush: Option<Value>,
symbol: Option<Value>,
options: [bool; 5],
plane: Plane,
}
impl Unrecorded {
pub(crate) fn of(d: &Document) -> Self {
let g = PerspectiveGrid::current(d);
Unrecorded {
grid: d.grid.clone(),
export_settings: d.export_settings.clone(),
brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(),
symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(),
options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers],
plane: g.plane,
}
}
}
/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had
/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the
/// document before the undo or redo, since it changed after the step without an undo step. A part
/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also
/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the
/// active plane kept is not the one it holds.
fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) {
fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T {
if back == step { now.clone() } else { back.clone() }
}
let back = Unrecorded::of(d);
let cur = Unrecorded::of(now);
let mut want = Unrecorded {
grid: pick(&back.grid, &step.grid, &cur.grid),
export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings),
brush: pick(&back.brush, &step.brush, &cur.brush),
symbol: pick(&back.symbol, &step.symbol, &cur.symbol),
options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])),
plane: pick(&back.plane, &step.plane, &cur.plane),
};
if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) {
want.brush = back.brush.clone();
}
if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) {
want.symbol = back.symbol.clone();
}
if want == back {
return;
}
let m = Arc::make_mut(d);
for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] {
match v {
Some(v) => m.unknown.insert(key.into(), v.clone()),
None => m.unknown.remove(key),
};
}
if (want.options, want.plane) != (back.options, back.plane) {
let mut g = PerspectiveGrid::current(m);
[g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options;
if g.plane != want.plane {
g.plane = want.plane;
g.inferred = None;
}
g.keep_positioning_valid();
super::distortcmds::store_grid(m, &g);
}
m.grid = want.grid;
m.export_settings = want.export_settings;
}
fn undo(s: &mut Session, _: &Value) -> Result<Value> {
settle_interaction(s)?;
let menu = s.menu.clone();
@@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let editing = st.doc.mask_edit.map(|m| m.layer);
let editing_symbol = st.doc.symbol_edit.clone();
let doc = std::mem::replace(&mut st.doc, e.doc);
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
@@ -1076,8 +1158,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
/// Select every surviving piece while retaining intentional compound-path structure.
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
/// references with surviving object IDs.
/// parent if now empty; a compound left with one member stays a compound path, as after Clear;
/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which
/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on
/// success, replacing direct-selection references with surviving object IDs.
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
@@ -1085,13 +1169,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
// The compound paths that hold a root; one left with no members goes too.
let compounds: BTreeSet<NodeId> = roots
.iter()
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
.collect();
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
continue;
}
let original = super::path::deletion_source(d, *id)?;
@@ -1114,12 +1203,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_leaving_no_empty_compound(d, *id)?;
pieces.put(d, *id, vec![])?;
} else {
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect();
super::pathops::remove_each(d, &emptied)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
@@ -1128,19 +1219,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
/// Remove object `id`, and the compound path that held it when it was the compound's last member.
/// A compound left with one member stays a compound path, as after Clear.
fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
@@ -1751,3 +1829,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn
pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> {
v.into_iter().map(Arc::new).collect()
}
#[cfg(test)]
mod tests;
+343
View File
@@ -0,0 +1,343 @@
//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties
//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection,
//! the clipboard and the undo history exactly as removing each of them on its own does.
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks};
use super::*;
use crate::tests_large_edits::{session, square};
/// Cut's removal with every root selected whole or emptied taken out by its own
/// [`Document::remove`], and its compound path removed right after when that left it empty. The
/// tests compare [`cut_direct_selection`] with it.
fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
s.edit("Cut", |d, selection| {
let gone = selection.guides.clone();
d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id)));
let mut survivors = vec![];
let mut pieces = super::super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct || node.path_data().is_none() {
remove_one(d, *id)?;
continue;
}
let original = super::super::path::deletion_source(d, *id)?;
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths);
for (si, sp) in owned.into_iter().enumerate() {
let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp);
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
subpaths.extend(super::super::path::without_segments(sp, &cuts));
} else {
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect();
subpaths.extend(super::super::path::without_anchors(sp, &gone));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
remove_one(d, *id)?;
} else {
survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
Ok(())
})?;
ok()
}
/// Removes object `id`, and the compound path that held it when it was the compound's last member.
fn remove_one(d: &mut Document, id: NodeId) -> Result<()> {
let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
Ok(())
}
/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of
/// [`cut_direct_selection`].
fn reference_cut(s: &mut Session) {
let (direct, roots) = copy_cut_targets(s).unwrap();
assert!(direct, "the selection is a direct selection");
copy(s, &json!({})).unwrap();
cut_one_at_a_time(s, &roots).unwrap();
}
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`.
fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) {
run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()}));
for (id, anchors) in partial {
run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"}));
}
}
/// The ids of every node of the document, depth first, with the depth of each.
fn tree(d: &Document) -> Vec<(usize, NodeId)> {
fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) {
out.push((depth, n.id));
for c in n.children().into_iter().flatten() {
walk(c, depth + 1, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, 0, &mut out);
}
out
}
/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo
/// steps.
fn assert_same(a: &Session, b: &Session, when: &str) {
let (x, y) = (a.doc().unwrap(), b.doc().unwrap());
assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree");
assert!(*x.doc == *y.doc, "{when}: the document");
assert_eq!(x.selection, y.selection, "{when}: the selection");
// Each session's document has its own uid; the clipboard names the one it came from.
assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source");
let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() };
assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard");
assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps");
assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps");
}
/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks
/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after
/// the Cut.
fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session {
let (mut a, mut b) = (make(), make());
let before = a.doc().unwrap().doc.clone();
assert_same(&a, &b, "before");
run(&mut a, "edit.cut", json!({}));
reference_cut(&mut b);
assert_same(&a, &b, "Cut");
let after = a.doc().unwrap().doc.clone();
run(&mut a, "edit.undo", json!({}));
run(&mut b, "edit.undo", json!({}));
assert_same(&a, &b, "Undo");
assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document");
run(&mut a, "edit.redo", json!({}));
run(&mut b, "edit.redo", json!({}));
assert_same(&a, &b, "Redo");
assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut");
run(&mut a, "edit.undo", json!({}));
run(&mut a, "edit.redo", json!({}));
a
}
/// A new document; [`rect`] adds squares to it.
fn new_doc() -> Session {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
s
}
/// Adds a 10 pt square to the current layer, 20 pt right of the last one.
fn rect(s: &mut Session) -> NodeId {
let x = 20.0 * s.doc().unwrap().doc.node_count() as f64;
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap())
}
/// Makes a compound path of `ids` and returns it with its members in order.
fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) {
run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap());
let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect();
(c, members)
}
/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed.
fn three_anchors() -> Value {
json!([[0, 0], [0, 1], [0, 2]])
}
/// Anchors 0 and 1 of a square: Cut keeps its other three sides.
fn two_anchors() -> Value {
json!([[0, 0], [0, 1]])
}
/// The compound path whose members are cut one whole and one emptied goes with them; the other
/// compound path keeps its one member left, as a compound path.
#[test]
fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() {
let make = || {
let mut s = new_doc();
let first = [(); 2].map(|()| rect(&mut s));
let (gone, gone_members) = compound(&mut s, &first);
let second = [(); 3].map(|()| rect(&mut s));
let (kept, kept_members) = compound(&mut s, &second);
let other = rect(&mut s);
select_direct(
&mut s,
&[gone_members[0], kept_members[0]],
&[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())],
);
(s, gone, kept, kept_members[2], other)
};
let s = same_as_one_at_a_time(|| make().0);
let (_, gone, kept, left, other) = make();
let d = &s.doc().unwrap().doc;
assert!(d.node(gone).is_none(), "the compound path whose members all went is removed");
let kept = d.node(kept).expect("the compound path with a member left stays");
assert!(matches!(kept.kind, NodeKind::Compound { .. }));
assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]);
assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected");
}
/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept
/// siblings, keep the order and ids that removing them one at a time leaves.
#[test]
fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let b = [(); 4].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()}));
run(&mut s, "object.group", json!({}));
let c = [(); 4].map(|()| rect(&mut s));
select_direct(
&mut s,
&[a[0], a[2], b[3], c[1]],
&[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())],
);
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected");
}
/// Selected ruler guides go with the objects, in the Cut's undo step.
#[test]
fn cut_removes_the_selected_guides_with_the_objects() {
let make = || {
let mut s = new_doc();
let [a, b, c] = [(); 3].map(|()| rect(&mut s));
run(&mut s, "guide.add", json!({"vertical": true, "pos": 30}));
run(&mut s, "guide.add", json!({"vertical": false, "pos": 40}));
select_direct(&mut s, &[a, c], &[(b, two_anchors())]);
run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true}));
s
};
let s = same_as_one_at_a_time(make);
assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed");
assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard");
}
/// Roots that are not separate (one inside another) are removed one at a time, as before.
#[test]
fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() {
let make = || {
let mut s = new_doc();
let a = [(); 3].map(|()| rect(&mut s));
run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()}));
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
let b = rect(&mut s);
select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]);
(s, vec![a[1], group, b])
};
let (mut x, roots) = make();
let (mut y, _) = make();
copy(&mut x, &json!({})).unwrap();
copy(&mut y, &json!({})).unwrap();
cut_direct_selection(&mut x, &roots).unwrap();
cut_one_at_a_time(&mut y, &roots).unwrap();
assert_same(&x, &y, "Cut");
}
/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and
/// anchors 0 and 1 of the square after them picked.
fn many() -> Session {
let mut s = session(10_001, square);
let ids = crate::tests_large_edits::layer(&s, 0);
let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect();
select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]);
s
}
/// The tree walks [`tree_walks`] counts while `f` runs on `s`.
fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 {
let before = tree_walks();
f(s);
tree_walks() - before
}
/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's
/// tree a few times, where removing them one at a time walks it several times for each object.
#[test]
fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() {
let s = same_as_one_at_a_time(many);
assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001);
let (mut a, mut b) = (many(), many());
let batched = walks(&mut a, |s| {
run(s, "edit.cut", json!({}));
});
let one_at_a_time = walks(&mut b, reference_cut);
println!("tree walks: Cut {batched}, one at a time {one_at_a_time}");
assert!(batched <= 64, "Cut walked the document's tree {batched} times");
assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}");
}
/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux).
fn cpu_time() -> 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 middle of `v`.
fn median(mut v: Vec<Duration>) -> Duration {
v.sort_unstable();
v[v.len() / 2]
}
/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's
/// CPU and wall-clock time with the medians. Run it with
/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`.
#[test]
#[ignore = "timing; prints the numbers"]
fn direct_selection_cut_timing() {
let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default();
for round in 0..7 {
for (k, (cpu, wall)) in runs.iter_mut().enumerate() {
let mut s = many();
let (c0, w0) = (cpu_time(), Instant::now());
if k == 0 {
reference_cut(&mut s);
} else {
run(&mut s, "edit.cut", json!({}));
}
let w = w0.elapsed();
let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w);
println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]);
cpu.push(c);
wall.push(w);
}
}
for (k, (cpu, wall)) in runs.into_iter().enumerate() {
println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall));
}
}
+2 -1
View File
@@ -65,6 +65,7 @@ pub mod zip;
use serde_json::{Value, json};
pub(crate) use action_batch::action_step;
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{
@@ -95,7 +96,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub use pdfimport::{LoadOptions, page_document, pages_can_link};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
+117 -32
View File
@@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
}
for (i, c) in cmds.iter().enumerate() {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let refuse = |reason: &str| bad(C, action_step(i, id, reason));
if id.is_empty() {
return Err(bad(C, format!("commands[{i}]: missing `command`")));
return Err(refuse("missing `command`"));
}
if id == "command.batch" || id == "action.batch" {
return Err(bad(C, "batches cannot nest"));
return Err(refuse("batches cannot nest"));
}
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
if id == "prefs.import" {
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
return Err(refuse("`prefs.import` runs on its own, not as a batch step"));
}
if find_command(id).is_none() {
return Err(bad(
C,
match super::super::params::nearest_command(id) {
Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"),
None => format!("commands[{i}]: unknown command `{id}`"),
},
));
return Err(refuse(&super::super::params::unknown_command(id).to_string()));
}
}
// Every option is checked before the destination folder is made.
@@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
};
match c.get("command").and_then(Value::as_str).unwrap_or("") {
"document.save" | "file.save" => !save && (path || own_file()),
"document.save" => !save && (path || own_file()),
"file.saveAs" => !save && path,
"file.saveCopy" | "file.saveAsTemplate" => path,
"document.export" | "document.exportSelection" => !export && path,
@@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
/// the native template format writes a copy and leaves the document's file as it was.
fn retargeting_save(c: &Value, redirected: bool) -> bool {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) {
return false;
}
let params = c.get("params");
@@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
// source file in the destination folder, other than that file's own output, or of a subfolder
// of the destination folder that holds source files.
let (steps, places) = filter_steps(run.steps, override_open, false);
let (steps, places) = filter_steps(run.steps, override_open);
let run = Run { steps: &steps, ..*run };
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
let mut picker =
@@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
}
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
let (steps, places) = filter_steps(run.steps, true, false);
let (steps, places) = filter_steps(run.steps, true);
let run = Run { steps: &steps, ..*run };
let mut processed = Vec::new();
let mut failed = 0usize;
@@ -353,22 +348,13 @@ impl StemPicker {
}
}
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
/// stay, and the index of each in `cmds`.
/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the
/// steps that stay, and the index of each in `cmds`.
#[cfg(not(target_arch = "wasm32"))]
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec<Value>, Vec<usize>) {
cmds.iter()
.enumerate()
.filter(|(_, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
if drop_open && matches!(id, "document.open" | "file.open") {
return false;
}
if drop_close && matches!(id, "file.close" | "document.close") {
return false;
}
true
})
.filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open")))
.map(|(i, c)| (c.clone(), i))
.unzip()
}
@@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Va
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
match places.get(n) {
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
Some(&place) if same => EngineError::Other(action_step(place, id, reason)),
_ => e,
}
})
}
/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with
/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The
/// checks before a batch runs and the errors of its steps as they run give the same text.
pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String {
let n = index.saturating_add(1);
if id.is_empty() {
format!("action step {n} failed: {reason}")
} else {
format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id))
}
}
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
#[cfg(not(target_arch = "wasm32"))]
@@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true });
continue;
}
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs"))
|| (run.override_export && matches!(id, "document.export" | "document.exportSelection"));
if writes {
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
@@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
};
if safe_extension(&ext) {
let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft");
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
let is_save = matches!(id, "document.save" | "file.saveAs");
let artboards = if is_save {
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
} else {
@@ -693,7 +691,7 @@ fn rewrite_paths(
.map(|c| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let mut c = c.clone();
let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs"))
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export"));
if !rewrite {
return c;
@@ -2385,10 +2383,97 @@ mod tests {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(s.active().is_none(), "no file was opened");
}
/// Each step the checks before the batch refuse is named by its place in `commands`, from 1,
/// as a step that fails as it runs is, and no source file is opened.
#[test]
fn a_refused_step_is_named_by_its_place_from_1() {
let src = tmp("step-number-refused-src");
write_svg(&src, "a.svg", "#f00");
let prefix = "invalid parameters for `action.batch`: ";
let cases = [
(json!({"params": {}}), "action step 2 failed: missing `command`"),
(json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"),
(json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"),
(json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"),
(
json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}),
"action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0",
),
];
for (step, want) in cases {
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert_eq!(e, format!("{prefix}{want}"), "{step}");
assert!(s.active().is_none(), "{step}: a file was opened");
assert!(s.journal.is_empty(), "{step}: a step ran");
}
}
/// The parameter check of an `action.batch` names the step whose params it refuses, from 1;
/// that of a `command.batch` passes the step's error on as it is.
#[test]
fn the_parameter_check_names_the_refused_step() {
let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}});
let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]);
let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0";
let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}"));
let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string();
assert_eq!(e, own);
}
/// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and
/// `document.close` are not engine commands, so a step with one is refused before the batch
/// starts, with Override Open and Override Save on or off.
#[test]
fn steps_with_ids_that_are_not_engine_commands_are_refused() {
let src = tmp("step-number-aliases-src");
write_svg(&src, "a.svg", "#f00");
for id in ["file.open", "file.save", "document.close"] {
for overrides in [true, false] {
let mut s = Session::new();
let p = json!({
"folder": src.to_string_lossy(),
"overrideOpen": overrides,
"overrideSave": overrides,
"commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}],
});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(
e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")),
"{e}"
);
assert!(s.active().is_none(), "{id}: a file was opened");
}
}
}
/// `command.batch` keeps its own numbering, from 0, for a step that fails.
#[test]
fn command_batch_keeps_its_own_step_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let e = s
.execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]}))
.unwrap_err();
assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}");
}
/// A step's id in the error is cut short, as an unknown key's is.
#[test]
fn a_long_step_id_is_cut_short() {
let id = "x".repeat(10_000);
let shown = action_step(0, &id, "why");
assert!(shown.len() < 1_000, "{}", shown.len());
assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}");
assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX));
}
/// Only the error `command.batch` gives for a failed step is read as one.
#[test]
fn batch_step_failure_reads_only_a_step_error() {
+1 -1
View File
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
+3 -2
View File
@@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
vec![(Some(b), rect(b)?, false)]
}
};
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
let outs = vectorcraft_cad::export_drawings(doc, &opts, &regions).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for (board, region, crop) in drawings {
let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?;
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
enc.files.push((board, out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
+6 -3
View File
@@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
};
let rects = boards
.iter()
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
.collect::<Result<Vec<_>>>()?;
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
let flat = crate::flatten_raster_effects(doc);
let src = flat.as_ref().unwrap_or(doc);
let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?;
let mut enc = Encoded::default();
for b in boards {
let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect;
let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?;
for (b, out) in boards.into_iter().zip(outs) {
enc.files.push((Some(b), out.bytes));
for w in out.warnings {
if !enc.warnings.contains(&w) {
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged Line truncated
has_doc,
export_pdf
),
@@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password
/// and `textAs` are checked apart ([`linked_pages`]).
pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes)
}
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
+18
View File
@@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() {
assert!(e.contains("useArtboards"), "{e}");
}
#[test]
fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() {
let mut s = two_boards();
// A second rectangle on the second artboard, so the two drawings differ.
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap();
let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap();
let files = r["files"].as_array().unwrap();
let doc = &s.doc().unwrap().doc;
let o = dxf::options(&json!({"unit": "pt"})).unwrap();
assert_eq!(files.len(), doc.artboards.len());
assert_ne!(b64(&files[0]), b64(&files[1]));
for (f, board) in files.iter().zip(&doc.artboards) {
let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap();
assert_eq!(b64(f), alone.bytes, "{}", f["name"]);
}
}
#[test]
fn selected_only_exports_the_selection_in_its_layers() {
let mut s = two_boards();
@@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() {
assert!(open(&mut s, &two, json!({"pages": "1"})).is_err());
open(&mut s, &two, json!({})).unwrap();
}
/// `linkPages` takes a PDF up to the largest file placed, and nothing else.
#[test]
fn pages_can_link_a_pdf_up_to_the_largest_file_placed() {
let small = three_pages();
assert!(pages_can_link("pages.pdf", &small));
assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1];
big[..small.len()].copy_from_slice(&small);
assert!(!pages_can_link("pages.pdf", &big), "over the limit");
big.pop();
assert!(pages_can_link("pages.pdf", &big), "at the limit");
}
+26 -5
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::text::INLINE_MAX_SCALE;
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun};
use vectorcraft_text::edit;
use super::brushsym::current_symbol;
@@ -25,12 +25,33 @@ pub fn specs() -> Vec<CommandSpec> {
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
/// resolve the inline art of every text again, in the layers and in the art of symbols, graph
/// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a
/// symbol's type before the type that shows that symbol inline).
pub(crate) fn refresh(before: &Document, d: &mut Document) {
/// symbol's type before the type that shows that symbol inline). `last` is the document the last
/// refresh left resolved, with what it measured: when nothing the inline art depends on changed
/// since, only the layer trees that differ from its own are checked
/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when
/// neither document has symbols and nothing was checked.
pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> {
if before.symbols.is_empty() && d.symbols.is_empty() {
return;
return None;
}
d.resolve_inline_art_with(&mut refresh_bounds);
#[cfg(test)]
let last = last.filter(|_| !FULL_PASS.get());
let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds);
#[cfg(test)]
PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone())));
Some(pass.measured)
}
/// A document a [`refresh`] left resolved, and what that refresh measured.
pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured);
#[cfg(test)]
thread_local! {
/// Each [`refresh`] on this thread that checked the document: whether it checked only the
/// changed layer trees, and the ids of the texts in the layers that changed.
pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) };
/// Set: every [`refresh`] on this thread takes the full pass.
pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
+22 -13
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Layer…",
["Window", "Layers"],
Some("Cmd+L"),
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
"{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}",
super::maskedit::outside_mask_editing,
new_layer
),
@@ -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, 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}",
"{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, which may also go above or below a row they copy (the target among `ids`). 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
),
@@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO
fn new_layer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.new";
let below = switch_or(p, "below", false, C)?;
if below && bool_or(p, "top", false) {
let top = bool_or(p, "top", false);
if below && top {
return Err(bad(C, "`top` and `below` can't both be true"));
}
// In Draw Behind a layer given neither `top` nor `below` goes below the current layer.
let below = below || (!top && s.draw_mode == crate::DrawMode::Behind);
let st = s.doc()?;
// Above the current layer, at its level; below it with `below`; on top of everything with `top`.
let cur = st.current_layer().filter(|_| !bool_or(p, "top", false));
let cur = st.current_layer().filter(|_| !top);
add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) {
Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })),
None => Ok((None, if below { 0 } else { usize::MAX })),
@@ -723,19 +726,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
} else {
vec![id]
};
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let all_selected = add && !ids.is_empty() && {
let selected: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
ids.iter().all(|i| selected.contains(i))
};
let rows = st.layer_rows.clone();
s.select(|_, sel| {
if !add {
sel.set(ids.iter().copied());
} else if all_selected {
for i in &ids {
sel.remove(*i);
}
sel.remove_all(ids.iter().copied());
} else {
for i in &ids {
sel.add(*i);
}
sel.add_all(ids.iter().copied());
}
})?;
let st = s.doc_mut()?;
@@ -774,9 +776,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "no such rows"));
}
// Never into itself or a row inside it.
// Never into itself or a row inside it. A copy may go above or below one of the rows it
// copies, which a move there would leave where it is (#8237).
let beside_itself = copy && place != Place::Inside && ids.contains(&target);
let around = d.ancestry(target).unwrap_or_default();
if ids.iter().any(|i| around.contains(i)) {
if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) {
return Err(bad(C, "a row can't go into itself"));
}
let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect();
@@ -788,6 +792,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
parent => (parent, Some(target)),
},
};
// A copy beside a top-level layer it copies, with objects among the rows, would go inside
// that layer: into itself.
if parent.is_some_and(|p| ids.contains(&p)) {
return Err(bad(C, "a row can't go into itself"));
}
if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) {
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())));
+13 -4
View File
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Locate Object",
["Window", "Layers"],
None,
"{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}",
"{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}",
has_doc,
locate
),
@@ -435,10 +435,19 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "layer.locate")?;
let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?;
let st = s.doc_mut()?;
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![id];
let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
if layers_only {
// Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself).
let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?;
ancestry.truncate(at + 1);
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.revision += 1;
Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() }))
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
}
+34 -2
View File
@@ -7,12 +7,16 @@
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
//! and a change of selection loads only the proxies. `paint.default` resets it.
//!
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
//! resets new art when it opens such a document.
use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
use super::gradient::unplaced;
@@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> {
}))
}
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template.
/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template;
/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects
/// at full opacity, not linked to the style.
pub(crate) fn reset(s: &mut Session) {
s.paint = PaintDefaults::default();
let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned();
if let Some(g) = style {
let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) };
s.take_new_art(ap, 1.0, BlendMode::Normal, None, false);
}
}
/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the
/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode
/// as a New Document profile's are.
pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> {
let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?;
let same =
|o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout);
if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) {
return None;
}
if d.color_mode != ColorMode::Rgb {
let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb);
shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE);
super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile);
if shipped.graphic_styles.first().is_some_and(same) {
return None;
}
}
Some(g)
}
+4
View File
@@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
// The profile's links keep their relative paths, which name places from the profile's file, as
// a new document from a history state keeps its source's.
s.doc_mut()?.links_from = links_from;
// A profile whose Default Graphic Style was redefined gives new art in the document that style.
if super::newart::redefined_default_style(&s.doc()?.doc).is_some() {
super::newart::reset(s);
}
// Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both
// are views of the whole app, so Default leaves them as they are.
if settings.preview_mode == PreviewMode::Overprint {
+14 -3
View File
@@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>)
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
let key = "all";
let all = match p.get(key) {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?,
};
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
@@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
let menu = s.menu.clone();
let prev = s.active().and_then(|d| d.isolation);
let prev = st.isolation;
// An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or
// that layer is hidden or locked; anything else leaves isolation mode.
let up = prev
.filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer))
.and_then(|i| st.doc.parent_of(i))
.filter(|parent| st.doc.is_editable(*parent));
if let Some(i) = prev {
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i);
let st = s.doc_mut()?;
st.isolation = None;
st.isolation = up;
crate::cmd::distortcmds::finish_edit_text(st, i);
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
st.selection.set([target]);
+2 -2
View File
@@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Exit Isolation Mode",
[],
None,
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
has_doc,
exit_isolation
),
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Shape Properties",
[],
None,
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
+54 -1
View File
@@ -6,6 +6,7 @@ use super::{
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
convert_radii_relative, ok, selected_roots, set_corners, targets,
};
use crate::MAX_COORD;
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
@@ -98,6 +99,30 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
}
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
let now = l.line_length()?;
let mut new = l.clone();
let mut changed = false;
if let Some(len) = len
&& (len - now).abs() > 1e-9 * len.max(now)
{
new.set_line_length(len);
changed = true;
}
if let Some(a) = angle
&& new.line_length().is_some_and(|n| n > 0.0)
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
&& turn > 1e-9
&& turn < 360.0 - 1e-9
{
new.set_line_angle(a);
changed = true;
}
(changed && new != *l).then_some(new)
}
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
@@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
@@ -171,6 +196,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
let line_angle = angle("lineAngle")?;
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
// ellipse as 0° to 360°).
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
@@ -181,8 +210,26 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// When every value given is the current one, the document and its undo history stay as they
// are.
let st = s.doc()?;
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
// past the document's coordinate limit is an error before anything changes.
let mut lines = std::collections::BTreeMap::new();
if line_length.is_some() || line_angle.is_some() {
for id in &ids {
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
if let Some(new) = line_edit(l, line_length, line_angle) {
let LiveShape::Line { a, b } = &new else { continue };
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
}
lines.insert(*id, new);
}
}
}
let has_values = |id: &NodeId| {
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
if lines.contains_key(id) {
return false;
}
match live.as_deref() {
Some(l @ LiveShape::Polygon { sides: now, .. })
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
@@ -244,6 +291,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
}
*path = l.to_path();
}
if let Some(new) = lines.get(id)
&& let Some(l) = live.as_deref_mut()
{
*l = new.clone();
*path = l.to_path();
}
if let Some(on) = relative_radii
&& let Some(l) = live.as_deref_mut()
{
+9 -2
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
has_doc,
default_paint
),
@@ -1035,6 +1035,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
let style = super::newart::redefined_default_style(&before).cloned();
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
@@ -1045,7 +1047,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
r.style.stroke = Paint::None;
}
}
_ => n.appearance = Appearance::default_art().into(),
_ => {
n.appearance = match &style {
Some(g) => g.appearance_on(n).into_owned().into(),
None => Appearance::default_art().into(),
}
}
}
}
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
+137 -11
View File
@@ -36,6 +36,9 @@
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
use std::collections::HashMap;
use std::sync::OnceLock;
use serde_json::Value;
use vectorcraft_apischema::shown_key;
@@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command};
use crate::Result;
/// What a params description says about the keys of the params object.
#[derive(Debug, Default, PartialEq)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParamKeys<'a> {
/// The keys it names.
pub keys: Vec<&'a str>,
@@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool {
/// The keys a params description names, or what in it doesn't read as one.
pub fn doc_keys(doc: &str) -> std::result::Result<ParamKeys<'_>, String> {
#[cfg(test)]
PARSES.with(|n| n.set(n.get() + 1));
let mut out = ParamKeys::default();
let (mut body, mut rest) = object_body(doc)?;
let mut entries = split_top(body, ',');
@@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator<Item = &'static super::CommandSpe
/// `None`: any key (a `…` entry naming no command, or a description that doesn't parse, which
/// the tests rule out).
fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
let parsed = doc_keys(doc).ok()?;
resolve(doc, depth, &mut |doc| doc_keys(doc).ok())
}
/// [`accepted`], with `parse` reading each description it reaches.
fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option<ParamKeys<'static>>) -> Option<Vec<&'static str>> {
let parsed = parse(doc)?;
let mut keys = parsed.keys;
for more in parsed.more {
let mut named = named_commands(more).peekable();
@@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> {
if UNCHECKED.contains(&spec.id) {
return None;
}
keys.extend(accepted(spec.params, depth + 1)?);
keys.extend(resolve(spec.params, depth + 1, parse)?);
}
}
Some(keys)
}
/// What the params description of a built-in command says about its keys, read once per process
/// ([`known`]).
#[derive(Debug)]
struct Known {
/// The keys it names itself; none when it doesn't parse.
own: Vec<&'static str>,
/// [`accepted`] of it.
accepted: Option<Vec<&'static str>>,
/// [`id_stands_for_ids`] of it.
id_stands_for_ids: bool,
}
impl Known {
/// [`takes_key`] of the description.
fn takes(&self, key: &str) -> bool {
self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key))
}
}
/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's)
/// has another place.
fn text_key(doc: &str) -> (usize, usize) {
(doc.as_ptr().addr(), doc.len())
}
/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once.
/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose
/// keys change as plug-ins are installed and removed.
fn read_descriptions(docs: impl IntoIterator<Item = &'static str>) -> HashMap<(usize, usize), Known> {
let names_plugin =
|more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX));
let mut parsed: HashMap<(usize, usize), (Option<ParamKeys<'static>>, bool)> = HashMap::new();
let mut table = HashMap::new();
for doc in docs {
if table.contains_key(&text_key(doc)) {
continue;
}
let mut live = false;
let mut parse = |doc: &'static str| {
let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| {
let keys = doc_keys(doc).ok();
let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m)));
(keys, plugin)
});
live |= *plugin;
keys.clone()
};
let own = parse(doc).map(|p| p.keys).unwrap_or_default();
let accepted = resolve(doc, 0, &mut parse);
if live {
continue;
}
let mut known = Known { own, accepted, id_stands_for_ids: false };
known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc);
table.insert(text_key(doc), known);
}
table
}
/// [`Known`] of `doc` when it is the params description of a built-in command.
fn known(doc: &str) -> Option<&'static Known> {
#[cfg(test)]
if UNCACHED.get() {
return None;
}
static TABLE: OnceLock<HashMap<(usize, usize), Known>> = OnceLock::new();
TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc))
}
#[cfg(test)]
thread_local! {
/// The times [`doc_keys`] parsed a description on this thread.
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Whether [`known`] is skipped on this thread ([`uncached`]).
static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Whether [`read_descriptions`] keeps what `doc` says.
#[cfg(test)]
pub(crate) fn read_once(doc: &'static str) -> bool {
read_descriptions([doc]).contains_key(&text_key(doc))
}
/// `f`'s result with every description parsed again where it is used, as without [`known`].
#[cfg(test)]
pub(crate) fn uncached<T>(f: impl FnOnce() -> T) -> T {
let before = UNCACHED.replace(true);
let out = f();
UNCACHED.set(before);
out
}
/// Every key the description `doc` takes, those of the commands its `…` entries name included, or
/// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a
/// command in [`UNCHECKED`].
pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
accepted(doc, 0)
match known(doc) {
Some(known) => known.accepted.clone(),
None => accepted(doc, 0),
}
}
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub fn takes_key(doc: &'static str, key: &str) -> bool {
if let Some(known) = known(doc) {
return known.takes(key);
}
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
}
@@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool {
/// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names
/// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)?
pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool {
if let Some(known) = known(doc) {
return known.id_stands_for_ids;
}
takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc)
}
/// No params object of `doc` names `ids` beside a required `id`.
fn no_required_id_beside_ids(doc: &str) -> bool {
fn head(alternative: &str) -> &str {
alternative.split([':', '=', '(']).next().unwrap_or_default().trim()
}
if !takes_key(doc, "ids") || !takes_key(doc, "id") {
return false;
}
let mut rest = doc;
while let Ok((body, after)) = object_body(rest) {
let entries = split_top(body, ',');
@@ -249,9 +362,17 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
if given.is_empty() {
return Ok(());
}
let Some(keys) = accepted(doc, 0) else { return Ok(()) };
let live;
let keys = match known(doc) {
Some(known) => known.accepted.as_deref(),
None => {
live = accepted(doc, 0);
live.as_deref()
}
};
let Some(keys) = keys else { return Ok(()) };
match given.keys().find(|k| !keys.contains(&k.as_str())) {
Some(key) => Err(unknown(id, key, &keys)),
Some(key) => Err(unknown(id, key, keys)),
None => Ok(()),
}
}
@@ -933,9 +1054,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
crate::schemas::check(spec, params, false)?;
}
if matches!(id, "command.batch" | "action.batch") && !in_batch {
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() {
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true);
// An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do.
match checked {
Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))),
checked => checked?,
}
}
}
}
+1
View File
@@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[
"edit.newDocument",
"edit.colorSettings",
"edit.dropSelection",
"symbol.placeFromDocument",
"artboard.copy",
"artboard.cut",
"text.rescanFonts",
+139 -1
View File
@@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect();
for id in super::leaf_targets(s, &rest)? {
if !out.contains(&id) {
if seen.insert(id) {
out.push(id);
}
}
@@ -429,6 +431,52 @@ impl Session {
painted(first, true, &mut nodes);
node_stroke(nodes.first()?)
}
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
/// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of
/// them, and the result is `Some`, holding whether any of them has a width profile. The result
/// is `None` when a profile changes at least one of them.
///
/// The strokes are the ones `stroke.set` edits:
/// - the Appearance panel's active stroke row in each target that has an equal row
/// ([`ItemTarget::per_target`]), and the top stroke in the others;
/// - else a selected group's own stroke;
/// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]).
///
/// The art of graph designs is left out, and so are images and symbol instances without an
/// active row. The result is also `None` with nothing selected, with an object inside a symbol
/// instance selected, with type among the targets while no Appearance row is active for it,
/// and with a target that has no stroke row, since `stroke.set` gives such a target a plain
/// stroke.
pub fn brushed_strokes_profiled(&self) -> Option<bool> {
const C: &str = "stroke.set";
let st = self.active()?;
if st.selected_symbol_part().is_some() {
return None;
}
let p = json!({});
let item = item_target(self, &p, C).ok()?.of_kind(self, false);
let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? };
let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?;
if item == ItemTarget::Top {
ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. })));
}
let mut strokes = vec![];
for (id, each) in ids.iter().zip(item.per_target(self, &ids)) {
let n = st.doc.node(*id)?;
let row = each?.resolve(&n.appearance, false, C).ok()?;
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
return None;
}
strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?);
}
if strokes.is_empty() {
return None;
}
// The library is read only when every stroke names a brush.
let lib = vectorcraft_brush::library(&st.doc);
strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some()))
}
}
impl DocState {
@@ -678,6 +726,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_doc::NodeId;
#[test]
fn weight_steps_follow_units_and_stop_at_their_bounds() {
@@ -693,4 +742,93 @@ mod tests {
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
}
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
fn made(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
}
/// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list.
fn listed_merge(s: &Session, p: &Value) -> Vec<NodeId> {
let d = &s.doc().unwrap().doc;
let own = |id: &NodeId| {
d.node(*id).is_some_and(|n| {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own);
for id in super::super::leaf_targets(s, &rest).unwrap() {
if !out.contains(&id) {
out.push(id);
}
}
out
}
/// `stroke.set` with no `item` lists the same targets in the same order as a linear merge:
/// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and
/// layers, compound paths and compound shapes for their members, and each leaf once, also
/// when it is named both directly and through its group.
#[test]
fn stroke_targets_match_the_listed_merge() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 2000, "height": 400}));
let base = s.doc().unwrap().doc.layers[0].id;
let mut x = 0.0;
let mut rect = |s: &mut Session| {
x += 120.0;
made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100})))
};
let (a, b) = (rect(&mut s), rect(&mut s));
let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]})));
let (c, d) = (rect(&mut s), rect(&mut s));
let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]})));
run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]}));
let (e, f) = (rect(&mut s), rect(&mut s));
run(&mut s, "select.set", json!({"ids": [e.0, f.0]}));
let compound = made(run(&mut s, "object.compoundPath.make", json!({})));
let (g, h) = (rect(&mut s), rect(&mut s));
run(&mut s, "select.set", json!({"ids": [g.0, h.0]}));
let shape = made(run(&mut s, "object.compoundShape.make", json!({})));
let lone = rect(&mut s);
let layer = made(run(&mut s, "layer.new", json!({})));
let (j, k) = (rect(&mut s), rect(&mut s));
run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]}));
{
let doc = &s.doc().unwrap().doc;
assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two");
assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape)));
assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some());
}
let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]});
let cases = [
named.clone(),
json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}),
json!({"ids": [base.0, layer.0, base.0]}),
json!({"ids": [d.0, owned.0, base.0]}),
json!({"ids": []}),
];
for p in &cases {
assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}");
}
run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]}));
assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection");
// The edit reaches every listed target, counting a repeated one once, and leaves the other
// member of the group with its own stroke alone.
let want = listed_merge(&s, &named);
assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}");
let distinct: std::collections::HashSet<_> = want.iter().collect();
let before = s.doc().unwrap().doc.node(d).unwrap().clone();
let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3}));
let doc = &s.doc().unwrap().doc;
assert_eq!(r["objects"], distinct.len(), "{r} {want:?}");
for id in &want {
assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}");
}
assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone");
}
}
+7 -1
View File
@@ -318,8 +318,14 @@ impl Session {
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
/// for the topmost path directly inside it, which a style applied to the group links.
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
self.graphic_style_of(*self.active()?.selection.subjects().first()?)
}
/// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`]
/// gives it for the first selected object.
pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> {
let st = self.active()?;
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?);
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
+50 -1
View File
@@ -20,7 +20,7 @@ use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::swatch::str_list;
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req};
/// The extension of saved symbol libraries: native documents.
pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION;
@@ -54,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
add
),
cmd!(
"symbol.placeFromDocument",
"Place Symbol Instance",
[],
None,
"{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}",
has_doc,
place_from_document
),
cmd!(
"symbol.saveLibrary",
"Save Symbol Library…",
@@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument`
/// placed in the active document, with the symbol and the resources it uses added as a drop of
/// art from that document adds them, in one undo step. The source document is not changed.
fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.placeFromDocument";
let uid = u64_req(p, "sourceDocument", C)?;
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
let st = s.doc()?;
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?);
let parent = st.target_parent()?;
let same = uid == st.uid;
let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc));
let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?;
if !src.symbols.iter().any(|sym| sym.name == name) {
return Err(bad(C, format!("no symbol named `{name}` in the document it came from")));
}
// A symbol of the active document itself is placed as it is.
let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)]));
// The source's colors are kept even where the active document has swatches of the same names.
let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?;
let (id, placed) = s.edit("Place Symbol Instance", |d, sel| {
let placed = match &clip {
// Each symbol added takes its Symbol Options along.
Some(clip) => {
let imported = clip.import_into(d, &choices, false)?;
let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str());
renamed.unwrap_or(name).to_string()
}
None => name.to_string(),
};
let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed));
let id = d.alloc_id();
d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?;
sel.set([id]);
Ok((id, placed))
})?;
Ok(json!({ "id": id.0, "name": placed }))
}
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "symbol.saveLibrary";
let st = s.doc()?;
+10
View File
@@ -25,6 +25,10 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -136,6 +140,10 @@ pub struct DocState {
/// same document comes to the front, its type set in them is not measured again. While this
/// reference lasts, its allocation holds no other document. Not saved.
pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>,
/// The document as the last edit's refresh of inline graphics left it, and what that refresh
/// measured: the next refresh checks only the layer trees that differ from it
/// ([`cmd::inline::refresh`]). Not saved.
pub(crate) inline_resolved: Option<cmd::inline::Resolved>,
}
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
@@ -318,6 +326,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -355,6 +364,7 @@ impl DocState {
plugin_effects: Default::default(),
art_to_fit: Default::default(),
measured_in_own: None,
inline_resolved: None,
}
}
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
+7
View File
@@ -32,6 +32,9 @@ pub struct HistoryEntry {
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
/// Owned new-art snapshots included in both directional estimates.
color_mode_bytes: usize,
/// The state that changes without an undo step as the next state had it: undo and redo compare
/// it with `doc` to tell what the step changed.
pub(crate) unrecorded: Arc<crate::cmd::Unrecorded>,
}
impl Clone for HistoryEntry {
@@ -49,6 +52,7 @@ impl Clone for HistoryEntry {
serial: self.serial,
color_mode_paints: self.color_mode_paints.clone(),
color_mode_bytes: self.color_mode_bytes,
unrecorded: self.unrecorded.clone(),
}
}
}
@@ -94,6 +98,7 @@ impl HistoryEntry {
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)),
}
}
@@ -126,6 +131,7 @@ impl HistoryEntry {
serial: next_serial(),
color_mode_paints: None,
color_mode_bytes: 0,
unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)),
}
}
@@ -337,6 +343,7 @@ impl History {
e.next_bytes = after.saturating_add(e.color_mode_bytes);
e.next = std::ptr::from_ref(now) as usize;
e.serial = next_serial();
e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now));
}
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ use vectorcraft_tools::{PaintDefaults, Tool};
pub use cmd::clipboard::{Clipboard, SourceLayer};
pub use cmd::create::constrain_click;
pub use cmd::distortcmds::perspective_click;
pub use cmd::distortcmds::{perspective_click, width_point_pair};
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
+7 -2
View File
@@ -53,7 +53,8 @@ impl Session {
let mut symbol_synced =
if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) };
// Inline graphics in text follow their symbols.
cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc));
let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc));
let mut resolved = measured.map(|m| (st.doc.clone(), m));
// The document the passes below start from, for the symbol to follow what they
// change on its editing layer.
let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone());
@@ -86,7 +87,10 @@ impl Session {
let new = art(&st.doc);
if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) {
let resynced = st.doc.clone();
cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc));
let last = resolved.as_ref().or(st.inline_resolved.as_ref());
if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) {
resolved = Some((st.doc.clone(), m));
}
if !st.doc.text_threads.is_empty() {
cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc));
}
@@ -100,6 +104,7 @@ impl Session {
if !st.doc.variables.bindings.is_empty() {
Arc::make_mut(&mut st.doc).prune_variable_bindings();
}
st.inline_resolved = resolved;
if let Err(e) = symbol_synced {
Err(e)
} else if st.doc.too_deep(Some(&before)) {
+6 -2
View File
@@ -122,6 +122,7 @@ mod paintproxy;
mod panelcmds;
mod paragraphs;
mod params;
mod params_cache;
mod path_menu_enabled;
mod pathfinder_clip;
mod pathops;
@@ -371,9 +372,12 @@ fn a_long_unknown_command_id_is_answered_at_once() {
fn action_batch_names_the_nearest_command_id() {
let mut s = session();
let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "select.al"}]})).unwrap_err();
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `select.al`; did you mean `select.all`?");
assert_eq!(
e.to_string(),
"invalid parameters for `action.batch`: action step 1 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"
);
let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "nope"}]})).unwrap_err();
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `nope`");
assert_eq!(e.to_string(), "invalid parameters for `action.batch`: action step 1 (`nope`) failed: unknown command `nope`");
}
#[test]
+106
View File
@@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() {
assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0));
}
/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it
/// has one, else its members'. It answers only while each of them draws with a brush, and not
/// while an object has no stroke row, which `stroke.set` would give a plain stroke.
#[test]
fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile");
run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"}));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile");
let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'");
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile");
let c = rect(&mut s, 400.0);
run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1}));
assert!(node(&s, c).appearance.stroke().is_none());
run(&mut s, "select.set", json!({"ids": [a.0, c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke");
}
/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count.
#[test]
fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0));
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap());
assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke");
s.edit("Brush", |d, _| {
for id in [a, b] {
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
st.brush = Some("3 pt. Round".into());
}
}
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), None);
s.edit("Brush", |d, _| {
d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
Ok(())
})
.unwrap();
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the
/// brushed path inside the layer does not count.
#[test]
fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let layer = s.doc().unwrap().doc.layers[0].id;
run(&mut s, "layer.target", json!({"id": layer.0}));
run(&mut s, "appearance.addStroke", json!({}));
let rows = &node(&s, layer).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row");
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile");
run(&mut s, "stroke.set", json!({"profile": "lens"}));
assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some())));
assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was");
}
/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does
/// not count; the brushed path alone decides.
#[test]
fn brushed_strokes_profiled_leaves_out_symbol_instances() {
let mut s = session();
let a = rect(&mut s, 100.0);
run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"}));
let r = rect(&mut s, 300.0);
run(&mut s, "select.set", json!({"ids": [r.0]}));
let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap());
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }));
run(&mut s, "select.set", json!({"ids": [a.0, inst.0]}));
assert_eq!(s.brushed_strokes_profiled(), Some(false));
}
/// With the active row a stroke of the first object that another selected object has no equal
/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides.
#[test]
fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() {
let mut s = session();
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "appearance.addStroke", json!({}));
run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"}));
run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5}));
let rows = &node(&s, a).appearance.items;
let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke");
assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}");
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
run(&mut s, "appearance.setActiveItem", json!({"index": index}));
assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too");
}
#[test]
fn text_items_take_item_paint() {
let mut s = session();
+17
View File
@@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg");
}
/// The shared settings are not an undo step, so undo and redo of the steps before them leave them
/// as they are.
#[test]
fn undo_and_redo_keep_the_shared_settings() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
run(&mut s, "assets.add", json!({"ids": [a]}));
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.undo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""}));
let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone();
run(&mut s, "edit.redo", json!({}));
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings);
}
/// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or
/// mobile/density), its format settings over the saved ones, its prefix and its sub-folders.
#[test]
+85
View File
@@ -1289,6 +1289,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
}
/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused
/// before the path's brush changes: the brush, the selection and the undo history stay as they were.
#[test]
fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() {
let mut s = session();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[a]);
let undo = undo_steps(&s);
let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"});
for connect in
[json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})]
{
let mut params = one.clone();
params["connect"] = connect;
assert!(s.execute("brush.freehand", &params).is_err(), "{params}");
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays");
assert_eq!(selected(&s), [a], "{params}: the selection stays");
assert_eq!(undo_steps(&s), undo, "{params}: no undo step");
}
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
@@ -1400,6 +1423,40 @@ fn paintbrush_tool_uses_the_current_brush() {
assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err());
}
/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as
/// they are. With nothing else changed outside the history, undo back to the saved document leaves
/// it saved.
#[test]
fn undo_and_redo_keep_the_current_brush_and_symbol() {
let mut s = session();
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "A"})).unwrap();
rect(&mut s, 40.0, 10.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "B"})).unwrap();
s.doc_mut().unwrap().mark_saved();
rect(&mut s, 70.0, 10.0, 20.0, 20.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "back at the saved document");
s.execute("edit.redo", &json!({})).unwrap();
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap();
let current = |s: &mut Session| {
let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone();
(brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone())
};
let want = (json!("Arrow"), json!("A"));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(current(&mut s), want);
// A symbol made current between undoing and redoing its deletion is not kept as current.
s.execute("symbol.delete", &json!({"name": "B"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A")));
}
/// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt).
fn pressure_round(s: &mut Session) {
let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]});
@@ -1569,6 +1626,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() {
assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke());
}
/// A Bristle path made from pen samples keeps its input when saved and uses it when exported.
#[test]
fn bristle_path_keeps_and_draws_its_pen_pose() {
let mut s = session();
let id = NodeId(
s.execute(
"brush.freehand",
&json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let doc: Document = (*s.doc().unwrap().doc).clone();
let st = doc.node(id).unwrap().appearance.stroke().unwrap();
assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some());
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st));
let mut neutral = doc.clone();
let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap();
st.pressure = None;
st.tilt = None;
st.bearing = None;
st.rotation = None;
assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default()));
}
/// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it.
#[test]
fn pressure_stays_with_its_own_path() {
+30
View File
@@ -1083,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() {
}
}
/// When `tool.setOption` names no tool, the option is set on the tool that was active when the
/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that
/// switches to the Selection tool.
#[test]
fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() {
let v = ViewInfo::default();
let mut s = session();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap();
square_row(&mut s);
click_row(&mut s, v);
s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap();
assert!(s.tool_editing(), "the press is held");
let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap();
assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool");
assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder"));
assert_eq!(out["pickColorFrom"], json!("artwork"));
assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork")));
// Named while it waits, the Shape Builder is read where it waits, not made afresh from the
// preferences.
s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches"));
let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap();
assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool");
// A value set on it counts as set on the tool chosen.
s.tool_set_since_reset = false;
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap();
assert!(s.tool_set_since_reset(), "the tool chosen was set");
assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false)));
}
/// A new revision of the document made outside a command while a merge is computed on another
/// thread keeps the merge when the selected art is as it was (the next poll applies it, as the
/// command computes it), and drops it when the art changed.
+44 -10
View File
@@ -1,5 +1,6 @@
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or
//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that
//! run it, and the Circle tool.
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
@@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() {
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
}
/// Points that are not three pairs of finite numbers are an error, not a fallback.
/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at
/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same
/// are refused, and so is a circle that would reach past the canvas, from two points or from three
/// nearly on one line; nothing is drawn and no undo step is recorded.
#[test]
fn two_points_are_the_ends_of_a_diameter() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}");
let id = id_of(&out);
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0)));
assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4);
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
let (undo, count) = (undo_len(&s), object_count(&s));
let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string();
assert!(e.contains("no circle passes through these points"), "{e}");
// 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt
// off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt.
for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{points}: {e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Points that are not two or three pairs of finite numbers are an error, not a fallback.
#[test]
fn malformed_points_are_refused() {
let mut s = session();
let undo = undo_len(&s);
for points in [
json!([[0, 0], [10, 0]]),
json!([[0, 0]]),
json!([]),
json!([[0, 0], [10]]),
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
json!([[0, 0], [10, 0], [0]]),
json!([[0, 0], [10, 0], ["0", 10]]),
@@ -109,12 +139,12 @@ fn malformed_points_are_refused() {
json!([[0, 0], [10, 0], [0, 10, 3]]),
] {
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}");
}
assert_eq!(undo_len(&s), undo);
}
/// With `points` left out, the three anchor points selected with Direct Selection give the
/// With `points` left out, the two or three anchor points selected with Direct Selection give the
/// circle, from one path or several; any other number of them is an error.
#[test]
fn three_direct_selected_anchor_points_give_the_circle() {
@@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
let out = s.execute(C, &json!({"points": null})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
// Two or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
// Two anchors are the ends of a diameter: (0, 0) and (80, 0).
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
let out = s.execute(C, &json!({})).unwrap();
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}");
// One or four anchors, or a path of four anchors selected whole.
for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}");
}
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
assert!(s.execute(C, &json!({})).is_err());
@@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() {
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
let e = s.execute(C, &json!({})).unwrap_err().to_string();
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}");
assert_eq!(undo_len(&s), undo);
}
+72
View File
@@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() {
assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}");
}
/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order.
fn visible_plates(r: &Value) -> Vec<bool> {
r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect()
}
/// A session whose document has the process plates and the spot plate `Brand Orange`.
fn session_with_spot_plate() -> Session {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap();
s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap();
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap();
s
}
/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate
/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an
/// empty set of plates all give the named plate alone. It leaves the document's undo list and
/// modified state alone.
#[test]
fn separations_preview_solo_toggle_shows_every_plate_the_second_time() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
let undo = s.doc().unwrap().history.undo.len();
let dirty = s.doc().unwrap().is_dirty();
let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap());
// Off: the preview turns on with the plate alone.
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()]));
// The same plate again: every plate, the spot plate included, and the preview stays on.
assert_eq!(solo(&mut s, "Cyan"), [true; 5]);
assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on");
// A plate shown among others, then another plate while one shows alone.
assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]);
assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]);
// A hidden plate.
s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap();
assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]);
// No plate shown.
s.execute("view.separationsPreview", &json!({"plates": []})).unwrap();
assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]);
// The spot plate alone, then every plate.
assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]);
assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]);
// A plate the document doesn't have is an error and leaves the view as it is.
let before = vectorcraft_render::proof::view();
assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err());
assert_eq!(vectorcraft_render::proof::view(), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified");
// `only` stays a setter: the same plate again keeps it alone.
s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true, false, false, false, false]);
}
/// A plate counts as shown alone when no other plate of the active document shows: names left in
/// the visible set by another document's plates don't count.
#[test]
fn separations_preview_solo_toggle_counts_the_active_documents_plates() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session_with_spot_plate();
s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap();
// A new document without the spot plate: Cyan is the only one of its plates shown.
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]);
let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap();
assert_eq!(visible_plates(&r), [true; 4]);
}
#[test]
fn proof_setup_simulates_tritanopia() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
+66 -5
View File
@@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() {
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
}
/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend`
/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes
/// neither the document nor the undo history. A `connect` of null is a key left out.
#[test]
fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() {
let mut s = session();
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
let b = line(&mut s, 300.0, 200.0, 400.0, 200.0);
let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap());
let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]});
for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] {
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend");
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend");
}
let refused = |s: &mut Session, p: &serde_json::Value| {
let before = s.doc().unwrap().doc.clone();
let undo = undo_steps(s);
assert!(s.execute("path.freehand", p).is_err(), "{p}");
assert!(s.doc().unwrap().doc == before, "{p} changed the document");
assert_eq!(undo_steps(s), undo, "{p} left an undo step");
};
refused(&mut s, &with(&stroke, json!({"connect": "b"})));
let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}});
let end = "connect end must be \"start\" or \"end\"";
for e in [json!("middle"), json!(1), json!(null)] {
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end);
}
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id");
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number");
let other = "connect needs a path other than the one extended";
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other);
refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end");
for p in [
with(&one, json!({"connect": "b"})),
with(&one, json!({"connect": {"id": 999_999, "end": "end"}})),
with(&one, json!({"connect": {"id": group.0, "end": "end"}})),
] {
refused(&mut s, &p);
}
assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed");
// A good `connect`, or a null one, on a stroke of one point leaves the path as it was.
let undo = undo_steps(&s);
for connect in [json!({"id": b.0, "end": "start"}), json!(null)] {
assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0));
}
assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo));
// Null without `extend`, `connect` is left out, and the stroke draws a new path.
s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap();
assert_eq!(paths(&s).len(), 5);
}
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
#[test]
@@ -6292,14 +6347,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() {
}
}
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more.
/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is
/// an error that leaves the option as it was.
#[test]
fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() {
let mut s = session();
for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap();
for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] {
let before = s.tool_options_of(tool)["fidelity"].clone();
let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err();
assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100"));
assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}");
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap();
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}");
let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}}));
assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}");
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}");
}
}
+213
View File
@@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}");
assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke");
}
/// What a click at (`x`, 100) with `opt` hits.
fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option<NodeId> {
vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf)
}
/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square.
fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) {
square(s);
let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap());
run(s, "select.set", json!({"ids": [inner.0]}));
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance
/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the
/// instance, in a symbol placed inside another symbol too.
#[test]
fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() {
for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", fill);
offset_row(&mut s, id, row, 10.0);
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
let r = render(&s);
assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100));
assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100));
}
// An effect of the instance's own reshapes the art as well.
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
offset_row(&mut s, id, row, 10.0);
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100));
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100));
}
/// A click where the effect on a symbol instance's fill or stroke paints its art outside the
/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by
/// Path Only and outline mode do not.
#[test]
fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(hit_at(&s, 44.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill");
assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance");
assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill");
assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out");
assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke");
assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill");
assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art");
// A path in the art with an Offset Path of its own: both offsets grow what it draws.
let mut s = session();
let art = square(&mut s);
run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art");
}
/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what
@@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}");
assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill");
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
@@ -292,6 +387,124 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
/// effect grows what that fill paints, and a click there selects the instance.
#[test]
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
// The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side.
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let im = NodeId(r["ids"][0].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [im.0]}));
run(&mut s, "appearance.addFill", json!({}));
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 70.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100));
assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill");
assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill");
}
/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect
/// grows the result, and a click past both shapes where only the subtracted shape would grow does
/// not select the instance.
#[test]
fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() {
let mut s = session();
// The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80.
let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"weight": 4}));
let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 45.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100));
assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100));
assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill");
assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow");
}
/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a
/// click where only its original shapes would grow does not select the instance.
#[test]
fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
assert!(node(&s, g).extras().shaper.is_some());
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 57.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape");
}
/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the
/// instance's stroke effect moves what that stroke paints, and a click selects the instance where
/// the canvas draws the moved stroke, not inside the original shapes.
#[test]
fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble removes the front rectangle's face; the group's stroke outlines both rectangles.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
let stroke = node(&s, g).appearance.items.len() - 1;
run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4}));
run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1}));
assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row");
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape");
}
/// Of several fills, only the topmost one's effects reach the art, and only while it is visible.
#[test]
fn only_the_topmost_visible_instance_fill_reshapes_the_art() {
+239
View File
@@ -529,6 +529,245 @@ fn saved_documents_keep_inline_graphics() {
assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds);
}
/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns
/// the ids of each group's rectangles.
fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec<Vec<NodeId>> {
s.edit("Rectangles", |d, _| {
let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut ids = vec![];
let mut made = vec![];
for g in 0..groups {
let kids: Vec<Arc<Node>> = (0..each)
.map(|i| {
let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone()))
})
.collect();
ids.push(kids.iter().map(|k| k.id).collect());
made.push(Arc::new(Node::group(d.alloc_id(), kids)));
}
match Arc::make_mut(&mut d.layers[0]).children_mut() {
Some(kids) => kids.extend(made),
None => panic!("the first layer holds art"),
}
Ok(ids)
})
.unwrap()
}
/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on
/// `fast`; checks that both leave the same document and that each refresh returned the same changed
/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees.
fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec<bool> {
let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut()));
take();
cmd::inline::FULL_PASS.set(true);
step(full);
cmd::inline::FULL_PASS.set(false);
let want = take();
step(fast);
let got = take();
assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc);
let ids = |passes: &[(bool, Vec<NodeId>)]| passes.iter().map(|(_, ids)| ids.clone()).collect::<Vec<_>>();
assert_eq!(ids(&got), ids(&want));
assert!(want.iter().all(|(partial, _)| !partial));
got.iter().map(|(partial, _)| *partial).collect()
}
/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and
/// the document and the changed texts are those of the full pass; a change to a symbol's art, its
/// natural size or anything else a symbol is measured with checks them all.
#[test]
fn refreshing_only_changed_trees_matches_the_full_pass() {
let setup = |s: &mut Session| {
circle_symbol(s, "Tap", 10.0);
circle_symbol(s, "Dot", 6.0);
let groups = rect_groups(s, 20, 10);
let id = text(s, "Tap here");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap();
// Type showing Dot inline becomes the opacity mask of a rectangle.
let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone();
let mask = text(s, "Dot");
s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap();
(groups, id)
};
let (mut full, mut fast) = (session(), session());
let (groups, id) = setup(&mut full);
assert_eq!(setup(&mut fast), (groups.clone(), id));
let rect = groups[3][4].0;
let len = obj(&fast, id).plain_text().len();
let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p);
let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p);
// A rectangle beside 19 unchanged groups moves.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Type with an inline graphic is edited, gets a second one, and loses it again.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap();
s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap();
s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap();
});
assert!(only_changed(&passes), "{passes:?}");
// Dot's art is redefined: the type in the opacity mask follows it.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot"));
assert!(passes.contains(&false), "{passes:?}");
// Tap's natural size changes, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.edit("Size", |d, _| {
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] }));
Ok(())
})
.unwrap();
});
assert!(all(&passes), "{passes:?}");
let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap"));
assert!(b.is_some() && b == want, "{b:?} {want:?}");
// 9-slice guides for Tap, its art unchanged.
let passes = same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap();
});
assert!(all(&passes), "{passes:?}");
// Symbol editing mode, entered and left, a rectangle moved inside it.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
s.execute("symbol.exitEditing", &json!({})).unwrap();
});
// Undo and redo, then edits after them.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap();
});
// Fonts scanned again, then another move.
same_as_full_pass(&mut full, &mut fast, &|s| {
s.execute("text.rescanFonts", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap();
});
}
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
fn thread_cpu() -> Option<std::time::Duration> {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
}
/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the
/// wall clock.
fn time_ms(f: impl FnOnce()) -> f64 {
let d = match thread_cpu() {
Some(before) => {
f();
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
}
None => {
let start = std::time::Instant::now();
f();
start.elapsed()
}
};
d.as_secs_f64() * 1000.0
}
/// The median, fastest and slowest of `runs`, as text.
fn spread(runs: &mut [f64]) -> String {
runs.sort_by(f64::total_cmp);
format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1])
}
/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with
/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100
/// groups, with three symbols and one line of type showing one of them inline: the refresh alone,
/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going
/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on
/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`.
#[test]
#[ignore = "a benchmark: run with --ignored --nocapture"]
fn inline_refresh_perf() {
const RUNS: usize = 7;
eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)");
for n in [5_000, 50_000, 200_000] {
let mut s = session();
for name in ["A", "B", "C"] {
circle_symbol(&mut s, name, 10.0);
}
let groups = rect_groups(&mut s, 100, n / 100);
let id = text(&mut s, "Type");
s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap();
let rect = groups[50][7];
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
// The refresh alone, after the same move made on a copy of the resolved document.
let resolved = s.doc().unwrap().inline_resolved.clone().unwrap();
let before = resolved.0.clone();
// The rectangle and the group and layer above it become new nodes, as a move makes them.
let mut after = (*before).clone();
assert!(after.node_mut(rect).is_some());
// Each run times EACH refreshes, or EACH commands, and gives the time of one.
const EACH: usize = 20;
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..RUNS {
let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]);
let mut go_full = || {
cmd::inline::FULL_PASS.set(true);
full.push(
time_ms(|| {
for d in &mut a {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
cmd::inline::FULL_PASS.set(false);
};
let mut go_partial = || {
partial.push(
time_ms(|| {
for d in &mut b {
cmd::inline::refresh(Some(&resolved), &before, d);
}
}) / EACH as f64,
);
};
if run % 2 == 0 {
go_full();
go_partial();
} else {
go_partial();
go_full();
}
assert_eq!(a, b);
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial));
// The whole command, moving the rectangle back and forth.
let (mut full, mut partial) = (vec![], vec![]);
for run in 0..2 * RUNS {
let take_full = (run / 2) % 2 == run % 2;
cmd::inline::FULL_PASS.set(take_full);
let ms = time_ms(|| {
for i in 0..EACH {
let dx = if i % 2 == 0 { -1 } else { 1 };
s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap();
}
}) / EACH as f64;
cmd::inline::FULL_PASS.set(false);
if take_full { full.push(ms) } else { partial.push(ms) }
}
eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial));
cmd::inline::PASSES.with(|p| p.borrow_mut().clear());
}
}
#[test]
fn create_outlines_turns_inline_graphics_into_symbol_instances() {
let mut s = session();
+230
View File
@@ -213,6 +213,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() {
assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]);
}
/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty
/// third layer `e`.
#[derive(Clone, Copy)]
struct Column {
layer: NodeId,
sub: NodeId,
a: NodeId,
g: NodeId,
b: NodeId,
c: NodeId,
o: NodeId,
e: NodeId,
}
fn column_start() -> (Session, Column) {
let mut s = session();
let (layer, sub, a, g, b, c) = tree(&mut s);
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let other = id(&run(&mut s, "layer.new", json!({})));
let o = rect(&mut s, 200.0);
let e = id(&run(&mut s, "layer.new", json!({})));
run(&mut s, "select.none", json!({}));
let top: Vec<NodeId> = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect();
assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}");
(s, Column { layer, sub, a, g, b, c, o, e })
}
type Prep = dyn Fn(&mut Session, Column);
/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the
/// same selection, reply, current layer, highlighted rows and revision as removing or adding each
/// id of `art` one at a time. Returns the session the click ran in.
fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec<NodeId>) -> (Session, Column) {
let (mut new, t) = column_start();
prep(&mut new, t);
let row = row(t);
let before = new.doc().unwrap().selection.clone();
let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true}));
let (mut old, t) = column_start();
prep(&mut old, t);
let ids = art(t);
let st = old.doc().unwrap();
let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i));
let rows = st.layer_rows.clone();
old.select(|_, sel| {
for i in &ids {
if all_selected { sel.remove(*i) } else { sel.add(*i) }
}
})
.unwrap();
old.doc_mut().unwrap().layer_rows = rows;
let (n, o) = (new.doc().unwrap(), old.doc().unwrap());
assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}");
assert_eq!(ids_sel(&reply), o.selection.objects);
assert_eq!(n.active_layer, o.active_layer);
assert_eq!(n.highlighted_rows(), o.highlighted_rows());
assert_eq!(n.revision, o.revision);
assert_eq!(undos(&new), undos(&old));
(new, t)
}
#[test]
fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() {
// `o` outside the layer is selected first and is the key object and the target; `a` is
// selected by one anchor, which is the key anchor.
let partly: &Prep = &|s, t| {
run(s, "layer.setCurrent", json!({"id": t.sub.0}));
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects = vec![t.o, t.a];
sel.anchors.insert(t.a, [(0, 1)].into());
sel.key = Some(t.o);
sel.key_anchor = Some((t.a, (0, 1)));
sel.target = Some(t.o);
};
let layer_art = |t: Column| vec![t.c, t.a, t.g];
// Some of the layer's art is selected: the rest is added after what was selected.
let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]);
assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked");
assert!(sel.target.is_none());
// All of it is selected, `a` as the key object: it is removed, with its anchors, key and key
// anchor.
let all: &Prep = &|s, t| {
partly(s, t);
let sel = &mut s.doc_mut().unwrap().selection;
sel.objects.extend([t.c, t.g]);
sel.key = Some(t.a);
};
let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.objects, vec![t.o]);
assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none());
// An object row, a group row and an empty layer's row.
shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]);
shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]);
shift_column_matches_each_id(partly, |t| t.e, |_| vec![]);
// A locked sublayer's row, and rows outside and inside the isolated group.
let locked: &Prep = &|s, t| {
partly(s, t);
run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true}));
};
shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]);
let isolated: &Prep = &|s, t| {
partly(s, t);
s.doc_mut().unwrap().isolation = Some(t.g);
};
shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]);
shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]);
}
fn ids_sel(v: &Value) -> Vec<NodeId> {
v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
@@ -481,6 +592,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() {
assert_eq!(children(&s, layer), vec![front, under, back]);
}
/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo
/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new
/// sublayers are not affected.
#[test]
fn new_layers_go_below_the_current_one_in_draw_behind() {
let mut s = session();
let (layer, sub, a, g, _, c) = tree(&mut s);
run(&mut s, "view.drawMode", json!({"mode": "behind"}));
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let before = undos(&s);
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer");
assert_eq!(undos(&s), before + 1);
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]);
assert_eq!(s.doc().unwrap().current_layer(), Some(n));
run(&mut s, "edit.undo", json!({}));
assert_eq!(children(&s, layer), vec![c, sub]);
// The Create New Layer button sends `top: false` for a plain click: still below.
run(&mut s, "layer.setCurrent", json!({"id": sub.0}));
let n = id(&run(&mut s, "layer.new", json!({"top": false})));
assert_eq!(children(&s, layer), vec![c, n, sub]);
run(&mut s, "edit.undo", json!({}));
// At the top level, and with options.
run(&mut s, "layer.setCurrent", json!({"id": layer.0}));
let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true})));
let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
assert_eq!(order(&s), vec![back, layer]);
assert!(node(&s, back).locked);
// `top` and `below` win over the drawing mode.
let top = id(&run(&mut s, "layer.new", json!({"top": true})));
assert_eq!(order(&s), vec![back, layer, top]);
let below = id(&run(&mut s, "layer.new", json!({"below": true})));
assert_eq!(order(&s), vec![back, layer, below, top]);
assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err());
// New sublayers still go on top of the parent's contents.
let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0})));
assert_eq!(children(&s, sub), vec![a, g, inner]);
// Draw Inside and Draw Normal put it above.
run(&mut s, "select.set", json!({"ids": [c.0]}));
for mode in ["inside", "normal"] {
run(&mut s, "view.drawMode", json!({"mode": mode}));
assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal });
run(&mut s, "layer.setCurrent", json!({"id": back.0}));
let n = id(&run(&mut s, "layer.new", json!({})));
assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}");
}
}
#[test]
fn rows_move_above_below_and_into_layers_and_groups() {
let mut s = session();
@@ -643,6 +802,45 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected");
}
/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up
/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still
/// refused.
#[test]
fn a_copy_goes_above_or_below_a_row_it_copies() {
let mut s = session();
let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let [only] = layers(&s)[..] else { panic!("one layer") };
for place in ["above", "below", "inside"] {
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself");
}
assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err());
assert_eq!(layers(&s), vec![only], "nothing changed");
let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true})));
assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original");
let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true})));
assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it");
run(&mut s, "edit.undo", json!({}));
assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step");
}
/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a
/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused,
/// and nothing changes.
#[test]
fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() {
let mut s = session();
let bottom = s.doc().unwrap().doc.layers[0].id;
let other = id(&run(&mut s, "layer.new", json!({})));
let r = rect(&mut s, 0.0);
assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer");
let count = s.doc().unwrap().doc.node_count();
for place in ["above", "below"] {
let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true});
assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it");
}
assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied");
}
/// The selected art in rows dragged into a hidden layer or group is deselected, the key object
/// included. Undo puts the rows back and selects the art again.
#[test]
@@ -904,6 +1102,38 @@ fn locate_object_highlights_its_row() {
assert!(s.execute("layer.locate", &json!({})).is_err());
}
/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer
/// or sublayer holding the object, through any groups; a layer locates itself.
#[test]
fn locate_layer_highlights_the_layer_holding_the_object() {
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
run(&mut s, "select.set", json!({"ids": [b.0]}));
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true}));
assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself");
// Off, the object's own row is highlighted, as before.
assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]}));
// Bad input changes nothing.
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
-28
View File
@@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() {
}
}
/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first
/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does
/// not refuse it, and one in the first asset does.
#[test]
fn confined_single_file_pdf_checks_the_document_it_carries() {
use crate::file_access::{AutomationRoots, confine};
let away = Folder::new("single-pdf-away");
let home = Folder::new("single-pdf-home");
let photo = away.file("photo.png");
write(&photo, &png(60, 30, RED));
let mut s = session();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
let placed = place(&mut s, &photo);
let mut assets = vec![];
for id in [rect, placed] {
assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap());
}
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]});
let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}");
let reversed = [assets[1], assets[0]];
let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string();
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
}
/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with
/// Preserve Editing, a package's document) carry the document without the Export for Screens
/// folder when it is outside the read roots, with the other export settings and the art; the open
+8 -3
View File
@@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) {
(s, a)
}
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the
/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them
/// back), and its warnings.
/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK
/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings,
/// as PDF import reads them back), and its warnings.
fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap();
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
@@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) {
if !nums.is_empty() {
out.push(nums.into_iter().rev().collect());
}
} else if *w == "k" {
let nums: Vec<f32> = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect();
if nums.len() == 4 {
out.push(nums.into_iter().rev().collect());
}
}
}
}
+101
View File
@@ -524,6 +524,107 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
}
}
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
/// length applies before the angle, every selected line takes them in one undo step, and a value
/// that changes nothing records none.
#[test]
fn a_line_takes_its_length_and_angle() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| {
NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap())
};
let id = line(&mut s, (100.0, 100.0), (200.0, 100.0));
let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { live: Some(l), path, .. } => {
let LiveShape::Line { a, b } = **l else { panic!("{l:?}") };
assert_eq!(*path, l.to_path(), "the path follows the line");
(a.x, a.y, b.x, b.y)
}
k => panic!("{k:?}"),
};
let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| {
assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}")
};
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
run(&mut s, json!({"lineLength": 50}));
near(ends(&s, id), (100.0, 100.0, 150.0, 100.0));
// 90° points up the page.
run(&mut s, json!({"lineAngle": 90}));
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
let n = steps(&s);
for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] {
run(&mut s, same.clone());
assert_eq!(steps(&s), n, "{same} records no undo step");
}
near(ends(&s, id), (125.0, 125.0, 125.0, 75.0));
run(&mut s, json!({"lineLength": 20, "lineAngle": 0}));
near(ends(&s, id), (115.0, 115.0, 135.0, 115.0));
assert_eq!(steps(&s), n + 1, "both in one step");
run(&mut s, json!({"lineAngle": 180}));
near(ends(&s, id), (135.0, 115.0, 115.0, 115.0));
run(&mut s, json!({"lineAngle": -90}));
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") };
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0));
// Several lines: each keeps its own first end, in one undo step.
let other = line(&mut s, (0.0, 0.0), (0.0, 40.0));
let n = steps(&s);
run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10}));
near(ends(&s, id), (125.0, 105.0, 125.0, 115.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 10.0));
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, other), (0.0, 0.0, 0.0, 40.0));
// Bad values, and a line that would reach past the coordinate limit, change neither line.
let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0));
let n = steps(&s);
for bad in [
json!({"ids": [id.0], "lineLength": 0}),
json!({"ids": [id.0], "lineLength": -3}),
json!({"ids": [id.0], "lineLength": "long"}),
json!({"ids": [id.0], "lineAngle": "up"}),
json!({"ids": [id.0], "lineLength": 1e300}),
json!({"ids": [id.0, far.0], "lineLength": 200_000}),
] {
assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
assert_eq!(steps(&s), n, "{bad}");
}
near(ends(&s, id), (125.0, 105.0, 125.0, 125.0));
near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0));
// A length past the coordinate limit is fine while both ends stay inside it.
let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0));
run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000}));
near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0));
// A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right.
let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0));
assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0));
let n = steps(&s);
run(&mut s, json!({"lineAngle": 45}));
assert_eq!(steps(&s), n);
run(&mut s, json!({"lineLength": 30}));
near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0));
// A very short length is applied.
let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12}));
assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change");
assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck));
// A length so short that the rounded ends do not move records no undo step.
let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0));
let n = steps(&s);
run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20}));
assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing");
near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0));
// Other live shapes ignore the line params.
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
let n = steps(&s);
run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45}));
assert_eq!(steps(&s), n);
}
#[test]
fn relative_corner_rounding_keeps_fraction_on_resize() {
let (mut s, id) = session();
+69
View File
@@ -4473,6 +4473,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() {
assert_eq!(selected(&s), vec![g]);
}
/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one
/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true`
/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a
/// sublayer still leaves in one call.
#[test]
fn exit_isolation_goes_up_one_layer_from_a_sublayer() {
let mut s = session();
let top = s.doc().unwrap().doc.layers[0].id;
let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap());
s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
let isolation = |s: &Session| s.doc().unwrap().isolation;
let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap();
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
let before = history(&s);
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer");
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer");
assert_eq!(history(&s), before, "no undo step");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": true}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true");
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
exit(&mut s, json!({"all": false}));
assert_eq!(isolation(&s), Some(mid), "all: false");
for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] {
let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string();
assert!(e.contains("`all` must be true or false"), "{bad}: {e}");
assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated");
}
// A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves.
s.execute("object.isolate", &json!({"id": deep.0})).unwrap();
s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap();
exit(&mut s, json!({}));
assert_eq!(isolation(&s), None, "hidden parent layer");
s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap();
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
exit(&mut s, json!({}));
assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer");
}
/// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that
/// Lock Guides has locked since, so a move after them leaves the guides where they are.
#[test]
@@ -5689,3 +5741,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() {
let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap();
assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}");
}
/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave
/// the guides locked.
#[test]
fn lock_guides_is_not_an_undo_step() {
let mut s = session();
let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
sel(&mut s, &[g]);
s.execute("view.guides.make", &json!({})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.guides_locked());
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.guides_locked());
}
+63
View File
@@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The fill, stroke and weight of `id` in the active document.
fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option<f64>) {
let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap();
(n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
}
#[test]
fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() {
use vectorcraft_color::Paint;
let (mut s, dir) = with_profiles("default-style");
// The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke.
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 0.25})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
let style = s.doc().unwrap().doc.graphic_styles[0].clone();
let red = style.appearance.stroke_paint();
assert!(matches!(red, Paint::Solid { .. }), "{red:?}");
assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}");
// The Mobile profile is saved as shipped.
s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap();
s.execute("document.save", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let green = s.paint.fill.clone();
// A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them.
s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap();
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25));
let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
// Default Fill and Stroke gives the selection and the defaults that look again, as one undo step.
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25)));
assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
// Nothing to change: no undo step.
let step = s.doc().unwrap().history.step();
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.step(), step);
// The new art is not linked to the style.
assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none());
// A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose.
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap();
s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap();
assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk);
assert_eq!(s.paint.fill, green);
// So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black.
s.execute("file.new", &json!({})).unwrap();
assert_eq!(s.paint.fill, green);
s.execute("paint.default", &json!({})).unwrap();
assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_profile_follows_the_preset_access_and_reset() {
let (mut s, dir) = with_profiles("choice");
+1
View File
@@ -430,6 +430,7 @@ fn set_live_shape_refuses_an_unknown_key() {
json!({"id": 3, "radius": 5}),
json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}),
json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}),
json!({"ids": [3], "lineLength": 72, "lineAngle": 90}),
json!({"items": null}),
] {
assert!(check_params(ID, &ok).is_ok(), "{ok}");
+168
View File
@@ -0,0 +1,168 @@
//! The params description of each built-in command is parsed once per process; the answers read
//! from it are those of parsing it where they are used.
use std::hint::black_box;
use serde_json::{Value, json};
use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached};
use crate::{Session, command_specs};
/// Every answer the key functions give about `doc` for command `id`, as text.
fn answers(id: &str, doc: &'static str) -> Vec<String> {
let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default();
let accepted = accepted_keys(doc);
let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))];
let near = own.first().map(|k| format!("{k}q"));
for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) {
out.push(format!("{key}: {}", takes_key(doc, key)));
}
let all: serde_json::Map<String, Value> = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect();
let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)];
cases.extend(near.map(|k| json!({ k: 1 })));
for params in cases {
out.push(format!("{params}: {:?}", check_keys(id, doc, &params)));
}
out
}
#[test]
fn every_command_gets_the_answers_of_its_parsed_description() {
for c in command_specs() {
assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id);
}
}
#[test]
fn a_built_in_description_is_not_parsed_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let run = |s: &mut Session| {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap();
s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap();
for c in command_specs() {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err());
}
};
run(&mut s);
PARSES.set(0);
run(&mut s);
assert_eq!(PARSES.get(), 0, "descriptions parsed again");
// Without the table each command parses its description where it is used.
uncached(|| run(&mut s));
assert!(PARSES.get() > command_specs().len());
}
/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed
/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are
/// installed and removed.
#[test]
fn other_descriptions_are_parsed_where_they_are_used() {
let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap();
let copy: &'static str = String::from(spec.params).leak();
assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params));
PARSES.set(0);
assert!(takes_key(copy, "ids") && id_stands_for_ids(copy));
assert!(PARSES.get() > 0);
assert!(read_once("{a, …settings as file.new}"));
assert!(!read_once("{a, …settings as plugin.some.command}"));
assert!(!read_once("{a, …the options of `plugin.some.command`}"));
}
/// This thread's CPU time in ns where Linux reports it, else the time since `start`.
fn now(start: std::time::Instant) -> (u128, bool) {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok());
match cpu {
Some(ns) => (ns, true),
None => (start.elapsed().as_nanos(), false),
}
}
fn median(mut v: Vec<u128>) -> u128 {
v.sort_unstable();
v[v.len() / 2]
}
/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints
/// the time of the key questions over every built-in description and of `Session::execute` on a
/// one-object document, with descriptions parsed where they are used (`parse`) and read once
/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux.
#[test]
#[ignore = "benchmark"]
fn bench_params_keys_once() {
let start = std::time::Instant::now();
let specs = command_specs();
let questions = || {
for c in specs {
black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id")));
black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params)));
}
};
let time = |f: &dyn Fn()| {
let t = now(start);
f();
(now(start).0 - t.0, t.1)
};
questions();
uncached(questions);
let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true);
for _ in 0..7 {
let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions())));
let (o, c2) = time(&|| (0..200).for_each(|_| questions()));
parse.push(p);
once.push(o);
cpu &= c1 && c2;
}
let per = |ns: u128| ns / (200 * specs.len() as u128);
println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" });
println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once)));
for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] {
let doc = || {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) };
(s, p)
};
let run = |s: &mut Session, p: &Value| {
for _ in 0..20_000 {
black_box(s.execute(cmd, p).unwrap());
}
};
let ((mut a, pa), (mut b, pb)) = (doc(), doc());
assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result");
let timed = |s: &mut Session, p: &Value, cached: bool| {
let t = now(start).0;
if cached {
run(s, p)
} else {
uncached(|| run(s, p))
}
now(start).0 - t
};
let (mut parse, mut once) = (Vec::new(), Vec::new());
for i in 0..7 {
let (mut s1, p1) = doc();
let (mut s2, p2) = doc();
if i % 2 == 0 {
parse.push(timed(&mut s1, &p1, false));
once.push(timed(&mut s2, &p2, true));
} else {
once.push(timed(&mut s2, &p2, true));
parse.push(timed(&mut s1, &p1, false));
}
// Each document has a `uid` of its own.
let state = |s: &Session| {
let mut d = crate::inspect::document(s);
d.as_object_mut().unwrap().remove("uid");
d
};
assert_eq!(state(&s1), state(&s2), "{cmd}: same document");
}
let ms = |ns: u128| ns as f64 / 1e6;
println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once)));
}
}
+85
View File
@@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() {
assert_eq!(PerspectiveGrid::from_doc(&back), Some(g));
}
/// The view options are not undo steps, so undo and redo of other steps leave them as they are:
/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a
/// grid definition brings back the old grid with the current view options.
#[test]
fn undo_and_redo_keep_the_view_options() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
let old = grid(&s);
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
let n = undo_len(&s);
for (id, on) in
[("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)]
{
run(&mut s, id, json!({"on": on}));
}
run(&mut s, "perspective.grid.show", json!({"visible": false}));
assert_eq!(undo_len(&s), n);
let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible);
let want = (true, true, false, true, false);
assert_eq!(view(&grid(&s)), want);
// Undo the one-point preset: the two-point grid comes back with today's view options.
s.execute("edit.undo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want));
// Undo the rectangle, which left the grid alone.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
// An option changed now holds through the redo steps.
run(&mut s, "perspective.grid.lock", json!({"on": false}));
s.execute("edit.redo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = grid(&s);
assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false)));
}
/// The view options set on a document whose steps hold no grid yet stay as they are when undo
/// brings back a step without one, and the active plane chosen without an undo step stays too.
#[test]
fn undo_keeps_the_view_options_of_a_grid_no_step_defined() {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40}));
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40}));
assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY));
run(&mut s, "perspective.grid.show", json!({"visible": true}));
run(&mut s, "perspective.grid.lock", json!({"on": true}));
run(&mut s, "perspective.grid.snap", json!({"on": false}));
run(&mut s, "perspective.plane.set", json!({"plane": "ground"}));
let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane);
let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground);
assert_eq!(view(&grid(&s)), want);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(view(&grid(&s)), want);
}
/// A step that changed a view option itself takes it back on undo and sets it again on redo: a
/// preset shows the grid, and a grid definition can lock it.
#[test]
fn undo_takes_back_the_view_options_a_step_changed() {
let mut s = session();
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
run(&mut s, "perspective.grid.show", json!({"visible": false}));
run(&mut s, "perspective.grid.preset", json!({"kind": 1}));
assert!(grid(&s).visible);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!grid(&s).visible, "the preset showed the grid");
s.execute("edit.redo", &json!({})).unwrap();
assert!(grid(&s).visible);
let cell = grid(&s).cell;
run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0}));
assert!(grid(&s).locked);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0));
// An option the step left alone and changed after it stays as it is.
run(&mut s, "perspective.grid.snap", json!({"on": false}));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (false, false));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!((grid(&s).locked, grid(&s).snap), (true, false));
}
/// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as
/// another value that is not true or false: the grid and the undo history stay as they were. Null is
/// read as the key left out, so it toggles the option.
+17
View File
@@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() {
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
}
/// The grid preferences are not an undo step in the documents they apply to, so undo and redo
/// leave the grid as the preferences set it.
#[test]
fn undo_and_redo_keep_the_grid_prefs() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (36.0, 4));
s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
let g = &s.doc().unwrap().doc.grid;
assert_eq!((g.spacing, g.subdivisions), (18.0, 3));
}
/// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the
/// desktop app restores them at launch, they give `file.new`'s document their grid.
#[test]
+66
View File
@@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1);
}
/// `symbol.placeFromDocument` places another open document's symbol in the active document as
/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A
/// second placement uses what the first added; the source document is left as it was; a symbol
/// of the active document itself is placed as it is; a closed document, a name the document does
/// not have and bad params are errors that change nothing.
#[test]
fn another_documents_symbol_is_added_and_placed_in_one_step() {
let mut s = kit();
let source = s.doc().unwrap().uid;
let source_doc = s.doc().unwrap().doc.clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}));
assert_eq!(undo_len(&s), before + 1, "added and placed in one step");
assert_eq!(r["name"], "Badge");
let mut names = symbols(&s);
names.sort();
assert_eq!(names, ["Badge", "Star"], "the nested Star came along");
assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0));
let placed = NodeId(r["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().selection.objects, [placed]);
let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") };
assert_eq!(symbol, "Badge");
let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned();
assert!(size(doc(&s)).is_some());
assert_eq!(size(doc(&s)), size(&source_doc));
// The Dots symbol brings its pattern and swatch.
run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"}));
assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some());
// Placed again, Badge is the one already added.
let count = doc(&s).symbols.len();
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"}));
assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none());
// The active document's own symbol, by its uid: placed, nothing added.
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
run(&mut s, "symbol.new", json!({"name": "Star"}));
let own = s.doc().unwrap().uid;
let before = undo_len(&s);
let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70}));
assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()]));
// Errors change nothing.
let before = (undo_len(&s), doc(&s).clone());
for p in [
json!({"sourceDocument": source, "name": "Nope"}),
json!({"sourceDocument": source}),
json!({"name": "Star"}),
json!({"sourceDocument": -1, "name": "Star"}),
json!({"sourceDocument": "1", "name": "Star"}),
json!({"sourceDocument": source, "name": "Star", "x": "10"}),
json!({"sourceDocument": u64::MAX, "name": "Star"}),
] {
assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}");
assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}");
}
// The source document is left as it was, and once it is closed its symbols are gone with it.
assert!(s.set_active(0));
assert_eq!(*s.doc().unwrap().doc, *source_doc);
run(&mut s, "file.close", json!({"index": 0}));
let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err();
assert!(e.to_string().contains("no longer open"), "{e}");
}
+113 -1
View File
@@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() {
let mut s = session();
for active in [false, true] {
select(&mut s, if active { "spiral" } else { "selection" });
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap();
// A decay past the 99.99 % a spiral draws is refused, and nothing changes.
let before = s.tool_options_of("spiral");
let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}}));
assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string()));
assert_eq!(s.tool_options_of("spiral"), before);
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap();
assert_eq!(options["decay"], json!(99.99));
assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99));
assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99));
@@ -387,3 +392,110 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() {
assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}");
}
}
/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an
/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also
/// when another option given with it is good, and nothing is saved or recorded for undo.
#[test]
fn bad_option_values_are_errors_that_set_nothing() {
let mut s = session();
select(&mut s, "smooth");
let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len());
let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100";
for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] {
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}");
}
let cases = [
(json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"),
(json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"),
(json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"),
(json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"),
(json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"),
(json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"),
(
json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}),
"tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`",
),
(json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"),
(json!({"values": [1]}), "`values` must be an object"),
(json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"),
(json!({"key": "fidelity"}), "`value` is missing for `fidelity`"),
];
for (p, want) in cases {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]);
assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo));
// A good value after the errors is set and read back.
assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0));
}
/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing.
#[test]
fn an_empty_set_option_reads_and_saves_nothing() {
let mut s = session();
select(&mut s, "smooth");
let saved = s.prefs.tool_settings.clone();
assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options());
assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare"));
// No params (null) read too; params that are not an object are an error.
assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options());
for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] {
assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}"));
}
assert_eq!(s.prefs.tool_settings, saved);
}
/// A Place queue with a malformed entry is an error, and the queue held stays as it was.
#[test]
fn a_malformed_place_queue_is_an_error() {
let mut s = session();
select(&mut s, "place");
let entry = json!({"params": {"svg": "<svg/>"}, "name": "a", "width": 10, "height": 10});
s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap();
let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10});
let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err();
assert!(e.starts_with("tool `place`: `queue` must be"), "{e}");
assert_eq!(s.tool_options()["names"], json!(["a"]));
assert_eq!(
s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(),
"tool `place`: `current` must be the index of a queued file, from 0 to 0"
);
}
/// A `current` given with a new Place queue picks among the files of that queue.
#[test]
fn a_place_queue_and_its_current_file_set_together() {
let mut s = session();
select(&mut s, "place");
let entry = |name: &str| json!({"params": {"svg": "<svg/>"}, "name": name, "width": 10, "height": 10});
let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]});
let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap();
assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2)));
let short = json!({"entries": [entry("d")]});
let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err();
assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0");
assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held");
}
/// A value given with a parametric shape's new `kind` is checked against that kind's range and
/// set on it, whether the tool is chosen or not.
#[test]
fn a_parametric_shape_kind_and_its_values_set_together() {
for active in [false, true] {
let mut s = session();
if active {
select(&mut s, "parametricShape");
}
let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values}));
set(&mut s, json!({"kind": "polygon"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}");
set(&mut s, json!({"kind": "ring"})).unwrap();
let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap();
assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}");
let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err();
assert!(e.contains("`a`"), "{e}");
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
}
}
+118
View File
@@ -167,6 +167,124 @@ fn adjust_adjoining_scales_the_neighbours() {
assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]);
}
/// A line with a discontinuous point in the middle: 1× before it, 2× after it.
fn pair_session(points: serde_json::Value) -> (Session, NodeId) {
let (mut s, id) = line_session();
s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap();
s.doc_mut().unwrap().mark_saved();
(s, id)
}
#[test]
fn paired_set_edits_both_halves_in_one_step() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20});
assert_eq!(set(&mut s, p.clone()), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let after = s.doc().unwrap().doc.clone();
// The same widths again change nothing and record no undo step.
set(&mut s, p);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
}
#[test]
fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
// The incoming half doubles and the outgoing half halves: the start doubles, the end halves.
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
// A discontinuous point at the start has only a point after it to adjust.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]);
}
/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though
/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts.
#[test]
fn paired_set_adjusts_the_point_after_a_chained_pair() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]]));
set(
&mut s,
json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}),
);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]);
}
#[test]
fn single_width_only_leaves_one_continuous_point() {
for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single});
assert_eq!(set(&mut s, p), 1);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
}
// With Adjust Adjoining, each neighbor follows the change of the half beside it.
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]]));
let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true});
set(&mut s, p);
assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]);
}
#[test]
fn paired_set_refuses_what_is_not_one_discontinuous_point() {
let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]]));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let pair = |extra: serde_json::Value| {
let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5});
for (k, v) in extra.as_object().unwrap() {
if v.is_null() {
p.as_object_mut().unwrap().remove(k);
} else {
p[k] = v.clone();
}
}
p
};
for p in [
pair(json!({"index": 1, "t": 0.25, "outIndex": 2})),
pair(json!({"outIndex": 4})),
pair(json!({"index": 3, "outIndex": 2})),
pair(json!({"outIndex": 99})),
pair(json!({"outIndex": "3"})),
pair(json!({"outIndex": -1})),
pair(json!({"t": 0.6})),
pair(json!({"index": 4, "t": 0.75, "outIndex": 5})),
pair(json!({"index": null})),
pair(json!({"outLeft": null})),
pair(json!({"outRight": -1})),
pair(json!({"outLeft": 1.0e6})),
pair(json!({"single": "both"})),
pair(json!({"single": true})),
pair(json!({"outIndex": null})),
pair(json!({"outIndex": null, "outLeft": null})),
json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}),
] {
assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}");
assert_eq!(s.doc().unwrap().doc, before, "{p}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
}
#[test]
fn flipping_along_swaps_the_sides_of_a_discontinuous_point() {
let (mut s, id) = line_session();
+18
View File
@@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() {
assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0));
}
/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the
/// tool's reason in the status bar and leaves the stroke and the undo history as they were.
#[test]
fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() {
let (mut s, c, _) = compound();
s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap();
let steps = s.journal.len();
let v = ViewInfo::default();
s.select_tool("width", v).unwrap();
for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] {
let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap();
let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE));
assert_eq!(said, reason, "{kind:?}: {ui:?}");
}
assert_eq!(profile(&s, c), None);
assert_eq!(s.journal.len(), steps, "no command ran");
}
#[test]
fn width_point_commands_given_a_member_edit_the_compound() {
let (mut s, c, members) = compound();
+45 -15
View File
@@ -1321,7 +1321,14 @@ impl Session {
/// The options of tool `id`: the active tool's, or those it would have if chosen now.
pub fn tool_options_of(&self, id: &str) -> Value {
if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() }
if id == self.tool.id() {
self.tool.options()
} else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) {
// The tool that lent a selection tool for a Cmd-drag holds its options while it waits.
lender.options()
} else {
self.make_tool(id).options()
}
}
/// Set options of tool `id` (default: the active tool). Another tool's persistent options are
@@ -1333,14 +1340,22 @@ impl Session {
self.note_place_queue_roots();
}
let active = id.is_none_or(|id| id == self.tool.id());
self.tool_set_since_reset |= active;
// The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again
// when the drag ends.
let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id));
self.tool_set_since_reset |= active || lender;
// The Place queue and a parametric shape's kind are set first: setting the queue starts
// again at its first file, and a `current` given with it is an index into it; setting the
// kind puts the shape's other numbers back to that kind's, and those given with it are its.
let first = |k: &str| k == "queue" || k == "kind";
let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k)));
let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default()));
let t = other.as_deref_mut().unwrap_or(self.tool.as_mut());
for (k, v) in values {
for (k, v) in ordered() {
t.set_option(k, v);
}
Self::store_tool_settings(&mut self.prefs, t);
let out = t.options();
let mut out = t.options();
if let Some(other) = other {
// The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when
// it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's
@@ -1348,11 +1363,14 @@ impl Session {
// active tool.
if let Some(lender) = self.lender.as_deref_mut() {
if lender.id() == other.id() {
for (k, v) in values {
for (k, v) in ordered() {
lender.set_option(k, v);
}
}
Self::restore_tool_settings(&self.prefs, lender);
if lender.id() == other.id() {
out = lender.options();
}
}
// Only the stores it shares with the tool set: the active tool's own options stay as they
// are, also in the middle of a drag that Escape can cancel.
@@ -1364,21 +1382,28 @@ impl Session {
/// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the
/// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default:
/// the active tool) → its options.
/// the tool active when the call arrives, named before the edit in progress is finished) → its
/// options. With no option given, the options are read and nothing is set. Parameters that are
/// not an object are an error; none (null) read the options. Every option given is checked
/// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong
/// type or a number out of range is an error that sets none of them.
pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result<Value, String> {
let tool = p.get("tool").and_then(Value::as_str);
let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?;
if let Some(t) = tool
&& vectorcraft_tools::tool_info(t).is_none()
{
return Err(format!("unknown tool `{t}`"));
}
let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default();
if let Some(k) = p.get("key").and_then(Value::as_str) {
values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null));
// The tool is named before the edit in progress is finished: finishing it can make a held
// Cmd press, which lends a selection tool and makes that the active tool.
let id = tool.unwrap_or(self.tool.id());
let active = id == self.tool.id();
if values.is_empty() {
return Ok(self.tool_options_of(id));
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
vectorcraft_tools::builder::check_builder_options(id, &values)?;
if id == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
let max = self.doc().ok().and_then(|st| {
@@ -1397,7 +1422,7 @@ impl Session {
crate::file_access::check_read(path)?;
}
}
if tool.unwrap_or(self.tool_id()) == "dimension" {
if id == "dimension" {
if let Some(style) = values.get("style") {
vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?;
}
@@ -1407,11 +1432,16 @@ impl Session {
return Err("Unknown dimension mode".into());
}
}
if active {
vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?;
} else {
vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?;
}
// The active tool's merge being computed is applied with the options it was started with.
if tool.is_none_or(|t| t == self.tool.id()) {
if active {
self.finish_tool_edit_later().map_err(|e| e.to_string())?;
}
Ok(self.set_tool_options(tool, &values))
Ok(self.set_tool_options(Some(id), &values))
}
/// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]):
+30
View File
@@ -1273,6 +1273,36 @@ fn polygon_properties_junk() {
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line
/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound.
#[test]
fn line_properties_junk() {
let mut cases: Vec<Value> = vec![json!({"lineLength": 4.0e6, "lineAngle": 45})];
for key in ["lineLength", "lineAngle"] {
for v in junk_values() {
cases.push(json!({ key: v }));
}
}
let mut failures = vec![];
for (a, b) in [((10.0, 20.0), (110.0, 70.0)), ((50.0, 50.0), (50.0, 50.0)), ((-4.0e6, 4.0e6), (4.0e6, -4.0e6))] {
for p in &cases {
let mut s = Fixture::Multi.session();
let Ok(_) = no_panic(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1}))) else {
continue;
};
match catch_quiet(|| no_panic(s.execute("object.setLiveShape", p))) {
Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{a:?} {b:?}]: {m}")),
Ok(_) => {
if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) {
failures.push(format!("object.setLiveShape {p} [{a:?} {b:?}]: {e}"));
}
}
}
}
}
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
/// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the
/// first junk values, a string under a file or folder key replaced by a location inside `path`'s
/// folder.
+9 -3
View File
@@ -1971,9 +1971,15 @@ fn dimension_colours_follow_the_document_colour_model() {
let black = colours(&s, id);
assert!(!black.is_empty() && black.iter().all(|c| *c == vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)), "{black:?}");
let pdf = pdf_content(&run(&mut s, "document.exportPdf", json!({"preset":"PDF/X-4:2010"})));
// PDF/X-4 paints in the output intent's CMYK space: `/c0 CS 0 0 0 1 SCN` strokes, `scn` fills.
let operands = |op: &str| pdf.match_indices(op).map(|(i, _)| pdf[i.saturating_sub(7)..i].to_string()).collect::<Vec<_>>();
let (strokes, fills) = (operands(" SCN"), operands(" scn"));
// PDF/X-4 writes CMYK in the output intent's profile as DeviceCMYK: `0 0 0 1 K` strokes, `k` fills.
let words: Vec<&str> = pdf.split_whitespace().collect();
let operands = |op: &str| {
(4..words.len())
.filter(|&i| words[i] == op && words[i - 4..i].iter().all(|w| w.parse::<f32>().is_ok()))
.map(|i| words[i - 4..i].join(" "))
.collect::<Vec<_>>()
};
let (strokes, fills) = (operands("K"), operands("k"));
assert!(!strokes.is_empty() && !fills.is_empty(), "{pdf}");
assert!(strokes.iter().chain(&fills).all(|v| v == "0 0 0 1"), "K-only colours: {strokes:?} {fills:?}");
run(&mut s, "dimension.update", json!({"ids":[id],"options":{"lineColor":[255,0,0]}}));
+244
View File
@@ -0,0 +1,244 @@
//! Path fill hit testing follows the visible paint stack while transparent paint remains selectable.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
use vectorcraft_render::{RenderOptions, Renderer};
fn fill(paint: Paint) -> FillLayer {
FillLayer::new(paint)
}
fn rectangle(fills: Vec<FillLayer>, stroke: bool) -> Document {
let mut doc = Document::new(128.0, 128.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let mut appearance = Appearance::default();
appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill));
if stroke {
appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)));
}
let path = shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0));
doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap();
doc
}
fn compound(fills: Vec<FillLayer>) -> Document {
let mut doc = Document::new(128.0, 128.0);
let layer = doc.layers[0].id;
let outer_id = doc.alloc_id();
let inner_id = doc.alloc_id();
let compound_id = doc.alloc_id();
let children = vec![
Arc::new(Node::path(outer_id, shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)), Appearance::default())),
Arc::new(Node::path(inner_id, shapes::rectangle(Rect::new(50.0, 40.0, 70.0, 80.0)), Appearance::default())),
];
let mut appearance = Appearance::default();
appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill));
appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)));
let mut node = Node::new(compound_id, NodeKind::Compound { children, rule: FillRule::EvenOdd });
node.appearance = appearance.into();
doc.insert(Some(layer), usize::MAX, node).unwrap();
doc
}
#[test]
fn hit_uses_the_visible_fill_stack() {
let black = || fill(Paint::solid(Color::BLACK));
let mut hidden = black();
hidden.visible = false;
let mut transparent = black();
transparent.opacity = 0.0;
let mut hidden_lower = black();
hidden_lower.visible = false;
let cases = vec![
("visible black fill", rectangle(vec![black()], true)),
("lower black fill under a top None fill", rectangle(vec![black(), fill(Paint::None)], true)),
("lower black fill under a top None fill without stroke", rectangle(vec![black(), fill(Paint::None)], false)),
("only hidden non-None fill", rectangle(vec![hidden], true)),
("basic Fill None", rectangle(vec![fill(Paint::None)], true)),
("hidden lower black and top None fills", rectangle(vec![hidden_lower, fill(Paint::None)], true)),
("visible fill at zero opacity", rectangle(vec![transparent], true)),
];
let mut observed = Vec::new();
for (name, doc) in cases {
let image = Renderer::new().render(
&doc,
128,
128,
Affine::IDENTITY,
&RenderOptions { background: None, artboards: false, ..RenderOptions::default() },
);
let center_alpha = image.pixel(60, 60)[3];
let edge_alpha = image.pixel(100, 60)[3];
let center = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind);
let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind);
let outline = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind);
let path_only = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind);
observed.push((name, center_alpha, edge_alpha, center, edge, outline, path_only));
}
let expected = vec![
("visible black fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None),
("lower black fill under a top None fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None),
("lower black fill under a top None fill without stroke", 255, 0, Some(HitKind::Fill), Some(HitKind::Outline), None, None),
("only hidden non-None fill", 0, 255, None, Some(HitKind::Stroke), None, None),
("basic Fill None", 0, 255, None, Some(HitKind::Stroke), None, None),
("hidden lower black and top None fills", 0, 255, None, Some(HitKind::Stroke), None, None),
("visible fill at zero opacity", 0, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None),
];
assert_eq!(observed, expected, "render and hit-test observations by fill-stack case");
}
#[test]
fn compound_hit_uses_visible_fill_stack() {
let black = || fill(Paint::solid(Color::BLACK));
let mut hidden = black();
hidden.visible = false;
let mut transparent = black();
transparent.opacity = 0.0;
let cases = vec![
("visible black fill", compound(vec![black()])),
("lower black fill under a top None fill", compound(vec![black(), fill(Paint::None)])),
("only hidden non-None fill", compound(vec![hidden])),
("basic Fill None", compound(vec![fill(Paint::None)])),
("visible fill at zero opacity", compound(vec![transparent])),
];
let mut observed = Vec::new();
for (name, doc) in cases {
let image = Renderer::new().render(
&doc,
128,
128,
Affine::IDENTITY,
&RenderOptions { background: None, artboards: false, ..RenderOptions::default() },
);
let ring_alpha = image.pixel(30, 60)[3];
let hole_alpha = image.pixel(60, 60)[3];
let edge_alpha = image.pixel(100, 60)[3];
let ring = hit_test(&doc, Point::new(30.0, 60.0), HitOptions::default()).map(|hit| hit.kind);
let hole = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind);
let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind);
let outline = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind);
let path_only = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind);
observed.push((name, ring_alpha, hole_alpha, edge_alpha, ring, hole, edge, outline, path_only));
}
let expected = vec![
("visible black fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None),
("lower black fill under a top None fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None),
("only hidden non-None fill", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None),
("basic Fill None", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None),
("visible fill at zero opacity", 0, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None),
];
assert_eq!(observed, expected, "render and hit-test observations by Compound fill-stack case");
}
#[test]
fn hit_respects_open_stroke_caps_with_hidden_fill() {
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{BezPath, PathData};
let mut observed = Vec::new();
let mut expected = Vec::new();
// Round and Square are legitimate controls before the Butt regression.
for (cap, endpoint_pixel, endpoint_hit) in [
(LineCap::Round, [0, 0, 0, 255], Some(HitKind::Stroke)),
(LineCap::Square, [0, 0, 0, 255], Some(HitKind::Stroke)),
(LineCap::Butt, [255, 255, 255, 255], None),
] {
for join in [LineJoin::Miter, LineJoin::Round] {
let mut hidden = fill(Paint::solid(Color::BLACK));
hidden.visible = false;
for (name, fills) in [
("hidden painted fill", vec![hidden]),
("absent fill", vec![]),
("explicit Fill None", vec![fill(Paint::None)]),
("visible fill on a zero-area line", vec![fill(Paint::solid(Color::BLACK))]),
] {
let mut doc = Document::new(160.0, 96.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let mut appearance = Appearance::default();
appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill));
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0);
stroke.cap = cap;
stroke.join = join;
appearance.items.push(AppearanceItem::Stroke(stroke));
let path = PathData::from_bezpath(&BezPath::from_svg("M24 48 L124 48").unwrap());
doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap();
let mut renderer = Renderer::new();
renderer.threads = 0;
let image = renderer.render(
&doc,
160,
96,
Affine::IDENTITY,
&RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() },
);
let options = HitOptions { tol: 0.5, ..HitOptions::default() };
let end = hit_test(&doc, Point::new(20.0, 48.0), options).map(|hit| hit.kind);
let body = hit_test(&doc, Point::new(60.0, 48.0), options).map(|hit| hit.kind);
assert_eq!(image.pixel(60, 48), [0, 0, 0, 255], "INPUT: {cap:?}/{join:?}/{name} stroke body must draw");
assert_eq!(body, Some(HitKind::Stroke), "INPUT: {cap:?}/{join:?}/{name} stroke body must hit");
observed.push((cap, join, name, image.pixel(20, 48), end, image.pixel(60, 48), body));
expected.push((cap, join, name, endpoint_pixel, endpoint_hit, [0, 0, 0, 255], Some(HitKind::Stroke)));
}
}
}
assert_eq!(observed, expected, "visible stroke caps and hit testing must agree, including hidden-fill paths");
}
#[test]
fn hit_respects_hidden_fill_stroke_joins() {
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{BezPath, PathData};
let mut observed = Vec::new();
let mut expected = Vec::new();
for (join, joint_painted, joint_hit) in
[(LineJoin::Round, true, Some(HitKind::Stroke)), (LineJoin::Miter, true, Some(HitKind::Stroke)), (LineJoin::Bevel, false, None)]
{
let mut doc = Document::new(160.0, 96.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let mut hidden = fill(Paint::solid(Color::BLACK));
hidden.visible = false;
let mut appearance = Appearance::default();
appearance.items.push(AppearanceItem::Fill(hidden));
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0);
stroke.cap = LineCap::Round;
stroke.join = join;
appearance.items.push(AppearanceItem::Stroke(stroke));
let path = PathData::from_bezpath(&BezPath::from_svg("M32 64 L96 64 L96 24").unwrap());
doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap();
let mut renderer = Renderer::new();
renderer.threads = 0;
let image = renderer.render(
&doc,
160,
96,
Affine::IDENTITY,
&RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() },
);
let options = HitOptions { tol: 0.5, ..HitOptions::default() };
let joint = hit_test(&doc, Point::new(99.0, 67.0), options).map(|hit| hit.kind);
let body = hit_test(&doc, Point::new(60.0, 64.0), options).map(|hit| hit.kind);
assert_eq!(image.pixel(60, 64), [0, 0, 0, 255], "INPUT: {join:?} stroke body must draw");
assert_eq!(body, Some(HitKind::Stroke), "INPUT: {join:?} stroke body must hit");
// Round's corner pixel can be antialiased; only its visible paint is required.
observed.push((join, image.pixel(99, 67) != [255, 255, 255, 255], joint));
expected.push((join, joint_painted, joint_hit));
}
assert_eq!(observed, expected, "hidden-fill stroke joins must match actual CPU paint at the outer joint");
}
+539
View File
@@ -4197,6 +4197,165 @@ fn images_that_cant_be_decoded_are_mid_gray_boxes() {
assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5))));
}
/// A `w` × `h` RGB image whose pixels follow from `seed`, no two of its pixels gray.
fn seeded_png(seed: u32, (w, h): (u32, u32)) -> Vec<u8> {
let px = |x: u32, y: u32| {
let v = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663) ^ seed.wrapping_mul(83_492_791)).to_le_bytes();
image::Rgb([v[0], v[1] | 1, v[2] & 0xfe])
};
png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, px)))
}
/// A document placing `blobs` in turn on one layer, each `times` times: the first, the second and
/// so on, then the first again. Each blob is kept under `keys`' key at its index.
fn images_in_turn(blobs: &[ImageBlob], keys: &[&str], times: usize) -> Document {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
for (blob, key) in blobs.iter().zip(keys) {
doc.images.insert((*key).to_string(), blob.clone());
}
for i in 0..times * blobs.len() {
let key = keys[i % blobs.len()].to_string();
let xf = Affine::translate((f64::from(u32::try_from(i).unwrap()), 10.0)) * Affine::scale(2.0);
let im = ImageObject { key, width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None };
let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
doc.insert(Some(layer), usize::MAX, node).unwrap();
}
doc
}
/// `doc` written keeping the pixels of each image read (`last_only` false) or of the image read
/// last alone, and how many times an image's pixels were read.
fn export_reading(doc: &Document, last_only: bool) -> (AiEditingOutput, usize) {
writer::LAST_SAMPLES_ONLY.with(|l| l.set(last_only));
writer::SAMPLE_READS.with(|n| n.set(0));
let out = export_ai_editing(doc, &opts());
writer::LAST_SAMPLES_ONLY.with(|l| l.set(false));
(out.unwrap(), writer::SAMPLE_READS.with(std::cell::Cell::get))
}
/// `doc` written both ways ([`export_reading`]), the files and warnings compared whole, and the
/// reads of each way.
fn reads_for_the_same_file(doc: &Document) -> (usize, usize) {
let (kept, kept_reads) = export_reading(doc, false);
let (last, last_reads) = export_reading(doc, true);
assert!(kept.program == last.program, "the files differ");
assert_eq!(kept.header, last.header);
assert_eq!(kept.warnings, last.warnings);
(kept_reads, last_reads)
}
/// Two images placed one after the other 25 times each are each read once in a save, and the file
/// is the same as when only the image read last is kept.
#[test]
fn images_placed_in_turn_are_read_once_a_save() {
// GUARDS: each image was read again whenever the other was placed between its copies.
let blobs = [ImageBlob::png(seeded_png(1, (4, 4))), ImageBlob::png(seeded_png(2, (4, 4)))];
let doc = images_in_turn(&blobs, &["a", "b"], 25);
assert_eq!(reads_for_the_same_file(&doc), (2, 50));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 50);
}
/// A document of one image placed many times reads it once, and one without images reads none.
#[test]
fn one_image_is_read_once_and_no_image_never() {
let doc = images_in_turn(&[ImageBlob::png(seeded_png(3, (4, 4)))], &["a"], 10);
assert_eq!(reads_for_the_same_file(&doc), (1, 1));
assert_eq!(reads_for_the_same_file(&Document::new(200.0, 100.0)), (0, 0));
}
/// An image that can't be read, placed between copies of another, is read once too, and each copy
/// is still its gray outline with the same warning.
#[test]
fn an_image_that_cant_be_read_is_read_once_a_save() {
// GUARDS: an image that can't be read was read again whenever another image came between.
let blobs = [ImageBlob::png(b"not an image".to_vec()), ImageBlob::png(seeded_png(4, (4, 4)))];
let doc = images_in_turn(&blobs, &["bad", "good"], 3);
assert_eq!(reads_for_the_same_file(&doc), (2, 6));
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(out.warnings, [writer::IMAGES]);
assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 3);
}
/// The same data under two MIME types is two images: each is read once, apart from the other.
#[test]
fn the_same_data_of_another_type_is_read_apart() {
let png = ImageBlob::png(seeded_png(5, (4, 4)));
let other = ImageBlob { mime: "image/x-other".into(), ..png.clone() };
assert!(Arc::ptr_eq(&png.bytes, &other.bytes));
let doc = images_in_turn(&[png, other], &["png", "other"], 3);
assert_eq!(reads_for_the_same_file(&doc), (2, 6));
}
/// Past the limits on the samples kept (bytes and images), an image is kept beside them in place
/// of the one before it, and the others are read again where they come: what is kept stays within
/// both limits, and the file is the same.
#[test]
fn images_past_the_limits_are_read_again_and_written_the_same() {
// Images of 48, 75 and 108 bytes of samples, then two of 48: 123 bytes and two images fit.
let sizes = [(4, 4), (5, 5), (6, 6), (4, 4), (4, 4)];
let blobs: Vec<_> = (0u32..).zip(sizes).map(|(i, s)| ImageBlob::png(seeded_png(10 + i, s))).collect();
let doc = images_in_turn(&blobs, &["a", "b", "c", "d", "e"], 3);
for (limits, kept_most, reads) in [((130, 8), (123, 2), 2 + 3 * 3), ((10_000, 3), (48 + 75 + 108, 3), 3 + 2 * 3)] {
writer::SAMPLE_LIMITS.with(|l| l.set(limits));
writer::SAMPLES_KEPT.with(|k| k.set((0, 0, false)));
let (kept_reads, last_reads) = reads_for_the_same_file(&doc);
let (bytes, images, beside) = writer::SAMPLES_KEPT.with(std::cell::Cell::get);
writer::SAMPLE_LIMITS.with(|l| l.set((256 << 20, 256)));
assert!(bytes <= limits.0 && images <= limits.1, "{limits:?}: kept {bytes} bytes of {images} images");
assert_eq!((bytes, images, beside), (kept_most.0, kept_most.1, true), "{limits:?}");
assert_eq!((kept_reads, last_reads), (reads, 15), "{limits:?}");
}
}
/// 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 two 2048 × 2048 images placed one after the other 25 times each, keeping the
/// pixels of each image read and of the image read last alone: the median of 7 runs of each,
/// alternating, with the files compared. Run with
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture images_placed_in_turn_are_written_quickly`.
#[test]
#[ignore = "timing"]
fn images_placed_in_turn_are_written_quickly() {
let blobs = [ImageBlob::png(seeded_png(1, (2048, 2048))), ImageBlob::png(seeded_png(2, (2048, 2048)))];
let doc = images_in_turn(&blobs, &["a", "b"], 25);
let mut times = [vec![], vec![]];
let mut files: [Option<Vec<u8>>; 2] = [None, None];
let mut reads = [0, 0];
let mut how = "";
for _ in 0..7 {
for (k, last_only) in [false, true].into_iter().enumerate() {
let (start, h) = thread_time();
let (out, n) = export_reading(&doc, last_only);
times[k].push(thread_time().0.saturating_sub(start));
how = h;
reads[k] = n;
files[k].get_or_insert(out.program);
}
}
assert!(files[0] == files[1], "the files differ");
assert_eq!(reads, [2, 50]);
for t in &mut times {
t.sort();
}
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
println!("50 placements of two 2048 x 2048 images, median of 7 runs ({how}):");
println!("| pixels kept | images read | median (ms) | runs (ms) |");
println!("|---|---:|---:|---|");
for (k, label) in ["each image read", "the image read last"].into_iter().enumerate() {
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.0}", ms(*d))).collect();
println!("| {label} | {} | {:.0} | {} |", reads[k], ms(times[k][3]), runs.join(", "));
}
}
#[test]
fn sixteen_bit_images_are_written_at_eight_bits() {
let mut doc = Document::new(200.0, 100.0);
@@ -7181,6 +7340,166 @@ fn art_styles_are_written_in_their_forms() {
assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}");
}
/// A document with `k` of each object a save checks a style on, on rows 20 pt apart: objects linked
/// to a new document's graphic style and to one of the document's own, objects with the same drop
/// shadow, two objects with different gradients under a drop shadow on the same outline, and paths
/// with a Calligraphic brush and a drop shadow.
fn checked_styles_document(k: usize) -> Document {
let mut doc = Document::new(400.0, 20.0 * k as f64 + 20.0);
vectorcraft_brush::store(&mut doc, &brush_library());
let lit_ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::rgb(0.2, 0.5, 0.9)), solid(Color::BLACK), 1.0) };
let mut lit = vectorcraft_doc::GraphicStyle::new("Lit", lit_ap);
lit.id = 40;
doc.graphic_styles.push(lit);
let ramp = |c: Color| {
let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, c)];
Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops, ..Gradient::default() })))
};
for i in 0..k {
let y = 10.0 + 20.0 * i as f64;
for (x, name) in [(10.0, "Sunshine"), (60.0, "Lit")] {
let g = doc.graphic_style(name).unwrap().clone();
let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned();
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 15.0)), ap);
n.extras_mut().graphic_style = Some(g.id);
put(&mut doc, n);
}
let n = styled_rect(&mut doc, "Shadowed", Rect::new(110.0, y, 150.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![drop_shadow()]);
put(&mut doc, n);
for c in [Color::BLACK, Color::rgb(0.9, 0.2, 0.1)] {
let n = styled_rect(&mut doc, "Graded", Rect::new(160.0, y, 200.0, y + 15.0), ramp(c), Paint::None, vec![drop_shadow()]);
put(&mut doc, n);
}
let stroke = Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0);
let mut line = Node::path(doc.alloc_id(), shapes::line((210.0, y).into(), (380.0, y + 10.0).into()), stroke);
line.appearance.stroke_mut().unwrap().brush = Some("Nib".into());
line.appearance.effects = vec![drop_shadow()];
put(&mut doc, line);
}
doc
}
/// A save parses each style text once, however many objects it checks with it: the panel's styles,
/// objects linked to them, objects with the same style of their own and brushed paths. Each object
/// is still checked: every linked object keeps its link, each graded object reads back with its own
/// gradient, and each brushed path with its brush.
#[test]
fn a_save_parses_each_style_text_once() {
let parses = |doc: &Document| {
crate::import::ART_STYLE_PARSES.set(0);
let out = export_ai_editing(doc, &opts()).unwrap();
(crate::import::ART_STYLE_PARSES.get(), String::from_utf8(out.program).unwrap().replace("\r\n", "\n"))
};
let (one, _) = parses(&checked_styles_document(1));
let doc = checked_styles_document(4);
let (four, p) = parses(&doc);
assert!(one > 0);
assert_eq!(four, one, "parses with one of each object and with four");
for linked in ["1 (Sunshine) XW\n", "1 (Lit) XW\n"] {
assert_eq!(p.matches(linked).count(), 4, "{linked}");
}
let back = read_back(&doc);
let kids = back.layers[0].children().unwrap();
let paints: Vec<&Paint> =
kids.iter().filter(|n| n.name.as_deref() == Some("Graded")).filter_map(|n| n.appearance.fill().map(|f| &f.paint)).collect();
let graded: Vec<&Paint> = doc.layers[0]
.children()
.unwrap()
.iter()
.filter(|n| n.name.as_deref() == Some("Graded"))
.map(|n| &n.appearance.fill().unwrap().paint)
.collect();
assert_eq!(paints.len(), 8);
for (got, want) in paints.iter().zip(&graded) {
let (Paint::Gradient(got), Paint::Gradient(want)) = (got, want) else { panic!("a gradient fill: {got:?}") };
assert_eq!(got.gradient.stops, want.gradient.stops);
}
let brushed: Vec<&Arc<Node>> = kids.iter().filter(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref()) == Some("Nib")).collect();
assert_eq!(brushed.len(), 4);
assert!(brushed.iter().all(|n| n.appearance.effects.len() == 1 && matches!(n.kind, NodeKind::Path { .. })));
}
/// A save that keeps each style text's parse writes the same program, header, warnings and private
/// data as one that parses the text again at every check.
#[test]
fn a_save_writes_the_same_with_each_style_text_parsed_once() {
let save = |doc: &Document, reparse: bool| {
writer::REPARSE.set(reparse);
let out = export_ai_editing(doc, &opts()).unwrap();
let private = private_data(doc, &opts()).unwrap();
writer::REPARSE.set(false);
(out.program, out.header, out.warnings, private.0.data, private.1)
};
for doc in [styles_document(), checked_styles_document(4), brushes_document()] {
let (once, again) = (save(&doc, false), save(&doc, true));
assert!(once == again, "{}", String::from_utf8_lossy(&once.0));
}
}
/// The CPU time of saving a document with 40 graphic styles, 20,000 rectangles linked to them in
/// turn and 5,000 paths with an Outer Glow of their own in 20 settings, with each style text's parse
/// kept and with the text parsed again at every check: the median of 7 runs of each, alternating.
/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture style_parse_time`.
#[test]
#[ignore = "timing; run by hand"]
fn style_parse_time() {
let mut doc = Document::new(2000.0, 2000.0);
let mut ids = vec![];
for i in 0..40u32 {
let shade = i as f32 / 40.0;
let mut ap = Appearance::basic(solid(Color::rgb(shade, 0.4, 1.0 - shade)), solid(Color::BLACK), 1.0 + f64::from(i % 4));
let round = fx("stylize.roundCorners", serde_json::json!({"radius": 2.0 + f64::from(i % 5)}));
ap.effects = vec![fx("stylize.dropShadow", serde_json::json!({"x": f64::from(i % 7), "y": 4.0})), round];
let mut g = vectorcraft_doc::GraphicStyle::new(format!("Style {i}"), ap);
g.id = 100 + i;
ids.push(g.id);
doc.graphic_styles.push(g);
}
for i in 0..20_000usize {
let g = doc.graphic_style_by_id(ids[i % ids.len()]).unwrap().clone();
let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned();
let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0);
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), ap);
n.extras_mut().graphic_style = Some(g.id);
put(&mut doc, n);
}
for i in 0..5_000usize {
let glow = fx("stylize.outerGlow", serde_json::json!({"blur": 1.0 + (i % 20) as f64}));
let (x, y) = ((i % 100) as f64 * 20.0, 1000.0 + (i / 100) as f64 * 20.0);
let n = styled_rect(&mut doc, "Glow", Rect::new(x, y, x + 15.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![glow]);
put(&mut doc, n);
}
// The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock.
let start = std::time::Instant::now();
let cpu = || {
std::fs::read_to_string("/proc/thread-self/schedstat")
.ok()
.and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::<u64>().ok()))
.unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX))
};
let mut times: [Vec<u64>; 2] = [vec![], vec![]];
let mut parses = [0, 0];
let mut outputs: [Vec<u8>; 2] = [vec![], vec![]];
for _ in 0..7 {
for (k, reparse) in [(0, true), (1, false)] {
writer::REPARSE.set(reparse);
crate::import::ART_STYLE_PARSES.set(0);
let t = cpu();
let out = export_ai_editing(&doc, &opts()).unwrap();
times[k].push(cpu() - t);
parses[k] = crate::import::ART_STYLE_PARSES.get();
outputs[k] = out.program;
}
}
writer::REPARSE.set(false);
assert!(outputs[0] == outputs[1]);
for (k, label) in [(0, "parsed at every check"), (1, "parsed once")] {
times[k].sort_unstable();
let ms: Vec<String> = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect();
println!("{label}: median {:.1} ms CPU, {} parses, runs {}", times[k][3] as f64 / 1e6, parses[k], ms.join(" "));
}
}
/// Objects whose appearance the reader wouldn't read with their style are written as their
/// drawn look, with the warnings they were written with before; graphic styles it wouldn't read
/// are left out with a warning; and a document without effects or styles of its own has no art
@@ -10255,6 +10574,40 @@ fn brush_art_of_a_straight_line_comes_back_as_the_line() {
}
}
/// A Scatter brush's art is written turned over into its section (y up), so the side that is down the
/// page in the brush's copies is up in the section: a triangle with its point down comes out with
/// its point above its base, and comes back with its point down.
#[test]
fn a_scatter_brushs_art_is_written_turned_over() {
use vectorcraft_brush::{Brush, BrushKind, Scatter};
use vectorcraft_geom::{Point, SubPath};
let point_down = PathData { subpaths: vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(20.0, 10.0)], true)] };
let art = Node::path(vectorcraft_doc::NodeId(1), point_down, Appearance::basic(black_fill(), Paint::None, 0.0));
let lib = vec![Brush { name: "Wedge".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }];
let mut doc = Document::new(300.0, 200.0);
vectorcraft_brush::store(&mut doc, &lib);
let text = program(&doc);
let start = text.find("%AI8_BeginBrushPattern").unwrap();
let end = start + text[start..].find("%AI8_EndBrushPattern").unwrap();
// The points of the frame and the triangle: the triangle's point is the one between the
// frame's left and right edges.
let points: Vec<(f64, f64)> = text[start..end]
.lines()
.filter_map(|l| l.strip_suffix(" m").or_else(|| l.strip_suffix(" L")))
.filter_map(|l| {
let mut n = l.split_whitespace().map(|v| v.parse::<f64>().ok());
Some((n.next()??, n.next()??))
})
.collect();
let (left, right) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, r), p| (l.min(p.0), r.max(p.0)));
let bottom = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let tip: Vec<f64> = points.iter().filter(|p| p.0 > left + 1e-3 && p.0 < right - 1e-3).map(|p| p.1).collect();
assert!(!tip.is_empty() && tip.iter().all(|y| (y - bottom - 10.0).abs() < 1e-3), "the point is 10 above the base in the section: {points:?}");
let back = vectorcraft_brush::library(&read_back(&doc));
let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[0].kind, &lib[0].kind) else { panic!("{back:?}") };
assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art);
}
/// Brush art of a path with several subpaths is written as a compound path, which the reader reads as
/// a compound path of one path for each subpath, and is weighed as the reader weighs that against the
/// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares,
@@ -11041,6 +11394,192 @@ fn variable_font_instances_name_their_design_space() {
);
}
/// Style 12 pt black in family `family` and style `style`, with the Variable Font settings `axes`.
fn font_style(family: &str, style: &str, axes: &[(&str, f64)]) -> vectorcraft_doc::CharStyle {
vectorcraft_doc::CharStyle {
font_family: family.into(),
font_style: style.into(),
font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(),
..style_of(12.0)
}
}
/// A document of `k` rows 30 pt apart, each with point type in three runs (Source Sans 3 Regular
/// and Bold, and the variable test font's Bold at a weight of 650), point type in four (Inter
/// Medium, the variable test font's Bold at 500 and at a weight that differs from 500 by less than
/// the font record's precision, and a family that isn't installed), and area type threaded through
/// two frames in Bold and the variable test font's Regular.
fn fonted_document(k: usize) -> Document {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
use vectorcraft_geom::Point;
use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font};
vectorcraft_text::FontDb::global().add_font(variable_font().unwrap());
let (regular, bold) = (style_of(12.0), font_style("Source Sans 3", "Bold", &[]));
let mut doc = Document::new(400.0, 30.0 * k as f64 + 30.0);
let layer = doc.layers[0].id;
for i in 0..k {
let y = 20.0 + 30.0 * i as f64;
let mut three = TextObject::point(Point::new(10.0, y), "", regular.clone());
three.runs = vec![
TextRun::new("One ", regular.clone()),
TextRun::new("two ", bold.clone()),
TextRun::new("three", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)])),
];
let mut four = TextObject::point(Point::new(100.0, y), "", regular.clone());
four.runs = vec![
TextRun::new("four ", font_style("Inter", "Medium", &[])),
TextRun::new("five ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.0)])),
TextRun::new("six ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.000_001)])),
TextRun::new("seven", font_style("No Such Family", "Bold", &[])),
];
let mut first = TextObject::point(Point::ZERO, "", bold.clone());
first.runs = vec![TextRun::new("eight nine ", bold.clone()), TextRun::new("ten", font_style(VARIABLE_FAMILY, "Regular", &[]))];
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(250.0, y - 10.0, 315.0, y + 10.0)) };
first.xf = Affine::IDENTITY;
let mut second = first.clone();
second.runs = vec![TextRun::new("", bold.clone())];
second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(325.0, y - 10.0, 390.0, y + 10.0)) };
let nodes = [text_node(&mut doc, three), text_node(&mut doc, four), text_node(&mut doc, first), text_node(&mut doc, second)];
doc.text_threads.push(vec![nodes[2].id, nodes[3].id]);
for n in nodes {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
}
doc
}
/// A save resolves the font of each style once, however many runs are set in it: as many fonts are
/// resolved (font records and checks that a font comes back) for one row of type as for four. Two
/// weights of a variable font that the font record writes as one number are one font written.
#[test]
fn a_save_resolves_each_font_once() {
// How many fonts a save of `doc` resolves, in a save during which the font database didn't change.
let resolves = |doc: &Document| {
let db = vectorcraft_text::FontDb::global();
for _ in 0..20 {
let before = db.generation();
writer::FONT_RESOLVES.set(0);
export_ai_editing(doc, &opts()).unwrap();
if db.generation() == before {
return writer::FONT_RESOLVES.get();
}
}
panic!("the font database changed during every save");
};
let one = resolves(&fonted_document(1));
let doc = fonted_document(4);
let four = resolves(&doc);
assert!(one > 0);
assert_eq!(four, one, "fonts resolved with one row of type and with four");
let td = text_document(&program(&doc));
// 650 × 65536 and 500 × 65536.
assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 42598400 ]").count(), 1, "{td}");
assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 32768000 ]").count(), 1, "{td}");
assert_eq!(td.matches("/CoolTypeFont").count(), 8, "seven fonts and the hidden characters' font: {td}");
}
/// A save that resolves each style's font once writes the same program, header, warnings and private
/// data as one that resolves the font of every run again: with type in many fonts, threaded type,
/// type in envelopes, and type taken out again when an envelope is written as its art.
#[test]
fn a_save_writes_the_same_with_each_font_resolved_once() {
use vectorcraft_doc::live::EnvelopeKind;
let save = |doc: &Document, each_run: bool| {
writer::RESOLVE_EACH_RUN.set(each_run);
let out = export_ai_editing(doc, &opts()).unwrap();
let private = private_data(doc, &opts()).unwrap();
writer::RESOLVE_EACH_RUN.set(false);
(out.program, out.header, out.warnings, private.0.data, private.1)
};
let mut docs = vec![sample(), typed(), fonted_document(3)];
for (_, kind) in live_envelope_kinds() {
for editing in [false, true] {
let mut doc = Document::new(200.0, 100.0);
let envelope = typed_envelope_node(&mut doc, kind.clone(), editing);
docs.push(alone(envelope));
}
}
for doc in &docs {
let (once, again) = (save(doc, false), save(doc, true));
assert!(once == again, "{}", String::from_utf8_lossy(&once.0));
}
// An envelope of type one object short of room: it is written as its art, and its story and fonts
// are taken out again.
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
let mut doc = Document::new(200.0, 100.0);
let envelope = typed_envelope_node(&mut doc, kind, false);
let doc = alone(envelope);
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
let within = |each_run: bool| {
writer::RESOLVE_EACH_RUN.set(each_run);
let out = export_within(&doc, &opts(), read - 1).unwrap();
writer::RESOLVE_EACH_RUN.set(false);
(out.program, out.warnings)
};
let (once, again) = (within(false), within(true));
assert!(once.1.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", once.1);
assert!(once == again, "{}", String::from_utf8_lossy(&once.0));
}
/// The CPU time of saving a document of 10,000 point type objects, each in three runs drawn in turn
/// from four fonts (Source Sans 3 Regular and Bold, Inter Medium, and the variable test font's Bold
/// at a weight of 650), with each style's font resolved once and with the font of every run
/// resolved again: the median of 7 runs of each, alternating.
/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture font_resolve_time`.
#[test]
#[ignore = "timing; run by hand"]
fn font_resolve_time() {
use vectorcraft_doc::{TextObject, TextRun};
use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font};
vectorcraft_text::FontDb::global().add_font(variable_font().unwrap());
let fonts = [
style_of(12.0),
font_style("Source Sans 3", "Bold", &[]),
font_style("Inter", "Medium", &[]),
font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)]),
];
let mut doc = Document::new(2000.0, 2000.0);
let layer = doc.layers[0].id;
for i in 0..10_000usize {
let (x, y) = ((i % 100) as f64 * 20.0, (i / 100) as f64 * 20.0 + 10.0);
let mut t = TextObject::point(vectorcraft_geom::Point::new(x, y), "", fonts[0].clone());
t.runs = (0..3).map(|r| TextRun::new(["ab ", "cd ", "ef"][r], fonts[(i + r) % fonts.len()].clone())).collect();
let n = text_node(&mut doc, t);
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
// The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock.
let start = std::time::Instant::now();
let cpu = || {
std::fs::read_to_string("/proc/thread-self/schedstat")
.ok()
.and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::<u64>().ok()))
.unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX))
};
// A first save loads the faces the document names.
export_ai_editing(&doc, &opts()).unwrap();
let mut times: [Vec<u64>; 2] = [vec![], vec![]];
let mut resolves = [0, 0];
let mut outputs: [Vec<u8>; 2] = [vec![], vec![]];
for _ in 0..7 {
for (k, each_run) in [(0, true), (1, false)] {
writer::RESOLVE_EACH_RUN.set(each_run);
writer::FONT_RESOLVES.set(0);
let t = cpu();
let out = export_ai_editing(&doc, &opts()).unwrap();
times[k].push(cpu() - t);
resolves[k] = writer::FONT_RESOLVES.get();
outputs[k] = out.program;
}
}
writer::RESOLVE_EACH_RUN.set(false);
assert!(outputs[0] == outputs[1]);
for (k, label) in [(0, "resolved for every run"), (1, "resolved once")] {
times[k].sort_unstable();
let ms: Vec<String> = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect();
println!("{label}: median {:.1} ms CPU, {} fonts resolved, runs {}", times[k][3] as f64 / 1e6, resolves[k], ms.join(" "));
}
}
fn style_of(size: f64) -> vectorcraft_doc::CharStyle {
style(size, Color::BLACK)
}
+8 -8
View File
@@ -37,12 +37,12 @@ pub(super) use envelopes::ENVELOPES;
pub(super) use meshes::MESHES;
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
#[cfg(test)]
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, REPARSE, STYLE_LINKS, WARPED_IMAGES, same_appearance};
pub(super) use texts::wraps_held;
pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
#[cfg(test)]
pub(super) use paints::{
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
@@ -50,7 +50,7 @@ pub(super) use paints::{
#[cfg(test)]
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
pub(super) use texts::TYPE_ATTRIBUTES;
pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES};
#[cfg(test)]
pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
@@ -320,9 +320,9 @@ pub(super) struct Writer<'a> {
/// How many more envelopes and images with a Warp may be written live: as many as the reader
/// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both.
checks_left: usize,
/// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be
/// read): the pieces of a warped image, which follow one another, read them once.
last_samples: Option<(vectorcraft_doc::ImageBlob, Option<images::Read>)>,
/// The images read so far and their pixels: an image placed again, and each piece of a warped
/// image, is read once.
read_samples: images::SampleCache,
/// The images written whole so far, by the address of their data (which each entry keeps), each
/// with the index of its samples in [`Self::payloads`].
whole_images: HashMap<usize, (Arc<Vec<u8>>, usize)>,
@@ -422,7 +422,7 @@ impl<'a> Writer<'a> {
definition_links: 0,
definition_symbol_nodes: 0,
max_objects: crate::import::MAX_EDITING_OBJECTS,
last_samples: None,
read_samples: images::SampleCache::default(),
whole_images: HashMap::new(),
shown: vec![],
windowed: None,
@@ -1604,7 +1604,7 @@ impl<'a> Writer<'a> {
let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held);
placed.map(|p| (p, self.texts.take_lost()))
} else {
self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t)))
self.texts.add(t, self.canvas).map(|story| ((story, 0), self.texts.loses(t)))
};
let Some(((story, frame), lost)) = placed else {
// The text document can't hold it: the outlines count their own objects.
+6 -5
View File
@@ -401,11 +401,12 @@ impl Writer<'_> {
fn brush_out(&mut self, b: &Brush) -> Option<BrushOut> {
let plugin = crate::import::brush_plugin_name(&b.kind);
let section = format!("Brush Art {}", self.brush_set.sections + 1);
// The art as the reader reads it: a section is read with y down, and an Art brush's art is
// turned over after that (its section's y up is the right of the path).
// The art as the reader reads it: a section is read with y down, and a Scatter or Art
// brush's art is turned over after that (its section's y up is down the page in each
// Scatter copy and the right of the path in Art).
let (params, art) = match &b.kind {
BrushKind::Calligraphic(c) => (calligraphic_params(c), None),
BrushKind::Scatter(s) => (scatter_params(s, &section)?, Some((s.art.clone(), Affine::FLIP_Y))),
BrushKind::Scatter(s) => (scatter_params(s, &section)?, Some((s.art.clone(), Affine::IDENTITY))),
BrushKind::Art(a) => (art_params(a, &section)?, Some((a.art.clone(), Affine::IDENTITY))),
BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None,
};
@@ -565,14 +566,14 @@ impl Writer<'_> {
/// Does the reader read the brushed strokes of style text `text` with their brushes on them?
pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool {
self.brush_set();
let section = super::styles::known_style("x", text);
let Some(parsed) = self.styles.parsed.get(text) else { return false };
let written = &self.brush_set.written;
let read = self.brush_set.read.get_or_insert_with(|| {
let brushes: Vec<(&str, &str, &str, Option<&Node>)> =
written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect();
crate::import::BrushesRead::new(&brushes)
});
read.style_reads(section.as_bytes(), "x")
read.style_reads(parsed)
}
/// The brushes' art in a non-printing block, then the brush manager's order and the brushes in
Loaded 100 of 298 files, more files were not shown because too many files have changed in this diff. Show more