Merge main into fix/custom-toolbar-errors-translated

This commit is contained in:
dotCooCoo
2026-11-14 15:00:58 -08:00
173 changed files with 10176 additions and 1049 deletions
+5
View File
@@ -31,3 +31,8 @@ jobs:
require-craft-fonts: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
run-package-check: true
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
# four jobs and again with two. One rustc at a time; it still uses every core.
cargo-build-extra-args: "-j 1"
cargo-test-extra-args: "-j 1"
+1
View File
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates 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.
+440 -16
View File
@@ -19,11 +19,11 @@
use std::f64::consts::PI;
use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::text::TextObject;
@@ -79,7 +79,11 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) ->
/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ),
/// as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let stops = &g.stops;
link_in(&g.stops, t)
}
/// [`link_at`] of a gradient's `stops`.
fn link_in(stops: &[GradientStop], t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates);
let Some(first) = stops.first() else { return (None, 1.0, None) };
if t <= first.offset {
@@ -103,15 +107,32 @@ fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
stops.last().map_or((None, 1.0, None), link)
}
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred).
/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two
/// where either gradient steps there: two of its stops at the same offset).
const STEP: f32 = 1e-4;
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An
/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its
/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step.
fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
let mut out = g.clone();
out.stops = offsets
.iter()
.map(|&o| {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
.enumerate()
.map(|(i, &o)| {
let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o);
let stepped =
if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None };
match stepped {
Some(s) => {
GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) }
}
None => {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
}
}
})
.collect();
out
@@ -130,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec<f32>) {
}
/// Two gradients of one kind with the same number of stops: as they are when the counts match,
/// else both resampled at every place either changes.
/// else both resampled at every place either changes, with two stops where either steps.
fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
if a.kind != b.kind {
return None;
@@ -146,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
gradient_breaks(b, &mut offs);
offs.retain(|o| o.is_finite());
offs.sort_by(f32::total_cmp);
offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4);
Some((resample_stops(a, &offs), resample_stops(b, &offs)))
offs.dedup_by(|x, y| (*x - *y).abs() < STEP);
let mut steps: Vec<f32> =
[a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect();
steps.sort_by(f32::total_cmp);
let mut at = Vec::with_capacity(offs.len() + steps.len());
let mut k = 0;
for o in offs {
at.push(o);
while steps.get(k).is_some_and(|&s| s <= o - STEP) {
k += 1;
}
if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) {
at.push(o);
}
}
Some((resample_stops(a, &at), resample_stops(b, &at)))
}
fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<GradientPaint> {
@@ -627,12 +662,128 @@ fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr
out
}
/// A stroke read along its subpath turned as `o` says: its width profile (whose sides swap when
/// reversed), pen pressure, tilt, bearing and rotation. Its arrowheads stay as they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the
/// part from `s` on runs first, then the part before it, stepping where the old start now falls.
/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once.
/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between
/// two of them the link [`link_at`] reads there.
fn gradient_from(g: &Gradient, s: f32) -> Gradient {
// A hue gradient that reflects unrolls through its curve, whose stops have no links: the links
// come from its own stops unrolled as a Classic gradient's, which keep them.
let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue();
let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() });
let g = g.unrolled();
let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone());
own.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let mut stops = Vec::new();
// The part from `s` to the end runs first, then the part up to `s`.
for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] {
// The first of `own` not yet matched: the parts' stops run in order, so the links are
// found in one pass.
let mut j = 0;
for (k, st) in g.span(from, to).stops.into_iter().enumerate() {
let p = from + (to - from) * st.offset;
while own.get(j).is_some_and(|o| o.offset <= p - STEP) {
j += 1;
}
let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity);
let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP));
let mut hit = near.clone().find(|&i| same(i));
// A part starting on a step starts with the color after it, so its first stop takes
// the link of the step's last stop of that color.
if k == 0
&& let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset)
{
hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit);
}
let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) {
Some((i, o)) => {
j = i + 1;
(o.swatch.clone(), o.tint, o.plates)
}
None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p),
};
stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st });
}
}
Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() }
}
/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the
/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries
/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern
/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs
/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners
/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed
/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run
/// on without restarting there.
fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
if !d.is_dashed() || !d.offset.is_finite() {
return;
}
let mut pat = d.pattern.clone();
// An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap).
if pat.len() % 2 == 1 {
pat.extend_from_within(..);
}
let period: f64 = pat.iter().sum();
// Where along the key's own subpath the turned one starts (a closed one wraps round). A
// closed one reversed from its own start runs back from its end.
let at = match (o.closed, o.seam()) {
(true, s) if s == 0.0 && o.reversed => 1.0,
(true, s) => s,
(false, _) => o.start,
};
let first = pat.first().copied().unwrap_or(0.0);
let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len };
let offsets: Vec<f64> = lens.iter().map(|&len| offset(len)).collect();
let agree = offsets.first().is_some_and(|&a| {
offsets.iter().all(|&b| {
let r = (b - a).rem_euclid(period);
r.is_finite() && r.min(period - r) <= 1e-6
})
});
if o.reversed {
if let Some(rest) = pat.get_mut(1..) {
rest.reverse();
}
d.pattern = pat;
}
if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) {
d.offset = off;
}
}
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
/// they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
if o.is_identity() {
return;
}
if let Some(d) = &mut s.dash {
reorient_dash(d, o, lens);
}
let along = s.gradient_mode == StrokeGradientMode::Along;
if s.path_gradient().is_some()
&& let Paint::Gradient(g) = &mut s.paint
{
let start = along && o.seam() > 0.0;
if start {
g.gradient = gradient_from(&g.gradient, o.seam() as f32);
}
// Stops that reflect an even number of times read the same either way.
let (spread, runs) = g.gradient.painted_spread();
let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0);
if reverse {
g.gradient.reverse();
}
if start || reverse {
// The turned gradient is no longer the swatch's.
g.swatch = None;
}
}
let same = |v: f64| v;
if let Some(p) = &mut s.profile {
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
@@ -676,9 +827,11 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
if o.is_identity() {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
reorient_stroke(s, o, &lens);
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
@@ -709,9 +862,11 @@ pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
if o.is_identity() || !turns.all(|t| t.same_turn(&o)) {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
reorient_stroke(s, o, &lens);
}
}
}
@@ -2791,6 +2946,275 @@ mod tests {
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
}
#[test]
fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() {
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
let mut ap = Appearance::default();
ap.set_stroke(Paint::solid(Color::BLACK));
if let Some(s) = ap.stroke_mut() {
edit(s);
}
Node::path(NodeId(1), path, ap)
};
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
// How light the stroke's gradient is at `u` (0 black, 3 white).
let light = |s: &StrokeLayer, u: f32| match &s.paint {
Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::<f32>(),
p => panic!("a gradient: {p:?}"),
};
// Whether dash pattern `d` draws a dash `at` this far along its subpath.
let dash_at = |d: &Dash, at: f64| {
let p = if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() };
let mut x = (at + d.offset).rem_euclid(p.iter().sum());
for (i, v) in p.iter().enumerate() {
if x < *v {
return i % 2 == 0;
}
x -= v;
}
false
};
let graded = |mode: StrokeGradientMode| {
move |s: &mut StrokeLayer| {
s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
s.gradient_mode = mode;
s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false });
}
};
// An open key clicked at its last anchor runs the other way: a gradient along it or across
// it (whose sides swap) runs the other way too, and its dashes are read from its end.
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false));
let plain = keyed(line(0.0), &|_| {});
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
let key = keyed(line(100.0), &graded(mode));
let s = stroke(&Lerp::new(&plain, &key, (None, Some(1))).at(1.0));
assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{mode:?}: {:?}", s.paint);
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..130 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, 13.0 - u), "at {u}: {d:?}");
}
}
// A closed key started half way round starts its gradient along it there too, stepping
// where its own start was, and its dashes start there.
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
let key = keyed(square(100.0), &graded(StrokeGradientMode::Along));
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0));
for (u, want) in [(0.0, 1.5), (0.25, 0.75), (0.499, 0.0), (0.501, 3.0), (0.75, 2.25), (1.0, 1.5)] {
assert!((light(&s, u) - want).abs() < 0.02, "at {u}: {} for {want}: {:?}", light(&s, u), s.paint);
}
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..200 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, u + 20.0), "at {u}: {d:?}");
}
// A closed key that winds the other way runs the other way from the same anchor: its
// dashes are read back from the end of its own subpath, which is 40 long and not a whole
// number of periods.
let wound = |x: f64| {
let mut p = square(x);
for sp in &mut p.subpaths {
sp.reverse();
}
p
};
let back = keyed(wound(100.0), &graded(StrokeGradientMode::Along));
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &back, (Some(0), Some(0))).at(1.0));
let (own, d) = (stroke(&back).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..400 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, 40.0 - u), "at {u}: {d:?}");
}
// Stops that reflect twice read the same either way; a link to a swatch stays.
let reflected = keyed(line(100.0), &|s| {
let mut g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::default() };
g.stops[1].swatch = Some("Ink".into());
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
assert_eq!(stroke(&Lerp::new(&plain, &reflected, (None, Some(1))).b).paint, stroke(&reflected).paint);
let linked = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
g.stops[1].swatch = Some("Ink".into());
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &linked, (Some(0), Some(2))).b);
let links = match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some("Ink")).map(|st| st.offset).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert!(links.contains(&0.5), "the stop the old start ended on keeps its link: {:?}", s.paint);
// Each stop of a step keeps its own link.
let step = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
let (mut before, mut after) = (GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.25, Color::WHITE));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
g.stops.splice(1..1, [before, after]);
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &step, (Some(0), Some(2))).b);
let links = match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.offset == 0.75).map(|st| st.swatch.clone()).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links, vec![Some("Ink".into()), Some("Paper".into())], "{:?}", s.paint);
// A step of one color between two swatches, where the turned subpath now starts: the
// start takes the link after the step and the end the link before it.
let seam_step = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
let gray = Color::rgb8(128, 128, 128);
let (mut before, mut after) = (GradientStop::new(0.5, gray), GradientStop::new(0.5, gray));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
g.stops.splice(1..1, [before, after]);
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &seam_step, (Some(0), Some(2))).b);
let ends = match &s.paint {
Paint::Gradient(g) => (g.gradient.stops.first().map(|st| st.swatch.clone()), g.gradient.stops.last().map(|st| st.swatch.clone())),
p => panic!("a gradient: {p:?}"),
};
assert_eq!(ends, (Some(Some("Paper".into())), Some(Some("Ink".into()))), "{:?}", s.paint);
// A hue gradient that reflects keeps its links on the repeated stops.
let hue = keyed(square(100.0), &|s| {
let (mut red, mut blue) =
(GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }));
(red.swatch, blue.swatch) = (Some("Ink".into()), Some("Paper".into()));
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![red, blue])
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue, (Some(0), Some(2))).b);
let linked = |name: &str| match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some(name)).map(|st| st.offset).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert!(linked("Paper").contains(&0.0) && linked("Paper").contains(&1.0), "{:?}", s.paint);
assert!(linked("Ink").contains(&0.5), "{:?}", s.paint);
// Two stops of one color at one place keep their own links, in reverse in a mirrored run.
let hue_step = keyed(square(100.0), &|s| {
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
let (mut before, mut after) = (GradientStop::new(0.5, green), GradientStop::new(0.5, green));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
let stops = vec![
GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }),
before,
after,
GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }),
];
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, stops)
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_step, (Some(0), Some(2))).b);
// The links at `u` in order, a link repeated by the next stop listed once.
let links_at = |u: f32| match &s.paint {
Paint::Gradient(g) => {
let mut links =
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
links.dedup();
links
}
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links_at(0.25), vec!["Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
assert_eq!(links_at(0.75), vec!["Ink".to_string(), "Paper".to_string()], "{:?}", s.paint);
// Where two runs meet, each run's stops keep their own links.
let hue_end = keyed(square(100.0), &|s| {
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
let (mut a, mut b) = (GradientStop::new(1.0, green), GradientStop::new(1.0, green));
(a.swatch, b.swatch) = (Some("Ink".into()), Some("Paper".into()));
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), a, b])
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_end, (Some(0), Some(1))).b);
let links_at = |u: f32| match &s.paint {
Paint::Gradient(g) => {
let mut links =
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
links.dedup();
links
}
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links_at(0.25), vec!["Ink".to_string(), "Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
// Blended with a gradient of other stops, the steps keep that step.
let three = keyed(square(0.0), &|s| {
let mut g = Gradient::default();
g.stops.insert(1, GradientStop::new(0.5, Color::BLACK));
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&three, &key, (Some(0), Some(2))).at(0.75));
assert!(light(&s, 0.501) - light(&s, 0.499) > 1.5, "{:?}", s.paint);
// Subpaths whose lengths call for different dash offsets keep the offset.
let rings = |x: f64, turn: usize| {
let mut inner = shapes::rectangle(Rect::new(x, 20.0, x + 7.0, 27.0)).subpaths.remove(0);
inner.anchors.rotate_left(turn);
PathData::new(vec![square(x).subpaths.remove(0), inner])
};
let key = keyed(rings(100.0, 2), &graded(StrokeGradientMode::Along));
let blend = Lerp::new(&keyed(rings(0.0, 0), &|_| {}), &key, (Some(0), Some(2)));
let turned = match &blend.shape {
Shape::Path { pair, .. } => pair.orient.1,
_ => panic!("a path blend"),
};
assert!((turned.seam() - 0.5).abs() < 1e-9, "both rings turn half way round: {turned:?}");
let s = stroke(&blend.at(1.0));
assert_eq!(s.dash.map(|d| d.offset), Some(0.75));
}
#[test]
fn gradients_of_other_stop_counts_keep_their_steps() {
let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
let stepped = Gradient::new(
vectorcraft_color::GradientKind::Linear,
vec![
GradientStop::new(0.0, Color::WHITE),
GradientStop::new(0.5, Color::BLACK),
GradientStop::new(0.5, Color::WHITE),
GradientStop::new(0.50015, red),
GradientStop::new(1.0, Color::BLACK),
],
);
let (a, b) = common_stops(&stepped, &Gradient::default()).unwrap_or_else(|| panic!("one kind"));
let at = |g: &Gradient| g.stops.iter().map(|s| (s.offset, s.color)).collect::<Vec<_>>();
assert_eq!(at(&a), vec![(0.0, Color::WHITE), (0.5, Color::BLACK), (0.5, Color::WHITE), (0.50015, red), (1.0, Color::BLACK)]);
assert_eq!(b.stops.len(), 5);
assert_eq!(b.stops.get(1).map(|s| s.color), b.stops.get(2).map(|s| s.color), "a gradient without the step paints one color there");
// A gradient with two stops close to the other's step, but no step of its own, does not step there.
let close = Gradient::new(
vectorcraft_color::GradientKind::Linear,
vec![
GradientStop::new(0.0, Color::WHITE),
GradientStop::new(0.5, Color::BLACK),
GradientStop::new(0.50005, red),
GradientStop::new(1.0, Color::BLACK),
],
);
let (_, b) = common_stops(&stepped, &close).unwrap_or_else(|| panic!("one kind"));
assert_eq!(b.stops.get(1).map(|s| s.color), Some(Color::BLACK));
assert_eq!(b.stops.get(2).map(|s| s.color), Some(Color::BLACK), "{:?}", b.stops);
}
#[test]
fn odd_dash_blends_to_solid_with_closed_gaps() {
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
+47
View File
@@ -379,6 +379,22 @@ pub struct SeriesPaint {
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub blend: Option<vectorcraft_color::BlendMode>,
/// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque.
/// Graph labels keep none.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_opacity: Option<f32>,
/// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_blend: Option<vectorcraft_color::BlendMode>,
/// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub group_isolate: bool,
/// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_knockout: Option<crate::Knockout>,
/// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub group_knockout_shape: bool,
/// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own
/// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -527,6 +543,10 @@ pub struct GraphSpec {
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
#[serde(skip_serializing_if = "Option::is_none")]
pub placed: Option<Rect>,
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
#[serde(skip_serializing_if = "Option::is_none")]
pub placed_art: Option<Rect>,
}
fn at_most_one(n: &usize) -> bool {
@@ -610,6 +630,32 @@ impl GraphSpec {
}
}
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
}
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
/// gives its own bounds, so a clipping group gives the bounds of its clip.
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
if matches!(n.kind, crate::NodeKind::Text(_)) {
return (None, true);
}
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
let mut bounds: Option<Rect> = None;
let mut had_type = false;
for c in children {
let (b, t) = art_bounds_of(c);
had_type |= t;
bounds = match (bounds, b) {
(Some(a), Some(b)) => Some(a.union(b)),
(a, b) => a.or(b),
};
}
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
}
impl Default for GraphSpec {
fn default() -> Self {
Self {
@@ -659,6 +705,7 @@ impl Default for GraphSpec {
connect_points: true,
edge_to_edge: false,
placed: None,
placed_art: None,
}
}
}
+1
View File
@@ -55,6 +55,7 @@ mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod ppi;
pub mod profiles;
pub mod puppet;
pub mod range;
+287
View File
@@ -0,0 +1,287 @@
//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`,
//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image
//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]).
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads?
pub fn reads(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(&[0xff, 0xd8])
|| bytes.starts_with(b"II*\0")
|| bytes.starts_with(b"MM\0*")
|| (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP")
|| bytes.starts_with(b"BM")
}
/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each
/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files.
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else {
None
};
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
}
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
b.get(at..at.checked_add(n)?)
}
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi
/// in the stored pixels' axes, unchecked; `None` without an absolute unit.
pub fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = slice(b, at + 8, len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
pub fn pixels_per_metre(ppi: f64) -> u32 {
(ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32
}
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
fn crc32(parts: &[&[u8]]) -> u32 {
let mut crc = !0u32;
for &b in parts.iter().flat_map(|p| p.iter()) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
}
}
!crc
}
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
// x, y, unit 1 = metre.
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
let mut out = Vec::with_capacity(21);
out.extend_from_slice(&9u32.to_be_bytes());
out.extend_from_slice(b"pHYs");
out.extend_from_slice(&data);
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
out
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there.
#[test]
fn a_png_takes_its_resolution_and_still_decodes() {
let png = png_of(4, 3);
assert_eq!(resolution(&png), None);
let tagged = with_png_resolution(&png, (300.0, 150.0));
assert_eq!(resolution(&tagged), Some((300.0, 150.0)));
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
// Every PNG ends with this IEND chunk CRC.
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
}
/// RIFF chunk `ty` holding `data`, padded to an even length.
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
if data.len() % 2 == 1 {
out.push(0);
}
out
}
fn webp_of(chunks: &[Vec<u8>]) -> Vec<u8> {
let body = chunks.concat();
let size = u32::try_from(body.len() + 4).unwrap();
[b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat()
}
/// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose
/// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to
/// an offset) gives no resolution.
#[test]
fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() {
// Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch.
let mut tiff = b"II*\0".to_vec();
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&2u16.to_le_bytes());
for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&ty.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
}
tiff.extend_from_slice(&0u32.to_le_bytes());
tiff.extend_from_slice(&300u32.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
let exif = [b"Exif\0\0".as_slice(), &tiff].concat();
let exif_len = u32::try_from(exif.len()).unwrap();
let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]);
assert_eq!(resolution(&ok), Some((300.0, 300.0)));
for len in [u32::MAX, u32::MAX - 7, 1_000] {
let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]);
assert_eq!(resolution(&bad), None, "chunk length {len}");
}
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
outline_text, reshape,
outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+16 -5
View File
@@ -508,6 +508,20 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
(runs, all, layout.bounds, colours)
}
/// Paint `piece`, a piece of type's outline in text space (glyphs, ruby glyphs or an underline or
/// strikethrough bar), with `style`, the fills and strokes of its run, and place it in the document
/// by `xf`, the type's transform, as the renderer paints the run: its unplaced gradients are fixed
/// to `bounds`, the layout's bounds in text space, so every piece of the type shows the one
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
/// move with the type.
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
let mut ap = style.appearance();
ap.pin_gradients(bounds);
piece.appearance = ap.into();
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
}
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
/// outline with the object's items below the characters under them and the others over them, as
@@ -520,7 +534,6 @@ pub fn outline_text(n: &Node) -> Option<Node> {
let NodeKind::Text(t) = &n.kind else { return None };
let (runs, all, bounds, colours) = laid_out(t);
let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf);
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
let mut children: Vec<Arc<Node>> = vec![];
for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() {
// Colour glyphs paint themselves, under their run's fill, as the renderer paints them.
@@ -528,10 +541,8 @@ pub fn outline_text(n: &Node) -> Option<Node> {
if bp.elements().is_empty() {
continue;
}
let mut ap = run.style.appearance();
ap.pin_gradients(bounds);
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap);
piece.transform(t.xf, scaling);
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
children.push(Arc::new(piece));
}
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
+153 -25
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
use crate::solids::wireframe::WireFace;
use crate::solids::{
@@ -338,34 +338,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
/// the surface it is cast from is past the limits.
fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> {
///
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
/// surface is swept again for its shadow alone.
fn shadow_of(
id: NodeId,
fx: &Effect,
path: &PathData,
item: &AppearanceItem,
b: Rect,
options: Revolve,
kept: Option<SolidFaces>,
) -> Result<Option<Node>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
let (_, opacity, blend) = paint_of(item);
if opacity <= 0.0 {
return Ok(None);
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?;
cast_surface(&mut caster, path, b, options, kept)?;
Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend }))
}
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
/// its shadow is cast from ([`surface`])?
fn casts(fx: &Effect, opacity: f32) -> bool {
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
}
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
/// drawn, or without them, the surface swept for its shadow alone.
fn cast_surface(
caster: &mut vectorcraft_three_d::ShadowCaster,
path: &PathData,
b: Rect,
options: Revolve,
kept: Option<SolidFaces>,
) -> Result<std::ops::Range<usize>, String> {
match kept {
Some(kept) => caster.add_solid(kept),
None => {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
}
}
}
/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one,
/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque,
/// in its paint's blending mode, and its opacity mask and blending mode apply to that part
/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the
/// limits.
fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> {
/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow
/// ([`surface`]); a member without them is swept again for its shadow alone.
fn group_shadow(
id: NodeId,
fx: &Effect,
shapes: &[Profile],
b: Rect,
options: Revolve,
kept: Vec<Option<SolidFaces>>,
) -> Result<Vec<Arc<Node>>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) };
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let mut cast = vec![];
let mut kept = kept.into_iter();
for s in shapes {
let kept = kept.next().flatten();
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
// A member whose surface is fully transparent casts nothing.
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
if ink.opacity <= 0.0 {
continue;
}
let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?;
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
cast.push((s.scopes.as_slice(), ink, faces));
}
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
@@ -377,7 +423,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
/// a face with a part of a graphic is a group of the face and that part.
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
#[allow(clippy::too_many_arguments)]
fn surface(
doc: Option<&Document>,
@@ -391,11 +438,18 @@ fn surface(
blend: vectorcraft_doc::color::BlendMode,
expand: bool,
copies: &mut Copies,
) -> Option<(Vec<Drawn>, Node)> {
cast: bool,
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
// A loaded file or a profile edited past the limits keeps drawing its source path instead
// of crashing the frame. Commands validate the same evaluator and report its errors.
if fx.id == CLASSIC_REVOLVE {
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
let (facets, kept) = if cast {
vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
} else {
(vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None)
};
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
@@ -405,10 +459,14 @@ fn surface(
let drawn =
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
let p = merged_params(&fx.id, &fx.params);
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p)));
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
}
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
let (faces, kept) = if cast {
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
} else {
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
};
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
@@ -532,7 +590,7 @@ fn surface(
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
Some((keys, group))
Some((keys, group, kept))
}
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
@@ -549,8 +607,9 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
/// [`surface`] adds to; its graphics take the symbols of `doc`.
fn object_surface(
doc: Option<&Document>,
n: &Node,
@@ -559,10 +618,11 @@ fn object_surface(
item: &AppearanceItem,
expand: bool,
copies: &mut Copies,
) -> Option<Node> {
) -> Option<(Node, Option<SolidFaces>)> {
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
let cast = casts(fx, opacity);
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
}
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
@@ -692,7 +752,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, fx, options)?);
}
return Ok((out, group_shadow(n.id, fx, &shapes, b, options)?));
return Ok((out, group_shadow(n.id, fx, &shapes, b, options, vec![])?));
}
let (path, _) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
@@ -703,7 +763,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&path, b, fx, fx_options(fx))?;
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx))?;
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)?;
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
@@ -764,9 +824,9 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let paints = solid_paints(n);
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
if let Some(b) = path.bounds()
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
{
children.push(Arc::new(shadow));
}
@@ -790,10 +850,10 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
if let Some(b) = p.bounds()
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
{
shadow.appearance.effects = art.appearance.effects.clone();
shadows.push(Arc::new(shadow));
@@ -942,21 +1002,28 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut copies = Copies::default();
let mut surfaces = vec![];
// The faces each member's surface kept for the shadow, member by member.
let mut kept = vec![];
let mut opaque = true;
// The graphics go once, on the side of the member with the longest profile. Without graphics
// no member is measured for them.
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
for (k, s) in shapes.iter().enumerate() {
let Some(item) = surface_item(&s.items) else { continue };
let Some(item) = surface_item(&s.items) else {
kept.push(None);
continue;
};
// The opacity and blending of the member and the groups it is in apply through its scopes.
let (paint, opacity, blend) = paint_of(item);
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
// A member with transparency of its own keeps every face, as a transparent object does.
let expand = expand && s.scopes.is_empty();
let doc = doc.filter(|_| longest == Some(k));
let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
let cast = casts(fx, opacity * s.opacity);
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
surfaces.push((depths, art, s.scopes.as_slice()));
kept.push(faces);
}
if surfaces.is_empty() {
return None;
@@ -1057,7 +1124,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
};
// One shadow for every member's surface, behind them all.
let mut children = children;
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?);
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
@@ -1682,6 +1749,67 @@ mod tests {
}
assert_eq!(expand_revolve_art(&sample), revolve_art(&sample));
}
/// The settings the shadows are compared with: the defaults, a partial sweep turned with
/// perspective, and an open surface away from its axis under a colored light.
fn shadow_settings() -> [Value; 3] {
[
json!({"shadow": true}),
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}),
json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}),
]
}
/// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces,
/// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an
/// object whose fill is half transparent, and for a group of two members, one at half opacity.
#[test]
fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() {
for id in [REVOLVE, CLASSIC_REVOLVE] {
for params in shadow_settings() {
// Revolve (Classic) takes no shadow settings from commands, but a file can carry them.
let mut fx = crate::new_effect(id, &json!({})).unwrap();
fx.params = params.clone();
let n = profile_node();
let (path, _) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let mut half = n.clone();
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
f.opacity = 0.5;
}
for n in [n, half] {
let item = surface_item(&n.appearance.items).unwrap();
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
let mut other = profile_node();
other.id = NodeId(2);
other.transform(Affine::translate((120.0, 0.0)), false);
other.opacity = 0.5;
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
g.appearance.effects.push(fx.clone());
let shapes = members(&g, "").unwrap();
let b = union_bounds(&shapes).unwrap();
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
let kept: Vec<Option<SolidFaces>> = shapes
.iter()
.map(|s| {
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
let cast = casts(&fx, opacity * s.opacity);
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
})
.collect();
assert!(kept.iter().all(Option::is_some), "{id} {params}");
let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap();
let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap();
assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
}
}
}
#[cfg(test)]
+197 -67
View File
@@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask};
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View};
use vectorcraft_three_d::{
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
}
}
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
/// classic effects cast no shadow: they keep no faces.
fn facets_and_faces(
id: &str,
path: &PathData,
rule: FillRule,
bounds: Rect,
p: &Value,
cast: bool,
) -> Result<(Vec<Facet>, Option<SolidFaces>), String> {
let view = view_options(p);
#[cfg(test)]
if cast && id == EXTRUDE {
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
}
let built = match id {
EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view),
ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view),
_ => return facets(id, path, rule, bounds, p).map(|f| (f, None)),
};
built.map(|(f, faces)| (f, Some(faces)))
}
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
/// need the object.
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
@@ -693,7 +719,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
#[cfg(test)]
thread_local! {
/// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests.
static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's
/// surfaces count too.
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
/// [`built_solids`] have built on this thread, for the tests.
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
@@ -712,10 +740,35 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
/// The surfaces of an object's solids, and the faces each solid kept for its shadow
/// ([`surfaces_for`]).
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]).
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
parts: &'a [Part<'a>],
bounds: Rect,
limit: usize,
cast: bool,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| {
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p))
let (o, view) = (inflate_options(p), view_options(p));
if cast {
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
} else {
Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None))))
}
});
let mut kept = 0usize;
let mut ended = false;
@@ -729,13 +782,13 @@ fn built_solids<'a>(
Some(each) => {
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
each.next().unwrap_or_else(|| Ok(vec![]))
each.next().unwrap_or_else(|| Ok((vec![], None)))
}
None => facets(id, area, *rule, bounds, p),
None => facets_and_faces(id, area, *rule, bounds, p, cast),
};
let result = match built {
Ok(f) => {
kept = kept.saturating_add(f.len());
kept = kept.saturating_add(f.0.len());
if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) }
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None),
@@ -1364,12 +1417,19 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), to be drawn behind every surface of the object, and the surfaces.
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
/// surface of the object, and the surfaces.
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(doc, n, fx, shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
let shadow = shadow_for(n.id, fx, shapes).ok()?;
let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) };
let shadow = match shadow.ok()? {
Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)),
None => vec![],
};
Some((shadow, art))
}
@@ -1408,6 +1468,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
for s in shapes {
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
let faces = caster.plane(&area, rule, b, view)?;
cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces));
}
@@ -1419,10 +1481,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
} else {
let mut added = vec![];
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
}
added
@@ -1444,6 +1510,76 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
Ok(Some((caster, settings, cast)))
}
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
return Ok(None);
}
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let mut cast: Vec<shadow::Cast> = vec![];
let ink = |item: &AppearanceItem, member: f32| {
let (_, opacity, blend) = paint_of(item, member);
shadow::Ink { opacity, blend }
};
if id == ROTATE {
let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect();
if items.len() != built.len() {
return cast_shadow(id, p, shapes);
}
for ((s, item), kept) in items.into_iter().zip(built) {
let ink = ink(item, s.opacity);
if ink.opacity <= 0.0 {
continue;
}
let faces = match kept {
Some(kept) => caster.add_solid(kept)?,
None => {
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.plane(&area, rule, b, view)?
}
};
cast.push((s.scopes.as_slice(), ink, faces));
}
return Ok(Some((caster, settings, cast)));
}
let (parts, bounds) = solid_parts(shapes, b);
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
return cast_shadow(id, p, shapes);
}
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
if ink.opacity <= 0.0 {
continue;
}
let faces = match kept {
Some(kept) => caster.add_solid(kept),
None => {
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.extrude(area, *rule, bounds, extrude_options(p), view)
}
};
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
// the solids together, the shadow is refused.
let faces = match faces {
Ok(faces) => faces,
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
Err(e) => return Err(e),
};
cast.push((*scopes, ink, faces));
}
Ok(Some((caster, settings, cast)))
}
/// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with
/// its member's scopes and ink ([`cast_shadow`]).
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
@@ -1502,31 +1638,31 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool {
colored && crate::lighting::opaque_paint(paint).1.is_some()
}
/// A graphic of [`placed_graphics`]: the index of the first surface of the solids that share it,
/// the index of the surface it is drawn right after, its face and its art.
type Placement = (usize, usize, PlanarFace, Arc<Node>);
/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is
/// drawn right after (the last of those solids holding its face) and its face. Solids in a run
/// with the same opacity and blending mode share their graphics. With `per_member`
/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get
/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes.
/// All the groups share one limit on the path elements drawn: once it is reached, later groups
/// draw no graphics.
fn placed_graphics(
doc: Option<&Document>,
id: NodeId,
effect: (&str, &Value),
bounds: Rect,
filled: &[Filled],
per_member: bool,
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
/// with the same opacity and blending mode share their graphics, one on each face. With
/// `per_member` (a member's opacity mask or blending mode applies to its surfaces) each member's
/// solids get graphics of their own, clipped to that member's caps, so they stay in that member's
/// scopes. All the groups share one limit on the path elements drawn: once it is reached, later
/// groups draw no graphics.
fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), bounds: Rect, filled: &[Filled], per_member: bool) -> Vec<Placement> {
let mut groups: Vec<Vec<&Filled>> = vec![];
for f in filled {
// Solids whose fills or strokes differ in opacity or blending mode get graphics of their
// own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask
// gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the
// group of the solid before it, so a graphic is never drawn past a solid painted between.
let joins = |first: &Filled| {
(!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked
// own, each drawn as its fill or stroke is. One member's solids share their graphics
// whether or not their surfaces carry an opacity mask, and each graphic takes the mask of
// the surface it is drawn after ([`with_graphics`]). Solids of different members share
// them only when neither surface carries a mask. A solid joins only the group of the solid
// before it, so a graphic is never drawn past a solid painted between.
let joins = |g: &&Filled| {
let member = g.member == f.member;
(member || !per_member && !g.masked && !f.masked) && g.opacity == f.opacity && g.blend == f.blend
};
match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) {
match groups.last_mut().filter(|g| g.iter().all(joins)) {
Some(g) => g.push(f),
None => groups.push(vec![f]),
}
@@ -1535,12 +1671,13 @@ fn placed_graphics(
let mut elements = 0usize;
for group in groups {
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
let first = group.first().map_or(0, |f| f.at);
let opacity = group.first().map_or(1.0, |f| f.opacity);
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
Arc::make_mut(&mut art).blend = blend;
out.push((f.at, face, art));
out.push((first, f.at, face, art));
}
}
}
@@ -1552,23 +1689,19 @@ fn placed_graphics(
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
/// [`with_graphics`] of built surfaces, each drawn whole.
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[Placement]) -> Vec<(&'s [Scope], Arc<Node>)> {
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts)
}
/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts`
/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes
/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(
surfaces: Vec<(&'s [Scope], Arc<Node>)>,
first: usize,
arts: &[(usize, PlanarFace, Arc<Node>)],
) -> Vec<(&'s [Scope], Arc<Node>)> {
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, first: usize, arts: &[Placement]) -> Vec<(&'s [Scope], Arc<Node>)> {
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
let mask = s.extras().mask.clone();
out.push((scopes, s));
out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| {
out.extend(arts.iter().filter(|(_, at, ..)| *at == first + k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
@@ -1585,8 +1718,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
}
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -1601,11 +1736,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
// the centre of theirs), so they stay together.
let mut out = vec![];
let mut filled = vec![];
let mut built = vec![];
for (member, s) in shapes.iter().enumerate() {
for item in &s.items {
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?;
built.push(faces);
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
return None;
}
@@ -1622,19 +1761,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, 0, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
}
let (parts, bounds) = solid_parts(shapes, b);
let mut solids = vec![];
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) {
let mut built = vec![];
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
let item: &AppearanceItem = item;
match f {
Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
return None;
}
Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)),
Ok(Some((f, faces))) => {
solids.push((item, *opacity, *scopes, f, *member));
built.push(faces);
}
// A stroke's outline past the limits is left out; the fill's solid still draws.
Ok(None) => {}
Ok(None) => built.push(None),
// A loaded file or a shape edited past the limits (its own, or those of the object's
// solids together) keeps drawing its source path instead of failing the frame;
// commands validate the same evaluator and report its errors.
@@ -1763,14 +1906,14 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
out.extend(with_graphics(run.collect(), first, &arts));
}
}
return Some(masked(n.id, out));
return Some((masked(n.id, out), built));
}
if !opaque || !surfaces.iter().all(plain) {
let surfaces =
surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect();
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built));
}
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))])
Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built))
}
/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when
@@ -1793,16 +1936,9 @@ fn underlaid_surface(id: NodeId, surface: Node, seal: bool) -> Node {
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
/// The faces of the surfaces that `seals` marks lie over underlays of themselves
/// ([`underlaid_runs`], [`underlaid_surface`]).
fn in_one_order(
id: NodeId,
surfaces: Vec<BuiltSurface<'_>>,
first: usize,
arts: &[(usize, PlanarFace, Arc<Node>)],
sealed: bool,
seals: &[bool],
) -> Vec<Arc<Node>> {
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[Placement], sealed: bool, seals: &[bool]) -> Vec<Arc<Node>> {
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect();
let arts: Vec<&Placement> = arts.iter().filter(|(_, at, ..)| (first..first + surfaces.len()).contains(at)).collect();
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
@@ -1813,24 +1949,18 @@ fn in_one_order(
}
let order = draw_order(&placed, sealed);
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
// mask that ends at its surface.
// share it ([`placed_graphics`]): those from the first of them to its own.
let last: Vec<Option<usize>> = arts
.iter()
.map(|(at, face, _)| {
let at = at - first;
let from = if masks.get(at).is_some_and(Option::is_some) {
at
} else {
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
};
.map(|(from, at, face, _)| {
let (from, at) = (from.saturating_sub(first), at - first);
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
})
.collect();
let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
drawn.extend(faces.get_mut(k).and_then(Option::take));
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| {
let mut art = art.clone();
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
+111 -55
View File
@@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
};
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
assert_eq!(masks(&art), vec![true]);
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
// and the stroke's outline gets an unmasked one.
// With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn
// after the stroke's cap as for a fill without a mask, and it takes the stroke's surface,
// which carries no mask.
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]);
}
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
@@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec<PathData> {
out
}
/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many
/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and
/// its blending mode.
fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> {
fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) {
match &n.kind {
NodeKind::Group { children, clip: true } => {
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
p.path_data().is_some()
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
}),
_ => false,
});
if graphic {
out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend));
} else if children.first().and_then(|c| c.path_data()).is_some() {
*faces += 1;
}
}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)),
_ => *faces += usize::from(n.path_data().is_some()),
}
}
let mut out = vec![];
walk(art, &mut 0, &mut out);
out
}
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops:
/// after the stroke's cap, without a mask.
#[test]
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
let solid = |graphics: Value| {
// A red gradient whose last stop has opacity `last`.
let gradient = |last: f32| {
let mut stop = GradientStop::new(1.0, red());
stop.opacity = last;
GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))
};
let solid = |fill: &GradientPaint, graphics: Value| {
let mut n = object(
EXTRUDE,
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient.clone()));
f.paint = Paint::Gradient(Box::new(fill.clone()));
}
// A gradient stroke: a solid color under the colored light would be one composite.
let blues = Gradient::new(
@@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
n.appearance.items.push(AppearanceItem::Stroke(stroke));
solid_art_in(Some(&d), &n).unwrap()
};
let with = solid(json!([{"symbol": "Mark"}]));
let without = solid(json!([]));
let masked = gradient(0.25);
let with = solid(&masked, json!([{"symbol": "Mark"}]));
let without = solid(&masked, json!([]));
assert!(face_paths(&without).len() > 20, "the faces are found");
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
let mut masked = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
&& paths.iter().any(|p| {
p.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
AppearanceItem::Stroke(_) => false,
})
})
{
masked.push(c.extras().mask.is_some());
}
});
masked.sort_unstable();
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
let mut drawn: Vec<(&str, Rect)> = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& c.extras().mask.is_some()
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
{
drawn.push(("graphic", bounds));
}
let first_stop = c.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => match &f.paint {
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
_ => None,
},
AppearanceItem::Stroke(_) => None,
});
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
}
});
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
let mut mask = false;
with.walk(&mut |c| mask |= c.extras().mask.is_some());
assert!(mask, "the fill's faces carry the gradient's mask");
let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}]));
assert_eq!(face_paths(&opaque), face_paths(&with));
let places = graphic_places(&with);
assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::<Vec<_>>(), [(false, 1.0, BlendMode::Normal)]);
assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it");
}
/// A plane in a gradient with transparent stops under a colored light draws its graphic with the
/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask.
#[test]
fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap());
assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::<Vec<_>>(), [true]);
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
n.appearance.items.push(AppearanceItem::Stroke(stroke));
let art = solid_art_in(Some(&d), &n).unwrap();
let places = graphic_places(&art);
assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face");
}
/// Members of a group share a graphic only when neither surface carries an opacity mask, while
/// one member's fill and stroke share theirs.
#[test]
fn members_in_transparent_gradients_keep_graphics_of_their_own() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))));
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0));
// Whether each graphic drawn on the group of `members` carries an opacity mask, in order.
let masks = |members: Vec<Node>| {
let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect());
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let mut masks: Vec<bool> = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect();
masks.sort_unstable();
masks
};
assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]);
// With a dashed stroke, the first member's fill and stroke share one graphic, without a mask.
let mut stroked = square(1, left, gradient.clone());
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
stroked.appearance.items.push(AppearanceItem::Stroke(stroke));
assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]);
// A member with a gray stroke listed before its fill in the gradient does not share its
// graphic with the gray member after it.
let mut layered = square(1, left, gradient);
layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0)));
assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]);
}
#[test]
+89
View File
@@ -223,3 +223,92 @@ fn expand_appearance_keeps_the_shadow_as_a_path() {
assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}");
}
}
/// A square filled red and stroked blue, its stroke as opaque as `stroke`.
fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node {
let mut n = square_node(id, dx);
n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into();
for item in &mut n.appearance.items {
if let AppearanceItem::Stroke(s) = item {
s.opacity = stroke;
}
}
n
}
/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose
/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members,
/// one of them at half opacity.
fn shadowed(id: &str, params: &Value) -> Vec<Node> {
let with = |mut n: Node| {
n.appearance.effects.push(crate::new_effect(id, params).unwrap());
n
};
let mut half = stroked_square(2, 200.0, 1.0);
half.opacity = 0.5;
let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]);
vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)]
}
/// The settings the shadows of effect `id` are compared with: the defaults, turned with
/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and
/// Rotate and behind it for Revolve.
fn shadow_settings(id: &str) -> [Value; 3] {
let position = if id == crate::REVOLVE { "behind" } else { "below" };
[
json!({"shadow": true}),
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}),
json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}),
]
}
/// How many solids drawing the art of `n` with effect `id` builds.
fn solids_built(n: &Node, id: &str) -> usize {
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
assert!(art(n, id).is_some(), "{id}");
SOLIDS_BUILT.with(std::cell::Cell::get) - start
}
/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from
/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow.
#[test]
fn a_shadowed_3d_object_builds_each_solid_once() {
for id in CASTING {
for params in shadow_settings(id) {
for (lit, mut plain) in shadowed(id, &params).into_iter().zip(shadowed(id, &params)) {
plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false));
let mut cast = 0;
art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some()));
assert!(cast > 0, "{id} {params}");
let built = solids_built(&plain, id);
assert!(built > 0, "{id}");
assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own");
}
}
}
}
/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids,
/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone.
#[test]
fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() {
for id in [EXTRUDE, INFLATE, ROTATE] {
for params in shadow_settings(id) {
for n in shadowed(id, &params) {
let (_, fx) = solid(&n.appearance.effects).unwrap();
let shapes = if is_container(&n) {
members(&n, "").unwrap()
} else {
let (path, rule) = profile(&n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
};
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
let p = crate::merged_params(&fx.id, &fx.params);
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
assert!(!alone.is_empty(), "{id} {params}");
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
}
}
}
}
+1 -1
View File
@@ -827,7 +827,7 @@ pub use docmenu::guide_indexes;
pub(crate) use edit::{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, key_location, location_in, location_keys};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub(crate) use vectorcraft_doc::range::parse_range;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
+7 -5
View File
@@ -23,7 +23,7 @@ use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::colorcmds::edit_if_changed;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::graph::{capture_series_object_opacity, series_groups_among};
use super::super::menucmds::whole_or;
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
use super::super::typecmd::refresh_bounds_of;
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
@@ -418,9 +418,11 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
/// again; the frontmost of them in a series sets them.
/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the
/// group.
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
let marks = series_children_in_paint_order(d, changed);
let mut marks = series_children_in_paint_order(d, changed);
marks.extend(series_groups_among(d, changed));
capture_series_object_opacity(d, &marks);
}
+7 -10
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
has_selection,
remove_breaks
),
@@ -821,9 +821,9 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
}
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
/// (each frame when `all`) comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> {
/// start of a frame between words of the frames on either side becomes a space. Each frame comes
/// with its own breaks, at its own bytes, its locked and hidden frames included.
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
// The breaks in story order, handed to the frames in one pass.
@@ -836,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(Node
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
own.push((at - start, space));
}
if all || d.is_editable(id) {
out.push((id, own));
}
out.push((id, own));
start = end;
}
out
@@ -859,7 +857,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
// Each type object with the breaks that go from it.
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false),
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
.into_iter()
.filter(|(id, ..)| d.is_editable(*id))
@@ -886,8 +884,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
};
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
// Every frame is among them, so each one keeps its breaks.
out.extend(story_cuts(d, &story, brk, true));
out.extend(story_cuts(d, &story, brk));
} else if let Some(t) = text_of(d, id) {
// `id` is type, so the story of its thread is the same for each of its frames.
partial.extend(thread);
+4 -1
View File
@@ -2,9 +2,11 @@
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
//! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner
//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]).
//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
mod banner;
mod nest;
mod stencil;
mod weed;
@@ -14,5 +16,6 @@ pub fn specs() -> Vec<CommandSpec> {
let mut v = stencil::specs();
v.extend(weed::specs());
v.extend(banner::specs());
v.extend(nest::specs());
v
}
@@ -0,0 +1,403 @@
//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs
//! the selected objects onto a sheet or a roll of material by their bounding boxes
//! (<https://en.wikipedia.org/wiki/Packing_problems>). The sheet is an
//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet
//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places
//! them better; they are never scaled or changed otherwise.
#[cfg(test)]
mod tests;
use std::collections::VecDeque;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::super::super::edit::selected_roots_to_transform;
use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns};
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or};
use crate::{Result, Session};
/// Nest Shapes' command.
pub const NEST: &str = "addon.cutting.nest";
/// The largest sheet width or height, in points.
const MAX_SIZE: f64 = 1_000_000.0;
/// The largest margin or spacing, in points.
const MAX_GAP: f64 = 100_000.0;
/// The most objects one run nests.
const MAX_SHAPES: usize = 10_000;
/// How far a box may reach past the sheet's edge and still fit (rounding).
const EPS: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cutting.nest",
"Nest Shapes…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}",
has_selection,
nest
)]
}
/// The length `p` gives for `key`, from 0 to `max`, or `default`.
fn length(p: &Value, key: &str, default: f64, max: f64) -> Result<f64> {
match length_given(p, key, NEST)? {
None => Ok(default),
Some(v) if (0.0..=max).contains(&v) => Ok(v),
Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))),
}
}
/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Span {
x: f64,
w: f64,
y: f64,
}
/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep
/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top.
struct Skyline {
spans: Vec<Span>,
width: f64,
height: f64,
}
impl Skyline {
fn new(width: f64, height: f64) -> Self {
Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height }
}
/// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it
/// allow, choosing the place where its bottom edge is highest and then furthest left. `None`
/// when it fits nowhere. The spans under the box at each span are a window whose two ends only
/// move right, and `window` holds the indices in it whose depth no later span in it reaches, so
/// its front is the deepest: one call takes time in proportion to the number of spans.
fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> {
let mut best: Option<(f64, f64)> = None;
let mut window: VecDeque<usize> = VecDeque::new();
let mut end = 0;
for (i, s) in self.spans.iter().enumerate() {
if s.x + w > self.width + EPS {
break;
}
while window.front().is_some_and(|&j| j < i) {
window.pop_front();
}
end = end.max(i);
while let Some(t) = self.spans.get(end)
&& (end == i || t.x < s.x + w - EPS)
{
while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) {
window.pop_back();
}
window.push_back(end);
end += 1;
}
let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0));
if y + h > self.height + EPS {
continue;
}
// The box is `h` tall at every place, so the place with the highest bottom edge is the
// place with the highest top edge.
if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) {
best = Some((s.x, y));
}
}
best
}
/// Fills the skyline down to `y + h` from `x` across `w`.
fn place(&mut self, x: f64, y: f64, w: f64, h: f64) {
if w <= 0.0 {
return;
}
let end = x + w;
let mut out = Vec::with_capacity(self.spans.len() + 2);
let mut added = false;
for s in &self.spans {
let s_end = s.x + s.w;
if s_end <= x || s.x >= end {
out.push(*s);
continue;
}
if s.x < x {
out.push(Span { x: s.x, w: x - s.x, y: s.y });
}
if !added {
out.push(Span { x, w, y: y + h });
added = true;
}
if s_end > end {
out.push(Span { x: end, w: s_end - end, y: s.y });
}
}
// Neighbors filled to the same depth are one span.
let mut merged: Vec<Span> = Vec::with_capacity(out.len());
for s in out {
match merged.last_mut() {
Some(l) if l.y == s.y => l.w = s.x + s.w - l.x,
_ => merged.push(s),
}
}
self.spans = merged;
}
}
/// One box to pack: its width and height as it stands, and when it may turn, as it is turned.
type Sizes = ((f64, f64), Option<(f64, f64)>);
/// The side a box is ordered by: its height, or its longest side when it may turn.
fn lead(b: &Sizes) -> (f64, f64) {
let ((w, h), turned) = *b;
if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) }
}
/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may
/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`]
/// puts it, turned when that puts its bottom edge higher (then further left), or when only the
/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box
/// that does not fit.
fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec<Option<(f64, f64, bool)>> {
let mut order: Vec<usize> = (0..boxes.len()).collect();
order.sort_by(|&a, &b| {
let (la, lb) = (lead(&boxes[a]), lead(&boxes[b]));
lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1))
});
let mut sky = Skyline::new(width, height);
let mut at = vec![None; boxes.len()];
for i in order {
let Some(&((w, h), turned)) = boxes.get(i) else { continue };
let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h));
if let Some((tw, th)) = turned
&& let Some((x, y)) = sky.find(tw, th)
{
let better = best.is_none_or(|(bx, by, _, _, bh)| {
let (was, now) = (by + bh, y + th);
now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS)
});
if better {
best = Some((x, y, true, tw, th));
}
}
if let Some((x, y, t, bw, bh)) = best {
sky.place(x, y, bw, bh);
if let Some(slot) = at.get_mut(i) {
*slot = Some((x, y, t));
}
}
}
at
}
/// A quarter turn clockwise on the page about `c`.
fn quarter_turn(c: Point) -> Affine {
Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2())
}
fn finite(r: &Rect) -> bool {
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())
}
/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects
/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows
/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds.
fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option<Rect> {
let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?;
if !preview {
return Some(b);
}
match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) {
Some(r) => Some(b.union(r)),
None => Some(b),
}
}
/// Whether `id` is a path of a pixel-aligned compound path.
fn in_aligned_compound(d: &Document, id: NodeId) -> bool {
d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned)
}
/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or
/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned
/// compound path.
fn snaps(d: &Document, id: NodeId) -> bool {
if in_aligned_compound(d, id) {
return true;
}
let mut stack: Vec<&Node> = d.node(id).into_iter().collect();
while let Some(n) = stack.pop() {
if n.extras().pixel_aligned {
return true;
}
stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c));
if let Some(m) = n.extras().mask.as_ref()
&& m.linked
{
stack.push(&*m.art);
}
}
false
}
fn nest(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &["patterns"], NEST)?;
let roll = switch_or(p, "roll", false, NEST)?;
let width = length(p, "width", 0.0, MAX_SIZE)?;
let height = length(p, "height", 0.0, MAX_SIZE)?;
let margin = length(p, "margin", 18.0, MAX_GAP)?;
let spacing = length(p, "spacing", 9.0, MAX_GAP)?;
let turn = switch_or(p, "rotate", false, NEST)?;
let preview = switch_or(p, "usePreviewBounds", true, NEST)?;
let named = match p.get("artboard") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?),
};
// A path of a compound path selected on its own moves without the rest of the compound path.
let ids = selected_roots_to_transform(s)?;
if ids.len() > MAX_SHAPES {
return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest")));
}
// Objects without a finite box (an empty group, empty type) are left where they are and
// listed as `skipped`.
let mut skipped = vec![];
let (items, board): (Vec<(NodeId, Rect)>, Rect) = {
let d = &s.doc()?.doc;
let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len());
for id in &ids {
match measure(d, *id, preview) {
Some(r) => items.push((*id, r)),
None => skipped.push(id.0),
}
}
let board = match named {
Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect,
None => {
let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b));
let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0);
d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect
}
};
(items, board)
};
if items.is_empty() {
return Err(bad(NEST, "the selection has nothing to nest"));
}
let sheet_w = if width > 0.0 { width } else { board.width() };
let sheet_h = if roll {
f64::INFINITY
} else if height > 0.0 {
height
} else {
board.height()
};
// Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than
// the room inside the margins, so the spacing falls between boxes and not at the far edges.
let room_w = sheet_w - 2.0 * margin;
let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin };
if room_w <= 0.0 || room_h <= 0.0 {
return Err(bad(NEST, "the margin leaves no room on the sheet"));
}
let all: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
let grid: Vec<bool> = {
let d = &s.doc()?.doc;
all.iter().map(|id| snaps(d, *id)).collect()
};
let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() };
// With `rotate`, each object is turned in a copy of the document and measured there, so the
// box packed for a turned object is the box its turned strokes and effects take. A path of a
// pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path
// again, which would move the compound's other paths away from where they were measured.
let turned: Vec<Option<(Affine, Rect)>> = if turn {
let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc);
let xfs: Vec<Option<Affine>> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect();
for ((id, _), xf) in items.iter().zip(&xfs) {
if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) {
transform_node(n, *xf, sc, true);
}
}
items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect()
} else {
vec![None; items.len()]
};
// An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the
// snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding.
let slack = |g: bool| if g { 1.0 } else { 0.0 };
let boxes: Vec<Sizes> = items
.iter()
.zip(&turned)
.zip(&grid)
.map(|(((_, r), t), g)| {
let pad = spacing + slack(*g);
((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad)))
})
.collect();
let at = pack(&boxes, room_w + spacing, room_h + spacing);
let origin = Vec2::new(board.x0 + margin, board.y0 + margin);
// The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an
// object on the pixel grid, so it moves at most 1 pt further right and down, into its slack.
let shift = |b: &Rect, to: Vec2, g: bool| {
let v = Vec2::new(to.x - b.x0, to.y - b.y0);
if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v }
};
// Each move: the quarter turn first, when the object turns, then the shift.
let mut moves: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
let mut aside: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
let mut unplaced = vec![];
let mut rotated = vec![];
let mut bottom = 0.0_f64;
// Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge
// and from each other, so that no object placed on the sheet covers them.
let aside_x = board.x0 + sheet_w + spacing;
let mut aside_y = board.y0;
for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) {
match (spot, t) {
(Some((x, y, true)), Some((xf, q))) => {
let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g);
moves.push((*id, Some(*xf), dv));
rotated.push(id.0);
bottom = bottom.max(q.y1 + dv.y - origin.y);
}
(Some((x, y, _)), _) => {
let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g);
moves.push((*id, None, dv));
bottom = bottom.max(r.y1 + dv.y - origin.y);
}
(None, _) => {
aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g)));
aside_y += r.height() + spacing + slack(*g);
unplaced.push(id.0);
}
}
}
if moves.is_empty() {
return Err(bad(NEST, "no selected object fits on the sheet"));
}
moves.extend(aside);
let length = 2.0 * margin + bottom;
let placed = moves.len() - unplaced.len();
let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length });
if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) {
return Ok(result);
}
s.edit("Nest Shapes", |d, _| {
for (id, xf, dv) in &moves {
// The turn is the one the object was measured with in the copy, and the shift after it
// is whole points for an object on the pixel grid.
for step in xf.iter().copied().chain([Affine::translate(*dv)]) {
if let Some(n) = d.node_mut(*id) {
transform_node(n, step, sc, true);
}
keep_compound_aligned(d, *id, sc);
}
}
Ok(())
})?;
Ok(result)
}
@@ -0,0 +1,433 @@
//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll.
use serde_json::{Value, json};
use vectorcraft_geom::Rect;
use super::{Skyline, pack};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
fn bounds(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn overlap(a: Rect, b: Rect) -> bool {
a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9
}
#[test]
fn boxes_pack_tallest_first_from_the_top_left() {
// 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20
// one is too wide for the 40 pt beside the first box, so it goes below the first box.
let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]);
}
#[test]
fn a_box_that_does_not_fit_is_left_out() {
let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0);
assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]);
}
/// Boxes that keep their orientation.
fn fixed(b: &[(f64, f64)]) -> Vec<super::Sizes> {
b.iter().map(|&s| (s, None)).collect()
}
/// Boxes that may turn a quarter.
fn turning(b: &[(f64, f64)]) -> Vec<super::Sizes> {
b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect()
}
#[test]
fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() {
// A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip
// turned, as 10 × 120.
let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]);
// Without turning, the 120 pt wide box is left out and the other stands up.
let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
assert_eq!(at, vec![Some((0.0, 0.0, false)), None]);
// A square box is never turned: turned, it is no better.
let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0);
assert_eq!(at, vec![Some((0.0, 0.0, false))]);
}
#[test]
fn the_skyline_fills_and_merges_spans() {
let mut sky = Skyline::new(100.0, f64::INFINITY);
sky.place(0.0, 0.0, 30.0, 10.0);
sky.place(30.0, 0.0, 30.0, 10.0);
assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans);
assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top");
assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0)));
}
#[test]
fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() {
let mut s = session();
let ids: Vec<NodeId> = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect();
select(&mut s, &ids);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(r["placed"], json!(6));
assert_eq!(r["unplaced"], json!([]));
let boxes: Vec<Rect> = ids.iter().map(|id| bounds(&s, *id)).collect();
for (i, a) in boxes.iter().enumerate() {
assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins");
assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized");
for b in &boxes[i + 1..] {
assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart");
}
}
// The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide
// boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below
// the 110 pt tall box at the right, where its bottom edge is highest.
assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0));
assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5);
assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0));
assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0));
}
#[test]
fn objects_that_do_not_fit_go_beside_the_sheet() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0);
let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0);
let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0);
select(&mut s, &[a, b, big]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(1));
assert_eq!(r["unplaced"], json!([b.0, big.0]));
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0));
// A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart.
assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0));
assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0));
}
#[test]
fn the_column_beside_the_sheet_is_in_stacking_order() {
let mut s = session();
let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0);
let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0);
let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0);
// Selected front first: the column still starts with the object at the back.
select(&mut s, &[front, small, back]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
assert_eq!(r["unplaced"], json!([back.0, front.0]));
assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0));
assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0));
}
#[test]
fn objects_without_bounds_are_skipped_and_listed() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
let layer = s.doc().unwrap().doc.parent_of(a);
let empty = s
.edit("empty group", |d, _| {
let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false });
Ok(d.insert(layer, usize::MAX, g).unwrap())
})
.unwrap();
select(&mut s, &[a, empty]);
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0])));
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0));
}
#[test]
fn the_sheet_is_the_artboard_under_the_center_of_the_selection() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0);
let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0);
select(&mut s, &[a, b]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first");
assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0));
}
#[test]
fn rotate_turns_clockwise() {
let mut s = session();
// A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the
// top-left corner goes to the top-right.
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0);
select(&mut s, &[long, mark]);
s.execute("object.group", &json!({})).unwrap();
let r = s
.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}))
.unwrap();
assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1));
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0));
assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right");
}
#[test]
fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() {
let mut s = session();
let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0);
let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0);
select(&mut s, &[outer, hole]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.setPixelAligned", &json!({})).unwrap();
select(&mut s, &[hole]);
// The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation.
let r =
s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}));
let e = r.unwrap_err().to_string();
assert!(e.contains("no selected object fits"), "{e}");
}
/// [`Skyline::find`] as a search of every span and every span under the box.
fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> {
let mut best: Option<(f64, f64)> = None;
for (i, s) in sky.spans.iter().enumerate() {
if s.x + w > sky.width + 1e-9 {
break;
}
let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y));
if y + h > sky.height + 1e-9 {
continue;
}
if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) {
best = Some((s.x, y));
}
}
best
}
#[test]
fn find_matches_a_search_of_every_span() {
// A fixed pseudo-random sequence of boxes, each placed where `find` puts it.
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
let mut next = |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % n) as f64 + 1.0
};
let mut sky = Skyline::new(200.0, 400.0);
for _ in 0..400 {
let (w, h) = (next(60), next(30));
let got = sky.find(w, h);
assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans);
if let Some((x, y)) = got {
sky.place(x, y, w, h);
}
}
}
#[test]
fn an_object_that_does_not_fit_is_not_covered_by_the_others() {
let mut s = session();
// The wide object sits on the sheet and does not fit; the small one must not land on it.
let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0);
let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
select(&mut s, &[wide, small]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small));
}
#[test]
fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0);
select(&mut s, &[a, b]);
s.execute("object.setPixelAligned", &json!({})).unwrap();
let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0);
assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b)));
s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}");
assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}");
assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}");
assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}");
}
#[test]
fn preview_bounds_take_in_a_drop_shadow() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap();
select(&mut s, &[a, b]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap();
assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}");
let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb);
assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}");
}
#[test]
fn a_roll_has_no_end() {
let mut s = session();
let ids: Vec<NodeId> = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect();
select(&mut s, &ids);
let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap();
assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([])));
let mut tops: Vec<f64> = ids.iter().map(|id| bounds(&s, *id).y0).collect();
tops.sort_by(f64::total_cmp);
assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll");
assert_eq!(r["length"], json!(2040.0));
}
#[test]
fn width_and_height_set_the_sheet_from_the_artboard_corner() {
let mut s = session();
let ids: Vec<NodeId> = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect();
select(&mut s, &ids);
let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(3));
for id in &ids {
let b = bounds(&s, *id);
assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}");
}
}
#[test]
fn preview_bounds_keep_strokes_apart() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet");
assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap");
}
#[test]
fn a_selection_already_nested_adds_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0);
select(&mut s, &[a]);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap();
assert_eq!(r["placed"], json!(1));
assert_eq!(steps(&s), n, "nothing moved");
}
#[test]
fn bad_params_are_refused_and_change_nothing() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
select(&mut s, &[a]);
let n = steps(&s);
let bad: [(Value, &str); 10] = [
(json!({"rotate": 1}), "`rotate` must be true or false"),
(json!({"width": -1}), "`width` must be from 0"),
(json!({"height": 2e6}), "`height` must be from 0"),
(json!({"margin": "x"}), "`margin` must be a number"),
(json!({"spacing": 1e6}), "`spacing` must be from 0"),
(json!({"roll": "yes"}), "`roll` must be true or false"),
(json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"),
(json!({"artboard": 3}), "there is no artboard 3"),
(json!({"artboard": -1}), "`artboard` must be"),
(json!({"margin": 400}), "the margin leaves no room"),
];
for (p, want) in bad {
let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string();
assert!(e.contains(want), "{p}: {e}");
}
let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string();
assert!(e.contains("no selected object fits"), "{e}");
let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string();
assert!(e.contains("`patterns` must be true or false"), "{e}");
assert_eq!(steps(&s), n, "a refused run changes nothing");
assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0));
}
#[test]
fn the_named_artboard_is_the_sheet() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
select(&mut s, &[a]);
s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0));
}
#[test]
fn rotate_turns_objects_a_quarter_to_fit_the_sheet() {
let mut s = session();
// On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up.
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0);
select(&mut s, &[long, small]);
let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false});
let r = s.execute("addon.cutting.nest", &p).unwrap();
assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit");
s.execute("edit.undo", &json!({})).unwrap();
let mut p = p;
p["rotate"] = json!(true);
let n = steps(&s);
let r = s.execute("addon.cutting.nest", &p).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0])));
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner");
// The 50 × 40 object stays as it is: turned, its bottom edge would be lower.
assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back");
}
#[test]
fn rotate_measures_the_turned_preview_bounds() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
select(&mut s, &[a]);
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap();
assert_eq!(r["rotated"], json!([a.0]));
assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet");
}
#[test]
fn a_compound_paths_path_selected_alone_moves_alone() {
let mut s = session();
let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0);
let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0);
select(&mut s, &[outer, hole]);
s.execute("object.compoundPath.make", &json!({})).unwrap();
select(&mut s, &[hole]);
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved");
assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed");
}
#[test]
fn a_group_is_nested_as_one_object() {
let mut s = session();
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0);
select(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0)));
}
+6 -4
View File
@@ -498,8 +498,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
}
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the
/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool {
for id in groups {
if let Some(n) = d.node_mut(*id) {
clear(n);
@@ -507,6 +508,7 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
n.extras_mut().graphic_style = None;
}
}
super::graph::capture_series_object_opacity(d, groups)
}
/// [`whole_targets`] of `cmd`, which needs at least one.
@@ -943,7 +945,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
}
clear_stood_for(d, &group);
let forgot = clear_stood_for(d, &group);
for id in &cleared {
if let Some(n) = d.node_mut(*id) {
clear(n);
@@ -961,7 +963,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
let labels = super::graph::capture_label_rows(d, &changed);
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels))
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
+20 -4
View File
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Asset Export Settings",
[],
None,
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
has_doc,
settings_set
),
@@ -435,19 +435,35 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "assets.settings.set";
let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?;
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") {
return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", "))));
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) {
return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", "))));
}
for k in ["subfolders", "openLocation"] {
if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) {
return Err(bad(C, format!("`{k}` is true or false")));
}
}
let mut settings = s.doc()?.doc.export_settings.clone();
let mut given = o.clone();
// Create Sub-folders is on for a document without settings (Export for Screens opens so), and
// Open Location after Export set on its own leaves it on.
if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) {
given.insert("subfolders".into(), json!(true));
}
if let Some(name) = given.remove("exportPreset") {
let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?;
with_screen_export_preset(s, C, &mut settings, name)?;
}
// Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice.
// Turned off on its own (the panel menu), it also ends a remembered folder per format or item;
// with an export preset, that preset's folder per format or item stays.
let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string);
let sorted = folders.as_deref().is_some_and(|f| f != "none");
match given.get("subfolders").and_then(Value::as_bool) {
Some(true) => _ = settings.insert("folders".into(), json!("rows")),
Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")),
Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => {
_ = settings.insert("folders".into(), json!("none"))
}
_ => {}
}
overlay(&mut settings, &given);
+1 -1
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Shape Builder",
[],
None,
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
has_selection_or_ids,
sb_merge
),
@@ -63,7 +63,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
&& let Some(&q) = pts.first()
&& let Some((i, run)) = map.stroke_at(&outlines, q, tol)
&& let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i))
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn))
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && leaf.appearance.has_drawn_fill(), b::outline_snap(drawn))
&& rest.length() > b::outline_snap(drawn)
{
// The path keeps the rest of it, and a copy of it with the run under the click goes
@@ -70,13 +70,26 @@ pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(_) => Some(switch_or(p, "visible", false, C)?),
};
let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?;
// A hidden grid holds no plane for Automatic Plane Positioning.
let g = silent(s, |g| {
g.visible = want.unwrap_or(!g.visible);
if !g.visible {
g.inferred = None;
}
})?;
Ok(json!({ "visible": g.visible }))
}
pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result<Value> {
let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?;
silent(s, |g| g.plane = plane)?;
// The new active plane passes through the point Automatic Plane Positioning holds, unless no
// plane is active or that would put the plane behind the viewer.
silent(s, |g| {
g.plane = plane;
if g.inferred.is_some() && (plane == Plane::None || g.validate().is_err()) {
g.inferred = None;
}
})?;
Ok(json!({ "plane": plane.id() }))
}
@@ -138,6 +151,9 @@ pub(super) fn attach(s: &mut Session, p: &Value) -> Result<Value> {
store_grid(d, &g);
Ok(())
})?;
if !ids.is_empty() {
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
}
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "plane": plane.id() }))
}
@@ -205,8 +221,13 @@ fn persp_edit(
return Err(EngineError::Other("select the objects to transform in perspective".into()));
}
let mut g = grid_of(&s.doc()?.doc);
// An object not in perspective yet attaches to `fallback` where that plane is now.
let attaches = {
let d = &s.doc()?.doc;
fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none()))
};
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None };
s.edit(label, |d, sel| {
let edited = s.edit(label, |d, sel| {
g.adopt_stored_attachments(d);
let targets = match &kept {
// The document becomes the snapshot with the kept copies, not yet mapped, and the loop
@@ -236,7 +257,11 @@ fn persp_edit(
}
store_grid(d, &g);
Ok((targets, first))
})
})?;
if let Some(plane) = attaches {
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
}
Ok(edited)
}
/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one
@@ -430,6 +455,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["offset", "by"], C)?;
let old = grid_of(&s.doc()?.doc);
let plane = plane_param(&old, p, C)?;
// A plane that Automatic Plane Positioning holds moves from where it is held, and the move
// places it there for good: the moved grid holds no plane (undoing the move holds it again).
let held = old.inferred;
let from = old.offset(plane);
let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) {
(Some(o), _) => o,
@@ -440,7 +468,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(objects, "none" | "move" | "copy") {
return Err(bad(C, "objects must be none, move or copy"));
}
let mut g = old.clone();
let mut g = PerspectiveGrid { inferred: None, ..old.clone() };
g.set_offset(plane, to);
g.validate().map_err(|e| bad(C, e))?;
let label = match objects {
@@ -458,8 +486,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
.collect()
};
// A plane moved to where it is, with its objects or without them, moves nothing: when the
// document holds the grid already, the document and its undo history stay as they are.
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) {
// document holds the grid already, the document and its undo history stay as they are (a
// plane held where it was placed stays held).
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) {
let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] };
return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
}
@@ -507,12 +536,19 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
let mut g = grid_of(&st.doc);
let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?;
// The moved grid holds no plane for Automatic Plane Positioning (undoing the move holds it
// again).
let held = g.inferred.take();
g.set_offset(plane, depth);
g.plane = plane;
g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?;
// When the plane is at the object and active already, and the document holds that grid, the
// document and its undo history stay as they are.
if grid_kept(&st.doc, &g) {
// document and its undo history stay as they are; a plane held elsewhere goes back to that
// place as view state.
if grid_kept(&st.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) {
if held.is_some() {
silent(s, |g| g.inferred = None)?;
}
return Ok(json!({ "plane": plane.id(), "offset": depth }));
}
s.edit("Move Plane to Match Object", |d, _| {
@@ -573,6 +609,7 @@ pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result<Value> {
st.history.recost_last(&st.doc);
}
res?;
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
Ok(json!({ "id": id.0, "plane": plane.id() }))
}
+10 -8
View File
@@ -265,25 +265,27 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
/// first such path.
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
/// the document as it is and stops at the first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let first = t.first_style();
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map(|r| &r.style);
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
let style = t.runs.get(run).map_or(&first, |r| &r.style);
if !matches!(style.fill, Paint::Gradient(_)) {
return false;
}
let path = PathData::from_bezpath(outline).transformed(t.xf);
let path = PathData::from_bezpath(outline);
if path.is_empty() {
return false;
}
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece)
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
File diff suppressed because one or more lines are too long
+16 -3
View File
@@ -678,15 +678,28 @@ impl ReadFile {
/// ([`super::importer`]).
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
let opts = LoadOptions::from_params("document.open", p)?;
let mut loaded = match super::importer::pick(name, bytes, p)? {
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
None => load_with(name, bytes, &opts)?,
let mut loaded = if opts.link_pages {
linked_pages(name, bytes, path.as_deref(), &opts)?
} else {
match super::importer::pick(name, bytes, p)? {
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
None => load_with(name, bytes, &opts)?,
}
};
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut loaded.doc);
Ok(ReadFile { loaded, opts, path, links })
}
/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents
/// linked to them ([`super::pdfimport::linked_pages`]), named after the file.
fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions) -> Result<Loaded> {
let (mut doc, warnings) = super::pdfimport::linked_pages(name, bytes, path, opts)?;
doc.title = file_name(name);
let format = detect(name, bytes).ok_or_else(|| err(format!("can't open `{}`: not a PDF", file_name(name))))?;
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
}
/// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active
/// document → `document.open`'s result.
pub fn open_read(s: &mut Session, file: ReadFile) -> Result<Value> {
+95 -6
View File
@@ -2,11 +2,15 @@
//! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages,
//! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{ColorMode, Document};
use vectorcraft_doc::{Artboard, ColorMode, Document, LayerColor, LinkInfo, Node, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs};
use super::super::colormgmt::Grays;
use super::super::place::document;
use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param};
use super::{err, source};
@@ -47,6 +51,9 @@ pub struct LoadOptions {
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
pub native: bool,
/// Each page of a PDF opens as a placed document linked to that page of its file, on an
/// artboard of its own, instead of as editable art (`linkPages`; see [`linked_pages`]).
pub link_pages: bool,
}
impl Default for LoadOptions {
@@ -65,6 +72,7 @@ impl Default for LoadOptions {
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
native: true,
link_pages: false,
}
}
}
@@ -74,8 +82,8 @@ impl LoadOptions {
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
/// import options).
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
None => None,
@@ -115,6 +123,10 @@ impl LoadOptions {
.and_then(vectorcraft_eps::NameEncoding::from_label)
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
};
let link_pages = match p.get("linkPages").filter(|v| !v.is_null()) {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self {
pages,
@@ -130,14 +142,15 @@ impl LoadOptions {
trust_editing_data,
legacy_names,
native: true,
link_pages,
})
}
/// Does the document read only part of the file, or read it differently (a page range, another
/// box, a password, without its hidden layers, without the VectorCraft document it carries)?
/// Writing it back would lose the rest, so Save doesn't (it asks for a name).
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
pub fn is_partial(&self) -> bool {
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
@@ -201,6 +214,82 @@ 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() }
}
/// `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
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left
/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
/// path, for any other file, with a password (a linked page is read again without one), with
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
/// [`document::MAX_FILE`] → the document and the notes of reading its pages.
pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
const C: &str = "document.open";
let file = super::file_name(name);
if !document::is_pdf(name, bytes) {
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
}
let path = path.ok_or_else(|| bad(C, "linkPages needs the file's path: linked pages are read from it"))?;
if o.password.is_some() {
return Err(bad(C, "linkPages can't open a file with a password: linked pages are read again without it"));
}
if o.text_as != TextAs::Text {
return Err(bad(C, "linkPages can't be used with textAs: outlines: linked pages show the file's own type"));
}
if bytes.len() > document::MAX_FILE {
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
}
let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count();
let picked = match &o.pages {
None => (0..count).collect(),
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
};
let bounding = o.crop == CropTo::Bounding;
let mut doc = Document::new(1.0, 1.0);
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
doc.artboards.clear();
doc.layers.clear();
let link = crate::cmd::links::link_info(path, bytes);
let gap = ImportOptions::default().artboard_gap;
// Every page's object keeps the same one copy of the file.
let shared = Arc::new(bytes.to_vec());
let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::<String>::new(), 0);
for (i, &index) in picked.iter().enumerate() {
let page = index as u32 + 1;
let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?;
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
if let NodeKind::PlacedDocument(p) = &mut node.kind {
p.xf = Affine::translate((x, 0.0));
}
node.name = Some(file.clone());
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
children.push(Arc::new(node));
}
doc.layers.push(Arc::new(layer));
let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height());
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
x = rect.x1 + gap;
for w in s.warnings {
if !warnings.contains(&w) {
warnings.push(w);
}
}
}
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
if cmyk_pages * 2 > picked.len() {
doc.color_mode = ColorMode::Cmyk;
let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model());
(doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into());
}
if let Some(mode) = o.color_mode.filter(|m| *m != doc.color_mode) {
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, o.grays);
}
Ok((doc, warnings))
}
const INFO: &str = "document.pdfInfo";
/// `document.pdfInfo`.
+9 -152
View File
@@ -3,26 +3,22 @@
//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF
//! resolution tags. Place
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
//! as a `pHYs` chunk.
//! as a `pHYs` chunk. The formats the image decoder reads are read by [`vectorcraft_doc::ppi`].
pub(super) use vectorcraft_doc::ppi::png_chunks;
use vectorcraft_doc::ppi::tiff;
pub use vectorcraft_doc::ppi::with_png_resolution;
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// The resolution a file declares as (horizontal, vertical) ppi; `None` when it declares none (or
/// only an aspect ratio).
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if super::jxlread::is_jxl(bytes) {
if vectorcraft_doc::ppi::reads(bytes) {
return vectorcraft_doc::ppi::resolution(bytes);
}
let r = if super::jxlread::is_jxl(bytes) {
jxl(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else if super::psdread::is_psd(bytes) {
super::psdread::resolution(bytes)
} else if super::pcxread::is_pcx(bytes) {
@@ -82,121 +78,9 @@ fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub(super) fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit.
fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = b.get(at + 8..at + 8 + len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn jxl(b: &[u8]) -> Option<(f64, f64)> {
if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) {
@@ -224,33 +108,6 @@ fn jxl(b: &[u8]) -> Option<(f64, f64)> {
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = vectorcraft_render::encode::png::phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
+4 -1
View File
@@ -865,7 +865,8 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
}
/// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph
/// series, for the graph's next redraw. The edited member is left to the edit's own command.
/// series, and the transparency a series group among them took, for the graph's next redraw. The edited member is left to
/// the edit's own command.
fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
let mut taken = vec![];
for id in edited {
@@ -874,6 +875,8 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
}
}
super::appearance::capture_series_changes(before, d, &taken);
let groups = super::graph::series_groups_among(d, &taken);
super::graph::capture_series_object_opacity(d, &groups);
}
/// The outlines of the members of the active document's Global Edit that are not selected, hold
+2 -1
View File
@@ -40,6 +40,7 @@ pub use commands::specs;
pub(crate) use data::apply_csv;
#[cfg(test)]
use data::{fmt_value, parse_csv, to_csv};
pub(crate) use edit::{graphs_holding, keep_placed};
#[cfg(test)]
use generate::generate;
#[cfg(test)]
@@ -47,7 +48,7 @@ use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in,
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
series_object_opacity_differs, shown_paint,
};
+56 -2
View File
@@ -1,3 +1,5 @@
use vectorcraft_doc::graph::art_bounds;
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
use super::data::apply_data;
use super::generate::{children_bounds, generate};
@@ -17,11 +19,62 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
}
}
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
/// bounds with a width and a height, or has no art without type now.
fn measured(n: &Node) -> Option<(Rect, Rect)> {
let kept = n.extras().graph.as_deref()?;
let c = n.children()?;
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
art.or_else(|| kept.placed.zip(children_bounds(c)))
}
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
/// `None` when `from` has no width or no height.
fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
if from.width() <= 1e-9 || from.height() <= 1e-9 {
return None;
}
let (sx, sy) = (to.width() / from.width(), to.height() / from.height());
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
}
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
for id in ids {
let Some(chain) = d.ancestry(*id) else { continue };
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
let children = d.node(gid).and_then(Node::children);
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
}
out
}
/// After an edit that changed the art of `graphs` (from [`graphs_holding`]) without moving them, set the bounds each
/// keeps so that its next redraw measures the same move or scale as it would have before the edit.
pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option<Rect>, Option<Rect>)]) {
for &(gid, art_was, whole_was) in graphs {
let Some(n) = d.node(gid) else { continue };
let children = n.children();
let (art_now, whole_now) = (children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)));
let Some(spec) = d.node_mut(gid).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
if let (Some(placed), Some(was), Some(now)) = (spec.placed_art, art_was, art_now) {
spec.placed_art = carried(now, was, placed).or(spec.placed_art);
}
if let (Some(placed), Some(was), Some(now)) = (spec.placed, whole_was, whole_now) {
spec.placed = carried(now, was, placed).or(spec.placed);
}
}
}
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
/// generation, which is recorded in the spec's `placed` bounds).
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
if let (Some(placed), Some(now)) = (n.extras().graph.as_ref().and_then(|g| g.placed), n.children().and_then(|c| children_bounds(c)))
if let Some((placed, now)) = measured(n)
&& placed.width() > 1e-9
&& placed.height() > 1e-9
&& (placed.x0 - now.x0).abs() + (placed.y0 - now.y0).abs() + (placed.x1 - now.x1).abs() + (placed.y1 - now.y1).abs() > 1e-6
@@ -33,6 +86,7 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
}
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
+2 -2
View File
@@ -6,7 +6,7 @@ use super::labels::{
recolour_text, runs, shadow_of,
};
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity};
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_group_opacity, with_series_opacity};
use super::{
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
};
@@ -1005,7 +1005,7 @@ impl<'a> Plot<'a> {
}
}
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)));
let grp = with_series_group_opacity(g, s, self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items))));
self.b.out.push(grp);
}
self.b.out.append(&mut self.on_top);
+89 -19
View File
@@ -475,15 +475,16 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
settle_series_paints(doc, before)
}
/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity
/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object
/// opacity or blend mode changed.
/// Copy the object transparency of generated series art just edited (`edited`) into what that series keeps: a path
/// directly in a series group sets the paths' object opacity and blend mode, and the series group itself sets the
/// group's opacity, blend mode, isolation, knockout and knockout shape. Called inside the same document edit, so both undo
/// together. Returns whether what a series keeps changed.
pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool {
let mut before = SeriesPaintsBefore::new();
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
// A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is.
if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index {
if look == ObjectOpacity::default() && spec.series_paints.len() <= index {
continue;
}
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
@@ -492,7 +493,12 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
}
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
(slot.opacity, slot.blend) = (opacity, blend);
if group {
(slot.group_opacity, slot.group_blend) = (look.opacity, look.blend);
(slot.group_isolate, slot.group_knockout, slot.group_knockout_shape) = (look.isolate, look.knockout, look.knockout_shape);
} else {
(slot.opacity, slot.blend) = (look.opacity, look.blend);
}
}
settle_series_paints(doc, before)
}
@@ -500,20 +506,50 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
/// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying
/// it.
pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool {
let mut after: HashMap<(NodeId, usize), (Option<f32>, Option<BlendMode>)> = HashMap::new();
let stored = |graph: NodeId, index: usize| {
let mut after: HashMap<(NodeId, usize, bool), ObjectOpacity> = HashMap::new();
let stored = |graph: NodeId, index: usize, group: bool| {
let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref());
spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend))
let slot = spec.and_then(|g| g.series_paints.get(index));
slot.map_or_else(ObjectOpacity::default, |slot| {
if group {
ObjectOpacity {
opacity: slot.group_opacity,
blend: slot.group_blend,
isolate: slot.group_isolate,
knockout: slot.group_knockout,
knockout_shape: slot.group_knockout_shape,
}
} else {
ObjectOpacity { opacity: slot.opacity, blend: slot.blend, ..ObjectOpacity::default() }
}
})
};
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
after.insert((graph, index), (opacity, blend));
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
after.insert((graph, index, group), look);
}
after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair)
after.into_iter().any(|((graph, index, group), look)| stored(graph, index, group) != look)
}
/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a
/// series group, in order.
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option<f32>, Option<BlendMode>)> {
/// The series groups among `ids`, for an edit that changes only what a group's transparency has beyond its opacity and
/// blend mode (isolation, knockout and knockout shape), which the graph keeps for series groups alone.
pub(crate) fn series_groups_among(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| n.extras().series_index.is_some())).collect()
}
/// An object's transparency as a graph keeps it: the object opacity and blend mode (None for 100% and Normal), and for a
/// series group its isolation, knockout (None for neutral) and knockout shape. Paths keep the first two only.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct ObjectOpacity {
opacity: Option<f32>,
blend: Option<BlendMode>,
isolate: bool,
knockout: Option<vectorcraft_doc::Knockout>,
knockout_shape: bool,
}
/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object
/// transparency of each of `edited` that is one of those, in order.
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> {
if edited.is_empty() {
return Vec::new();
}
@@ -524,14 +560,48 @@ fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, us
edited
.iter()
.filter_map(|id| {
// Only the paths the graph draws again, not the copy of a graph design.
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend)))
let r = members.get(id)?;
let group = r.group == *id;
// Only the series group and the paths the graph draws again, not the copy of a graph design.
let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?;
let mut look = ObjectOpacity {
opacity: (node.opacity < 1.0).then_some(node.opacity),
blend: (node.blend != BlendMode::Normal).then_some(node.blend),
..ObjectOpacity::default()
};
if group {
look.isolate = node.isolate;
look.knockout = (node.knockout != vectorcraft_doc::Knockout::Neutral).then_some(node.knockout);
look.knockout_shape = node.knockout_shape;
}
Some((r.graph, r.index, group, look))
})
.collect()
}
/// Series `i`'s group (`group`) with the object opacity, blend mode, isolation, knockout and knockout shape the graph
/// keeps for it. An opacity read from a file is held to 0..1, and one that is not a number is left out.
pub(super) fn with_series_group_opacity(g: &GraphSpec, i: usize, mut group: Arc<Node>) -> Arc<Node> {
let Some(slot) = g.series_paints.get(i) else { return group };
let opacity = slot.group_opacity.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
if opacity.is_none() && slot.group_blend.is_none() && !slot.group_isolate && slot.group_knockout.is_none() && !slot.group_knockout_shape {
return group;
}
let n = Arc::make_mut(&mut group);
if let Some(o) = opacity {
n.opacity = o;
}
if let Some(b) = slot.group_blend {
n.blend = b;
}
if let Some(k) = slot.group_knockout {
n.knockout = k;
}
n.isolate |= slot.group_isolate;
n.knockout_shape |= slot.group_knockout_shape;
group
}
/// Graph Data › Transpose row/column: categories become series and series categories.
pub(super) fn transpose(g: &mut GraphSpec) {
let cells = g.cells();
+367 -2
View File
@@ -923,6 +923,32 @@ fn what_global_edit_gives_the_marks_of_another_series_group_survives_regeneratio
assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == given));
}
/// With a whole series group picked and Global Edit on, the opacity and blend mode set on that group reach the other
/// series groups of the same form, and the graph stores them for those groups too.
#[test]
fn the_transparency_global_edit_gives_another_series_group_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
// Series without names draw no legend, so each series group holds only its columns, laid out like the other's.
let csv = ",,\nQ1,3,3\nQ2,5,5";
let made = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap();
let id = NodeId(made["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, other) = (series(&n, 0).id, series(&n, 1).id);
s.execute("object.isolate", &json!({"id": id.0})).unwrap();
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
let r = s.execute("select.globalEdit", &json!({})).unwrap();
assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}");
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40, "blend": "multiply"})).unwrap();
let g = s.doc().unwrap().doc.node(other).unwrap().clone();
assert_eq!((g.opacity, g.blend), (0.4, BlendMode::Multiply), "Global Edit reaches the other group");
let kept = spec(&s, id).series_paints[1].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply)));
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 1).0, (0.4, BlendMode::Multiply));
}
/// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of
/// the series again; Normal forgets it.
#[test]
@@ -2210,8 +2236,8 @@ fn appearance_commands_given_a_series_group_edit_its_marks() {
s.execute("edit.undo", &json!({})).unwrap();
let (rect, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap();
let was = spec(&s, id).series_paints;
s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap();
assert!(series_0_group(&s, id).1);
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity");
@@ -2433,10 +2459,10 @@ fn a_graphic_style_applied_to_a_series_group_styles_its_marks() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let (_, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null});
s.execute("transparency.set", &own).unwrap();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
let was = spec(&s, id).series_paints;
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal);
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap();
@@ -2513,6 +2539,161 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
}
/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it.
fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let g = series(&n, index);
((g.opacity, g.blend), g.children().unwrap().iter().map(|m| (m.opacity, m.blend)).collect())
}
/// An object opacity and blend mode set on a selected series group are kept by the graph for the group: the series group
/// has them after the graph is drawn again, the graph's data reads them back unchanged after it is written to JSON, its
/// paths and the other series stay opaque and Normal, setting them again records no step, 100% and Normal forget them,
/// and undo takes them back.
#[test]
fn an_opacity_and_blend_mode_on_a_series_group_survive_regeneration() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 40, "blend": "multiply"})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply)));
assert_eq!((kept.opacity, kept.blend), (None, None), "the paths keep their own");
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap();
assert_eq!(restored, spec(&s, id));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
let normal = (1.0, BlendMode::Normal);
let (own, paths) = group_transparency(&s, id, 0);
assert_eq!(own, (0.4, BlendMode::Multiply));
assert!(!paths.is_empty() && paths.iter().all(|t| *t == normal), "{paths:?}");
let (own, paths) = group_transparency(&s, id, 1);
assert_eq!(own, normal);
assert!(paths.iter().all(|t| *t == normal), "{paths:?}");
let (group, _) = series_0_group(&s, id);
let undo = s.doc().unwrap().history.undo.len();
s.execute("object.setProps", &json!({"id": group.0, "opacity": 40, "blend": "multiply"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already");
s.execute("object.setProps", &json!({"id": group.0, "opacity": 100, "blend": "normal"})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.group_opacity, kept.group_blend), (None, None));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"rows": [[2, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, normal);
for _ in 0..4 {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the edit and what the graph stored");
}
/// Commands that clear a series group's own opacity and blend mode also remove what the graph keeps for it: Clear
/// Appearance on the group, a graphic style applied to it and Move Appearance onto it.
#[test]
fn clearing_a_series_groups_opacity_forgets_what_the_graph_keeps() {
let kept = |s: &Session, id: NodeId| {
let slot = spec(s, id).series_paints[0].clone();
(slot.group_opacity, slot.group_blend)
};
let faded = (Some(0.5), Some(BlendMode::Screen));
let (mut s, id, _, _) = column_marks();
let (rect, _) = blue_style(&mut s, "Blue", false);
let (group, _) = series_0_group(&s, id);
s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap();
assert_eq!(kept(&s, id), faded);
let commands = [
("appearance.clear", json!({"ids": [group.0]})),
("graphicStyle.apply", json!({"name": "Blue", "ids": [group.0]})),
("appearance.transfer", json!({"source": rect.0, "target": group.0, "copy": true})),
];
for (cmd, params) in commands {
s.execute(cmd, &params).unwrap();
assert_eq!(kept(&s, id), (None, None), "{cmd}");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal), "{cmd}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(kept(&s, id), faded, "{cmd}");
}
}
/// Redefining a graphic style a series group is linked to clears the group's own opacity and blend mode, and removes
/// what the graph keeps for them.
#[test]
fn redefining_a_style_linked_to_a_series_group_forgets_its_kept_opacity() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
let (rect, _) = blue_style(&mut s, "Blue", false);
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
s.edit("Link", |d, _| {
let i = d.graphic_style_index("Blue").unwrap();
(d.graphic_styles[i].opacity, d.graphic_styles[i].blend) = (0.5, BlendMode::Screen);
let g = d.node_mut(group).unwrap();
g.appearance = style.appearance.clone().into();
(g.opacity, g.blend) = (0.5, BlendMode::Screen);
g.extras_mut().graphic_style = Some(style.id);
Ok(())
})
.unwrap();
s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap();
let slot = spec(&s, id).series_paints[0].clone();
assert_eq!((slot.group_opacity, slot.group_blend), (Some(0.5), Some(BlendMode::Screen)));
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, Some(style.id), "still linked");
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00"})).unwrap();
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
let slot = spec(&s, id).series_paints.first().cloned().unwrap_or_default();
assert_eq!((slot.group_opacity, slot.group_blend), (None, None));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal));
}
/// Isolate Blending, a knockout state and Knockout Shape set on a selected series group are kept by the graph for the
/// group, through the graph being drawn again; the other series' group stays as the graph draws it, and turning them off
/// forgets them.
#[test]
fn isolation_and_knockout_on_a_series_group_survive_regeneration() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("transparency.set", &json!({"isolate": true, "knockout": "off", "knockoutShape": true})).unwrap();
let slot = spec(&s, id).series_paints[0].clone();
assert_eq!((slot.group_isolate, slot.group_knockout, slot.group_knockout_shape), (true, Some(vectorcraft_doc::Knockout::Off), true));
assert_eq!((slot.group_opacity, slot.group_blend, slot.opacity, slot.blend), (None, None, None, None));
let undo = s.doc().unwrap().history.undo.len();
s.execute("object.setProps", &json!({"id": group.0, "isolate": true})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (g, other) = (series(&n, 0), series(&n, 1));
assert_eq!((g.isolate, g.knockout, g.knockout_shape), (true, vectorcraft_doc::Knockout::Off, true));
assert_eq!((other.isolate, other.knockout, other.knockout_shape), (false, vectorcraft_doc::Knockout::Neutral, false));
let (group, _) = series_0_group(&s, id);
s.execute("object.setProps", &json!({"id": group.0, "isolate": false, "knockout": "neutral", "knockoutShape": false})).unwrap();
assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "nothing is kept");
}
/// Randomize Opacity and Sort Objects given a series group keep the opacity they give it for the group.
#[test]
fn randomize_and_sort_opacity_on_a_series_group_are_kept() {
let (mut s, id, _, _) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [group.0], "min": 30, "max": 60, "seed": 7})).unwrap();
let given = s.doc().unwrap().doc.node(group).unwrap().opacity;
assert!(given < 1.0);
assert_eq!(spec(&s, id).series_paints[0].group_opacity, Some(given));
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
assert_eq!(group_transparency(&s, id, 0).0, (given, BlendMode::Normal));
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let (first, second) = (series(&n, 0).id, series(&n, 1).id);
s.execute("object.setProps", &json!({"id": second.0, "opacity": 80})).unwrap();
s.execute("addon.arrange.sort", &json!({"ids": [first.0, second.0], "by": "x", "apply": "opacity", "order": "descending"})).unwrap();
let d = &s.doc().unwrap().doc;
let (a, b) = (d.node(first).unwrap().opacity, d.node(second).unwrap().opacity);
assert_eq!((a, b), (0.8, given), "the opacities trade places");
let kept = &spec(&s, id).series_paints;
assert_eq!((kept[0].group_opacity, kept.get(1).and_then(|k| k.group_opacity)), ((a < 1.0).then_some(a), (b < 1.0).then_some(b)));
}
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
#[test]
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
@@ -5691,6 +5872,151 @@ fn formatting_one_label_keeps_that_kind_of_label() {
assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none());
}
/// Character and paragraph edits that resize a graph's labels leave the plot where it is when the graph is drawn
/// again, and a move or scale of the graph made after them is still followed.
#[test]
fn restyling_a_graphs_labels_leaves_the_plot_in_place() {
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let redraw = |s: &mut Session, id: NodeId| s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after a size change to every label");
let c = text_id(&s, id, "Axes", "Q2");
s.execute("text.setFormat", &json!({"ids": [c.0], "leftIndent": 20})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after an indent on the category labels");
let l = text_id(&s, id, "Legend", "2025");
s.execute("text.setStyle", &json!({"ids": [l.0], "size": 4})).unwrap();
redraw(&mut s, id);
assert_eq!(spec(&s, id).rect, rect, "after a smaller size on the legend labels");
// A move and a scale of the whole graph still carry the plot with them.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
redraw(&mut s, id);
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [moved.x0, moved.y0]})).unwrap();
redraw(&mut s, id);
let scaled = spec(&s, id).rect;
assert!((scaled.width() - 2.0 * rect.width()).abs() < 1e-6 && (scaled.height() - rect.height()).abs() < 1e-6, "{scaled:?}");
assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}");
}
/// Moving one label of a graph on its own leaves the plot where it is when the graph is drawn again.
#[test]
fn moving_one_label_leaves_the_plot_in_place() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
for (grp, text) in [("Legend", "2025"), ("Axes", "Q2")] {
let l = text_id(&s, id, grp, text);
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
s.execute("object.move", &json!({"dx": 120, "dy": 60})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "after moving {text}");
}
}
/// Label edits leave the plot in place in graphs whose legend swatches follow the size of the labels at the next
/// drawing: a legend across the top, a legend after a right value axis, and legend labels of several lines. A move of
/// the graph made after them is still followed.
#[test]
fn restyling_the_labels_of_a_graph_whose_legend_follows_them_leaves_the_plot_in_place() {
let csv = ",North|East|Coast,South|West,Inland|Hills|Lakes|Plains\nQ1,3,2,4\nQ2,5,4,1\nQ3,-1,6,2";
for options in [json!({"legendAcrossTop": true}), json!({"valueAxis": "right"}), json!({"valueAxis": "both"}), json!({})] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setType", &options).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let rect = spec(&s, id).rect;
for size in [16, 5] {
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": size})).unwrap();
for _ in 0..2 {
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "{options}: labels at {size} pt");
}
}
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 30, "dy": 20})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 20.0)).abs() < 1e-6, "{options}: {moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{options}: {moved:?}");
}
}
/// Outlining a graph's labels leaves the plot where it is when the graph is drawn again, and a move of the graph made
/// before them is still followed.
#[test]
fn outlining_a_graphs_labels_leaves_the_plot_in_place() {
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q2").0, text_id(&s, id, "Legend", "2025").0]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
assert_eq!(spec(&s, id).rect, rect, "after outlining labels");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 30, "dy": 15})).unwrap();
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0, text_id(&s, id, "Legend", "2024").0]})).unwrap();
s.execute("type.createOutlines", &json!({})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}");
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
}
/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art.
#[test]
fn a_graph_whose_art_without_type_kept_no_width_still_follows_a_move() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let mut flat = spec(&s, id);
let art = flat.placed_art.unwrap();
flat.placed_art = Some(vectorcraft_geom::Rect::new(art.x0, art.y0, art.x0, art.y1));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(flat));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
}
/// A graph saved before it kept the bounds of its art without type follows a move made since with its old bounds.
#[test]
fn a_graph_saved_with_only_its_whole_bounds_still_follows_a_move() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let rect = spec(&s, id).rect;
let mut old = serde_json::to_value(spec(&s, id)).unwrap();
old.as_object_mut().unwrap().remove("placedArt");
let old: GraphSpec = serde_json::from_value(old).unwrap();
assert_eq!(old.placed_art, None);
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let moved = spec(&s, id).rect;
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
assert!(spec(&s, id).placed_art.is_some(), "the next drawing keeps the bounds of the art without type");
}
/// Each Axes and Legend text after the graph is drawn again, with its object rows (fill or stroke, color, opacity, and
/// for a stroke its weight) and its object opacity.
type RowLooks = Vec<(bool, String, f32, f64)>;
@@ -6935,3 +7261,42 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
}
}
/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own
/// leaves the plot where it is at the first redraw.
#[test]
fn a_graph_opened_from_ai_measures_moves_without_its_labels() {
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\
u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n\
0 To\n1 0 0 1 100 220 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Sales) Tx\nTO\nU\n%_GS\n";
let text = format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\
%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n"
);
let dir = vectorcraft_testkit::temp_dir("graph-ai-label");
let path = dir.join("graph.ai");
std::fs::write(&path, text).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let (mut graphs, mut labels) = (vec![], vec![]);
s.doc().unwrap().doc.walk(|n| {
if n.extras().graph.is_some() {
graphs.push(n.id);
}
if matches!(&n.kind, NodeKind::Text(t) if t.plain_text() == "Sales") {
labels.push(n.id);
}
});
assert_eq!((graphs.len(), labels.len()), (1, 1));
let (id, label) = (graphs[0], labels[0]);
let before = spec(&s, id);
assert!(before.placed_art.is_some());
s.execute("select.set", &json!({"ids": [label.0]})).unwrap();
s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
assert_eq!(spec(&s, id).rect, before.rect);
}
+30 -4
View File
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded)|size (the linked file's size in bytes as Link Info shows it, smallest first; rows without one, embedded images and missing files whose size is not kept, last; equal sizes by name); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
list
),
@@ -2211,6 +2211,16 @@ fn document_row(p: &PlacedDocument) -> Value {
json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height })
}
/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's
/// size now, else the size the document keeps of it when the caller may see its path.
fn link_file_size(st: &crate::DocState, l: &LinkInfo) -> Option<u64> {
let doc_path = LinkBase::of(st).doc;
let kept = l.size.filter(|_| path_shown(&l.path, doc_path));
let roots = crate::file_access::current().or_else(|| st.opened_by.clone());
let now = crate::file_access::confine(roots.as_ref(), || fileio::document_path(&l.path, doc_path).ok().as_deref().and_then(file_stamp));
now.map(|s| s.0).or(kept)
}
/// Sort rank of a `links.list` status: missing, modified, ok, embedded.
fn status_rank(status: &str) -> usize {
["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4)
@@ -2277,8 +2287,14 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(show, "all" | "missing" | "modified" | "embedded") {
return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded")));
}
let sort = str_param(p, "sort");
if let Some(x) = sort.filter(|x| !matches!(*x, "name" | "kind" | "status" | "size")) {
return Err(bad(C, format!("sort `{x}`: name, kind, status or size")));
}
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
let statuses = statuses(st);
// The file size of each listed row's link, read only to sort by size.
let mut sizes: BTreeMap<u64, u64> = BTreeMap::new();
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
// order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the
// stored brushes), each once.
@@ -2326,6 +2342,11 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
}
let doc_path = LinkBase::of(st).doc;
if let Some(l) = link {
if sort == Some("size")
&& let Some(size) = link_file_size(st, l)
{
sizes.insert(n.id.0, size);
}
note_path(&mut row, "path", &l.path, doc_path);
if let Some(page) = l.page {
row["page"] = json!(page);
@@ -2346,12 +2367,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
rows.push(row);
}
let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase();
match str_param(p, "sort") {
None => {}
match sort {
Some("name") => rows.sort_by_cached_key(|r| text(r, "name")),
Some("kind") => rows.sort_by_cached_key(|r| (text(r, "format"), text(r, "name"))),
Some("status") => rows.sort_by_cached_key(|r| (status_rank(r["status"].as_str().unwrap_or_default()), text(r, "name"))),
Some(x) => return Err(bad(C, format!("sort `{x}`: name, kind or status"))),
// Smallest file first; rows without a file size (embedded images, a missing file whose
// size the document does not keep) come last; equal sizes by name.
Some("size") => rows.sort_by_cached_key(|r| {
let size = r["id"].as_u64().and_then(|id| sizes.get(&id).copied());
(size.is_none(), size.unwrap_or(0), text(r, "name"))
}),
_ => {}
}
let count = |k: &str| counts.get(k).copied().unwrap_or(0);
Ok(json!({ "links": rows, "missing": count("missing"), "modified": count("modified"), "embedded": count("embedded") }))
+1 -1
View File
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Object Properties",
[],
None,
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
has_doc,
set_props
),
+11 -3
View File
@@ -68,8 +68,14 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
let transparency = opacity.is_some() || blend.is_some();
let stores =
|| transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids));
// A series group's isolation, knockout and knockout shape are kept for the group alone.
let group_only = !transparency && ["isolate", "knockout", "knockoutShape"].iter().any(|k| p.get(*k).is_some());
let kept = if group_only { crate::cmd::graph::series_groups_among(d, &ids) } else { ids.clone() };
let stores = || {
(transparency || group_only)
&& (crate::cmd::graph::series_object_opacity_differs(d, &kept)
|| transparency && crate::cmd::graph::label_object_opacity_differs(d, &ids))
};
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() {
// Hidden or locked objects can't stay selected.
if hides {
@@ -123,8 +129,10 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
});
}
}
if transparency || group_only {
crate::cmd::graph::capture_series_object_opacity(d, &kept);
}
if transparency {
crate::cmd::graph::capture_series_object_opacity(d, &ids);
crate::cmd::graph::capture_label_object_opacity(d, &ids);
}
// Hidden or locked objects can't stay selected.
+1 -1
View File
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency",
["Window", "Transparency"],
None,
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
has_doc,
transparency
),
+7 -16
View File
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert to Text",
[],
None,
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
has_doc,
convert_list_to_text
),
@@ -1335,19 +1335,11 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
use vectorcraft_doc::text::ParaList;
let range = super::typecmd::TextRange::parse(p, C)?;
// After Select All in a frame of threaded text, a call that names no type and no range takes
// every paragraph of the story's editable frames; its locked and hidden frames stay as they are
// whichever way they are named.
let full = super::textedit::editing_story(s);
let story: Vec<NodeId> = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect();
// every paragraph of every frame of the story, its locked and hidden frames included: the story
// is one text.
let story = super::textedit::editing_story(s);
let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let ids = if !story.is_empty() && !named && range.is_none() {
story.clone()
} else {
super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect()
};
// The selected story's locked and hidden frames: no paragraph whose text starts in one is
// converted, and none of their paragraphs is restyled.
let held: Vec<NodeId> = full.iter().copied().filter(|f| !story.contains(f)).collect();
let ids = if !story.is_empty() && !named && range.is_none() { story.clone() } else { super::typecmd::text_targets(s, p, C)? };
// Converting the whole story leaves it selected.
let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f));
let editing = match super::textedit::editing_range(s)? {
@@ -1381,7 +1373,6 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
let mut converted = 0;
for story in &stories {
let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect();
let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id));
let mut paras: Vec<StoryParagraph> = vec![];
let mut named_parts = vec![];
let plains: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
@@ -1407,7 +1398,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
}
for (i, named) in named_parts {
if let Some(para) = paras.get_mut(i) {
let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame));
let listed = para.main_part().is_some_and(|p| p.list.is_some());
para.converts |= named && listed;
}
}
@@ -1497,7 +1488,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' };
style.tabs.insert(i, tab);
}
for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) {
for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) {
if let Some((stops, _)) = frame_edits.get_mut(part.frame) {
stops.push((part.index, style.clone()));
}
+1 -1
View File
@@ -183,7 +183,7 @@ pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> {
/// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands
/// its `…` entries name)?
pub(crate) fn takes_key(doc: &'static str, key: &str) -> bool {
pub fn takes_key(doc: &'static str, key: &str) -> bool {
doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key))
}
+122 -8
View File
@@ -7,7 +7,8 @@
//! fields; `perspective.grid.preset` applies one, `perspective.presets.*` manage them.
//!
//! View options (Lock Grid, Lock Station Point, Snap to Grid, Show Rulers) are view state on
//! the grid: they toggle without an undo step, as Show Grid does.
//! the grid: they toggle without an undo step, as Show Grid does. So is the point Automatic Plane
//! Positioning holds the active plane through (`perspective.plane.infer`).
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -15,12 +16,15 @@ use vectorcraft_doc::{Document, NodeId};
use vectorcraft_geom::{Point, Rect, Vec2};
use vectorcraft_tools::distort::perspective::Plane;
use vectorcraft_tools::distort::perspective::define::{BUILTINS, LETTER, first_artboard, is_builtin};
use vectorcraft_tools::distort::perspective::infer::{HIT_PX, InferSource};
use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace};
use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid};
use vectorcraft_tools::distort::perspective::{GridDefinition, MAX_DEPTH, PerspectiveGrid};
use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey};
use super::distortcmds::{grid_kept, grid_of, silent, store_grid};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name};
use super::{
CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, number_or, str_param, switch_or, unique_name,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -92,10 +96,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Perspective Grid Options",
[],
None,
"{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight} the Plane Switching Widget: shown or not, and the corner of the document window it stays in (kept with the preferences; no params reads them) → {show, position}",
"{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight, anchorPoint?: bool, gridlineIntersection?: bool} the Plane Switching Widget: shown or not, and the corner of the document window it stays in; Automatic Plane Positioning: whether it takes a point from an anchor point of art in perspective and from a gridline intersection (both on by default; see perspective.plane.infer). Kept with the preferences; no params reads them → {show, position, anchorPoint, gridlineIntersection}",
always,
widget_options
),
cmd!(
"perspective.plane.infer",
"Automatic Plane Positioning",
[],
None,
"{at?: [x, y], tolerance?: pt around `at` (default 6), clear?: bool} with `at` on an anchor point of shown art in perspective, or on a gridline intersection of a plane that shows, the active plane moves through that point for now and the other planes hide (the Perspective Selection tool: Shift held over one with no button down). An anchor point within reach wins over an intersection, and perspective.widget.options turns either off. Making another plane active (perspective.plane.set) brings that plane through the same point. The plane goes back to its place when an object is drawn on it or attached to it (perspective.draw, perspective.attach, an object brought into perspective by perspective.move or perspective.transform), when a plane is moved (perspective.plane.move, perspective.plane.matchObject), when the grid hides or no plane is active, when the file is opened again, and with `clear` (Escape with the Perspective Selection tool). View state: not an undo step; no params reads it → {active, plane, offset: where the active plane is, point?: [x, y, z] in the grid's frame, source?: anchor|gridline (what `at` found; absent when nothing was within reach)}",
has_doc,
plane_infer
),
cmd!(
"perspective.grid.lock",
"Lock Grid",
@@ -259,21 +272,32 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result<Value> {
let old = grid_of(&s.doc()?.doc);
let ab = s.doc()?.doc.artboards.first().map(|a| a.rect).ok_or_else(|| EngineError::Other("no artboard".into()))?;
let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?;
// The objects stay attached and the view options stay as they were.
let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g };
// The objects stay attached and the view options stay as they were, and so does a plane held
// by Automatic Plane Positioning while the new grid can hold it.
let mut g = PerspectiveGrid {
attached: old.attached,
locked: old.locked,
lock_station: old.lock_station,
snap: old.snap,
rulers: old.rulers,
inferred: old.inferred,
..g
};
g.keep_positioning_valid();
// When the document holds this grid already, apart from whether it shows and its active plane,
// the preset only sets those two, without an undo step (as perspective.grid.show and
// perspective.plane.set do).
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, ..g.clone() };
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, inferred: old.inferred, ..g.clone() };
if !grid_kept(&s.doc()?.doc, &view) {
s.edit("Perspective Grid Preset", |d, _| {
store_grid(d, &g);
Ok(())
})?;
} else if (old.visible, old.plane) != (g.visible, g.plane) {
} else if (old.visible, old.plane, old.inferred) != (g.visible, g.plane, g.inferred) {
silent(s, |cur| {
cur.visible = g.visible;
cur.plane = g.plane;
cur.inferred = g.inferred;
})?;
}
Ok(g.definition_json())
@@ -460,10 +484,100 @@ fn widget_options(s: &mut Session, p: &Value) -> Result<Value> {
o.position =
v.as_str().and_then(WidgetCorner::parse).ok_or_else(|| bad(C, "position must be topLeft, topRight, bottomLeft or bottomRight"))?;
}
if let Some(v) = p.get("anchorPoint") {
o.anchor_point = v.as_bool().ok_or_else(|| bad(C, "anchorPoint must be true or false"))?;
}
if let Some(v) = p.get("gridlineIntersection") {
o.gridline_intersection = v.as_bool().ok_or_else(|| bad(C, "gridlineIntersection must be true or false"))?;
}
s.prefs.perspective_widget = o;
Ok(json!(o))
}
/// What `perspective.plane.infer` reports for `g`.
fn infer_info(g: &PerspectiveGrid, source: Option<InferSource>) -> Value {
let active = g.inferred.is_some() && g.plane != Plane::None;
let mut v = json!({ "active": active, "plane": g.plane.id(), "offset": g.offset(g.plane) });
if let Some(at) = g.inferred.filter(|_| active) {
v["point"] = json!(at);
}
if let Some(source) = source {
v["source"] = json!(source.id());
}
v
}
fn plane_infer(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "perspective.plane.infer";
let clear = switch_or(p, "clear", false, C)?;
let at = match p.get("at") {
None | Some(Value::Null) => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?),
};
let tol = number_or(p, "tolerance", HIT_PX, C)?;
if !(tol.is_finite() && (0.0..=MAX_DEPTH).contains(&tol)) {
return Err(bad(C, "tolerance must be 0 or more"));
}
if clear && at.is_some() {
return Err(bad(C, "give `at` or `clear`, not both"));
}
let doc = &s.doc()?.doc;
let g = PerspectiveGrid::current(doc);
let mut source = None;
let next = match at {
_ if clear => None,
None => g.inferred,
Some(at) => {
if !g.visible {
return Err(EngineError::Other("the perspective grid is hidden".into()));
}
if g.plane == Plane::None {
return Err(EngineError::Other("no active perspective plane".into()));
}
let targets = s.prefs.perspective_widget.targets();
if !targets.any() {
return Err(EngineError::Other(
"Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)".into(),
));
}
match g.infer_at(doc, at, tol, targets) {
Some((found, point)) => {
source = Some(found);
Some(point)
}
None => g.inferred,
}
}
};
if next == g.inferred {
return Ok(infer_info(&g, source));
}
// A plane through the point stays in front of the viewer.
if next.is_some() {
PerspectiveGrid { inferred: next, ..g }.validate().map_err(|e| bad(C, e))?;
}
let g = silent(s, |g| g.inferred = next)?;
Ok(infer_info(&g, source))
}
/// An object was drawn on, or attached to, `plane`: when Automatic Plane Positioning holds that
/// plane, it goes back to its place as view state, not an undo step (a plane it doesn't hold
/// leaves it as it is). In a drag that happens once the drag is committed
/// ([`Session::commit_interaction`]), so the plane stays put while the object is drawn.
pub(crate) fn plane_positioning_used(s: &mut Session, plane: Plane) -> Result<()> {
let st = s.doc_mut()?;
let g = grid_of(&st.doc);
if g.inferred.is_none() || g.plane != plane {
return Ok(());
}
if let Some(it) = &mut st.interaction {
it.plane_placed = true;
return Ok(());
}
silent(s, |g| g.inferred = None)?;
Ok(())
}
impl Session {
/// The Plane Switching Widget's part of a pointer event: a press on it picks the plane (its
/// drag and release go nowhere); None when the event isn't the widget's.
+40 -4
View File
@@ -20,7 +20,7 @@ use std::sync::Arc;
use vectorcraft_doc::links::hash_bytes;
use vectorcraft_doc::placed_document::{PREVIEW_MAX, PREVIEW_PX_PER_PT, key_for};
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions};
use vectorcraft_doc::{ColorMode, Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::CropTo;
@@ -221,22 +221,57 @@ pub(crate) struct Source {
/// What is shown, in the file's coordinates: the artboard, the page's box or the art's bounds.
pub frame: Rect,
pub warnings: Vec<String>,
/// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK).
pub color_mode: ColorMode,
}
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
/// artboard `page`, or the PDF or `.ai` file for showing page `page` clipped to its box
/// `page_box` (its art's bounds when `bounding`).
pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, page_box: PageBox, cmd: &str) -> Result<Source> {
read_source(name, bytes, None, path, (page, bounding, page_box), cmd)
}
/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own:
/// several pages of one file read this way share one copy of it.
pub(crate) fn shared_source(
name: &str,
bytes: &Arc<Vec<u8>>,
path: Option<&str>,
page: u32,
bounding: bool,
page_box: PageBox,
cmd: &str,
) -> Result<Source> {
read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd)
}
/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page
/// (or artboard), whether the art's bounds are shown, and the page's box.
fn read_source(
name: &str,
bytes: &[u8],
shared: Option<&Arc<Vec<u8>>>,
path: Option<&str>,
shown: (u32, bool, PageBox),
cmd: &str,
) -> Result<Source> {
let (page, bounding, page_box) = shown;
// The same document placed the same way is read once (placing it again is free).
let key = key_for(&hash_bytes(bytes), page, bounding, page_box);
// Resolving its links depends on where the file is and on what the caller may read, so a hit
// needs the same path, and nothing is shared with or from a confined (automation) caller.
let confined = crate::file_access::current().is_some();
if !confined && let Some((_, s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() {
if !confined && let Some((_, mut s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() {
// The same bytes: the copy given is kept instead, so the pages that share it go on sharing.
if let Some(b) = shared {
s.blob.bytes = b.clone();
}
return Ok(s);
}
let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?;
let mut blob = ImageBlob::new(mime(name, bytes), bytes.to_vec());
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -249,9 +284,10 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo
};
let art = group(a.nodes, a.clip);
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
let color_mode = a.doc.color_mode;
// Drawing it needn't read it again.
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings };
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode };
if !confined {
let mut m = lock_memo();
if m.len() >= MEMO_SIZE {
+175 -35
View File
@@ -101,12 +101,30 @@ const FILE_WORDS: &[&str] = &[
"clipboard",
];
/// Param keys that name a file or a folder.
const FILE_KEYS: &[&str] =
&["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"];
/// Param keys that name a file or a folder, each by its whole name, the folder preferences
/// `prefs.set {values}` takes included: a command that adds a key naming one adds it here. A key
/// that only ends like one (`alignToPath`, `linksFolder`, `sortPaths`) names none, nor do `folders`
/// (how an export groups its files) and `url` (a web link).
const FILE_KEYS: &[&str] = &[
"path",
"paths",
"file",
"files",
"folder",
"dir",
"directory",
"destinationFolder",
"sourceFolder",
"diffPath",
"fontsFolder",
"pluginsFolder",
"recoveryFolder",
"templatesFolder",
];
/// The keys in [`FILE_KEYS`] that name a folder.
const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"];
const FOLDER_KEYS: &[&str] =
&["folder", "dir", "directory", "destinationFolder", "sourceFolder", "fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
/// What a param key that names a place on disk names there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -132,7 +150,83 @@ pub fn key_location(key: &str) -> Option<Location> {
/// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`]
/// names it for `spec` (it names part of the document there).
pub fn location_in(spec: &CommandSpec, key: &str) -> Option<Location> {
if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) }
ParamsPlace::top(Some(spec)).member(key, None).1
}
/// A place in the params of a command. What a key names on disk depends on the command and on the
/// keys above it: [`key_location`], less a key [`NOT_FILES`] names for the command at the top of its
/// params and one at the end of a [`NESTED_NOT_FILES`] key list. A walk of params starts at
/// [`ParamsPlace::top`] and goes down with [`ParamsPlace::member`] and [`ParamsPlace::item`].
#[derive(Clone, Copy, Debug)]
pub struct ParamsPlace {
/// The command whose params these are; `None` for a command that isn't known.
command: Option<&'static str>,
/// Whether this is the top of the params.
top: bool,
/// The keys of a [`NESTED_NOT_FILES`] list still to follow below this place.
trail: Option<&'static [&'static str]>,
}
impl ParamsPlace {
/// The top of the params of `spec`, or of a command that isn't known (`None`), where every key in
/// [`FILE_KEYS`] names a file or a folder.
pub fn top(spec: Option<&CommandSpec>) -> ParamsPlace {
ParamsPlace { command: spec.map(|s| s.id), top: true, trail: None }
}
/// The top of the params of the command with id `id` ([`ParamsPlace::top`]).
pub fn of(id: &str) -> ParamsPlace {
ParamsPlace::top(super::find_command(id))
}
/// The top of the params of the command that object `fields` calls, when it is a call
/// (`{command | id: <command id>, params}`, as a `command.batch` step or a control request is):
/// the place of its `params` member ([`ParamsPlace::member`]).
pub fn carried(fields: &serde_json::Map<String, Value>) -> Option<ParamsPlace> {
if !fields.contains_key("params") {
return None;
}
let id = fields.get("command").or_else(|| fields.get("id")).and_then(Value::as_str)?;
super::find_command(id).map(|spec| ParamsPlace::top(Some(spec)))
}
/// The top of the params of the command that array `items` records, when it is a recorded step
/// (`[command id, params]`): the place of its item 1 ([`ParamsPlace::item`]).
pub fn step(items: &[Value]) -> Option<ParamsPlace> {
match items {
[Value::String(id), Value::Object(_)] => super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))),
_ => None,
}
}
/// The place of member `key` of an object here, with what `key` names on disk there. `carried` is
/// [`ParamsPlace::carried`] of that object: its `params` member is then the top of that command's
/// params, and names no file.
pub fn member(self, key: &str, carried: Option<ParamsPlace>) -> (ParamsPlace, Option<Location>) {
if key == "params"
&& let Some(inner) = carried
{
return (inner, None);
}
let rest = if self.top {
let id = self.command;
NESTED_NOT_FILES.iter().find(|(c, keys)| Some(*c) == id && keys.first() == Some(&key)).map(|(_, keys)| keys.get(1..).unwrap_or_default())
} else {
self.trail.filter(|keys| keys.first() == Some(&key)).map(|keys| keys.get(1..).unwrap_or_default())
};
let document = (self.top && self.command.is_some_and(|id| NOT_FILES.contains(&(id, key)))) || rest.is_some_and(<[&str]>::is_empty);
let place = ParamsPlace { command: self.command, top: false, trail: rest.filter(|keys| !keys.is_empty()) };
(place, if document { None } else { key_location(key) })
}
/// The place of item `index` of an array here. `step` is [`ParamsPlace::step`] of that array: its
/// item 1 is then the top of that command's params.
pub fn item(self, index: usize, step: Option<ParamsPlace>) -> ParamsPlace {
match step {
Some(inner) if index == 1 => inner,
_ => ParamsPlace { command: self.command, top: false, trail: None },
}
}
}
/// The param keys of `spec` that name a file or a folder, with what they name: the keys in
@@ -158,9 +252,6 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[
("symbol.instance.setAppearance", "path"),
("symbol.instance.selectPart", "path"),
("object.objectsOnPath.attach", "path"),
("attributes.set", "url"),
("object.slice.options", "url"),
("document.exportForScreens", "folders"),
];
/// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there,
@@ -251,34 +342,24 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool {
})
}
/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth
/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`]
/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for
/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the
/// thread's.
/// Does `args`, the arguments of a call of command `id`, carry a key that names a file or a folder at
/// any depth (in objects and in arrays, [`ParamsPlace`]), such as an effect's `textureImage.path`?
/// Only a key [`NOT_FILES`] names for `id`, at the top level, and one at the end of a
/// [`NESTED_NOT_FILES`] key list for `id`, aren't counted. A call or a recorded step inside `args`
/// is read as part of `id`'s arguments, not as the command it names. The walk keeps its own stack,
/// so deep arguments can't overflow the thread's.
fn names_file(id: &str, args: &Value) -> bool {
// Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list
// still to follow below it.
let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)];
while let Some((v, top, trail)) = stack.pop() {
let mut stack: Vec<(&Value, ParamsPlace)> = vec![(args, ParamsPlace::of(id))];
while let Some((v, place)) = stack.pop() {
match v {
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))),
Value::Array(a) => stack.extend(a.iter().enumerate().map(|(i, x)| (x, place.item(i, None)))),
Value::Object(o) => {
for (k, x) in o {
let k = k.as_str();
let rest = if top {
NESTED_NOT_FILES
.iter()
.find(|(c, keys)| *c == id && keys.first() == Some(&k))
.map(|(_, keys)| keys.get(1..).unwrap_or_default())
} else {
trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default())
};
let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty);
if FILE_KEYS.contains(&k) && !document {
let (below, location) = place.member(k, None);
if location.is_some() {
return true;
}
stack.push((x, false, rest.filter(|keys| !keys.is_empty())));
stack.push((x, below));
}
}
_ => {}
@@ -638,7 +719,13 @@ mod tests {
assert!(names_file("effect.apply", &texture));
assert!(names_file("effect.setParams", &texture));
assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}})));
assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]])));
assert!(names_file("select.all", &json!([[[{"file": "file:///etc/hosts"}]]])));
// A web link and an export's grouping name no file.
assert!(!names_file("attributes.set", &json!({"url": "https://example.com/a"})));
assert!(!names_file("object.move", &json!({"opts": {"folders": "rows", "alignToPath": "baseline"}})));
// A call nested in the arguments doesn't vouch for its own keys.
assert!(names_file("object.move", &json!({"opts": {"command": "object.setLiveShape", "params": {"path": "/tmp/x"}}})));
assert!(names_file("object.move", &json!({"opts": ["object.setLiveShape", {"path": "/tmp/x"}]})));
assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}})));
assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}})));
// `path` is the path text is set on in text.createInPath, but only as its own param.
@@ -647,7 +734,13 @@ mod tests {
assert!(names_file("object.move", &json!({"path": [[0, 0]]})));
// object.setLiveShape takes no `path`; its description says "on any path:" in its prose.
assert!(names_file("object.setLiveShape", &json!({"path": "/tmp/x"})));
// Image Trace's path fidelity setting, only inside its tracing settings.
}
/// Image Trace's path fidelity setting `paths` names no file, but only inside its tracing
/// settings.
#[test]
fn image_trace_paths_name_no_file_only_in_its_settings() {
use serde_json::json;
for id in ["imageTrace.make", "imageTrace.makeAndExpand"] {
assert!(!names_file(id, &json!({"preset": "Default", "params": {"mode": "color", "paths": 50}})));
assert!(!names_file(id, &json!({"savedPreset": {"paths": 50, "corners": 75}})));
@@ -658,7 +751,12 @@ mod tests {
assert!(names_file(id, &json!({"options": {"paths": 50}})));
}
assert!(names_file("object.move", &json!({"params": {"paths": 50}})));
// A custom arrowhead's outline in stroke.set, only where stroke.set takes one.
}
/// A custom arrowhead's outline `path` names no file, but only where stroke.set takes one.
#[test]
fn a_custom_arrowhead_outline_names_no_file_only_in_stroke_set() {
use serde_json::json;
let outline = json!({"subpaths": []});
assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}})));
assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"})));
@@ -668,7 +766,12 @@ mod tests {
assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}})));
assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]})));
assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}})));
// Deep nesting is walked without recursion.
}
/// A file key under deep nesting is found, and the walk doesn't recurse.
#[test]
fn a_file_key_is_found_under_deep_nesting() {
use serde_json::json;
let mut deep = json!({"file": "/tmp/x"});
for _ in 0..10_000 {
deep = Value::Array(vec![deep]);
@@ -726,11 +829,48 @@ mod tests {
assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id);
assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id);
}
assert_eq!(key_location("url"), Some(Location::File));
assert_eq!(key_location("url"), None);
assert_eq!(key_location("folders"), None);
assert_eq!(key_location("linksFolder"), None);
assert_eq!(key_location("sourceFolder"), Some(Location::Folder));
assert_eq!(key_location("pathData"), None);
}
/// A key keeps the meaning its command gives it at every depth: a call (`{command, params}`) and a
/// recorded step (`[command id, params]`) carry their command's exceptions down, and a custom
/// arrowhead's outline is part of the document only at its own place in `stroke.set`.
#[test]
fn a_params_place_follows_its_command() {
use serde_json::json;
let at = |place: ParamsPlace, keys: &[&str]| {
let mut place = place;
let mut location = None;
for k in keys {
(place, location) = place.member(k, None);
}
location
};
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["path"]), None);
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["options", "path"]), Some(Location::File));
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "path"]), None);
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "file"]), Some(Location::File));
assert_eq!(at(ParamsPlace::of("no.such.command"), &["path"]), Some(Location::File));
assert_eq!(at(ParamsPlace::top(None), &["destinationFolder"]), Some(Location::Folder));
let call = json!({"command": "text.createInPath", "params": {"path": [[0, 0]]}});
let carried = call.as_object().and_then(ParamsPlace::carried);
let (inner, location) = ParamsPlace::of("command.batch").member("params", carried);
assert_eq!(location, None);
assert_eq!(inner.member("path", None).1, None);
assert_eq!(ParamsPlace::carried(&serde_json::Map::new()).map(|_| ()), None);
let unknown = json!({"command": "no.such.command", "params": {}});
assert!(unknown.as_object().and_then(ParamsPlace::carried).is_none());
let step = [json!("text.createInPath"), json!({"path": [[0, 0]]})];
let place = ParamsPlace::top(None).item(1, ParamsPlace::step(&step));
assert_eq!(place.member("path", None).1, None);
assert_eq!(ParamsPlace::top(None).item(0, ParamsPlace::step(&step)).member("path", None).1, Some(Location::File));
assert!(ParamsPlace::step(&[json!("text.createInPath")]).is_none());
}
/// A file key counts as a command's param only where its description takes it: not a word in
/// the prose after the params, in a nested object or in the result. A description that doesn't
/// say which keys it takes counts any `key:` in its text.
@@ -34,6 +34,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.contour.set",
"addon.cutting.banner",
"addon.cutting.bridges",
"addon.cutting.nest",
"addon.cutting.weed",
"addon.image.applyColorMask",
"addon.image.colorMask",
@@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[
"perspective.grid.snap",
"perspective.move",
"perspective.nudge",
"perspective.plane.infer",
"perspective.plane.matchObject",
"perspective.plane.move",
"perspective.plane.set",
+81 -11
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap};
use super::typecmd::refresh_bounds;
use super::{CommandSpec, EngineError, Result, Session, bool_or, checked_ids_or_selection, cmd, f64_or, has_selection};
use super::{CommandSpec, EngineError, Result, Session, bad, checked_ids_or_selection, cmd, has_selection, number_or, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Text Wrap"],
None,
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a negative offset (to -1000) lets the text that far into them → {ids}",
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}",
has_selection,
make
),
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap Options…",
["Object", "Text Wrap"],
None,
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); no options → the current {offset, invert}",
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
has_selection,
options
),
@@ -37,14 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
fn wrap_param(p: &Value, base: TextWrap) -> TextWrap {
let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end());
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) }
/// The options `p` gives, with `base` for an omitted or null `offset` or `invert`. An `offset` that is
/// not a number or lies outside [`TEXT_WRAP_OFFSET_RANGE`], or an `invert` that is not true or false,
/// is an error. `base`'s offset is kept as it is.
fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
let key = "offset";
let given = p.get(key).is_some_and(|v| !v.is_null());
let offset = number_or(p, key, base.offset, cmd)?;
if given && !TEXT_WRAP_OFFSET_RANGE.contains(&offset) {
let (lo, hi) = (TEXT_WRAP_OFFSET_RANGE.start(), TEXT_WRAP_OFFSET_RANGE.end());
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}")));
}
Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? })
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?;
let w = wrap_param(p, TextWrap::default());
let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?;
s.edit("Make Text Wrap", |d, _| {
for id in &ids {
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
@@ -86,10 +95,10 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default()
};
if p.get("offset").is_none() && p.get("invert").is_none() {
if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) {
return Ok(json!({ "offset": current.offset, "invert": current.invert }));
}
let w = wrap_param(p, current);
let w = wrap_param(p, current, "object.textWrap.options")?;
s.edit("Text Wrap Options", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id)
@@ -212,11 +221,72 @@ mod tests {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(6.0));
assert!(beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s));
// An offset past -1000 is kept at -1000: the whole object lets text through.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -5000})).unwrap()["offset"], json!(-1000.0));
// An offset of -1000 lets the text through the whole object.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -1000})).unwrap()["offset"], json!(-1000.0));
assert!(lines(&s, t).iter().all(|l| l.0 < 1.0 && l.1 > 300.0));
}
/// An offset that is not a number or lies outside -1000 to 1000 pt, or an invert that is not
/// true or false, is an error for Make and Options, and leaves the options and the history as
/// they were. Omitted and null values take the default, and the range's ends are accepted.
#[test]
fn text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let wrap = |s: &Session| s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap;
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let refused = [
(json!({"offset": "12"}), "`offset` must be a number"),
(json!({"offset": true}), "`offset` must be a number"),
(json!({"offset": [12]}), "`offset` must be a number"),
(json!({"offset": {"pt": 12}}), "`offset` must be a number"),
(json!({"offset": 1000.5}), "`offset` must be from -1000 to 1000"),
(json!({"offset": -1000.5}), "`offset` must be from -1000 to 1000"),
(json!({"offset": 5000}), "`offset` must be from -1000 to 1000"),
(json!({"offset": 12, "invert": "true"}), "`invert` must be true or false"),
(json!({"offset": 12, "invert": 1}), "`invert` must be true or false"),
(json!({"invert": "false"}), "`invert` must be true or false"),
];
let start = undo(&s);
for (p, msg) in &refused {
let e = s.execute("object.textWrap.make", p).unwrap_err().to_string();
assert!(e.contains(msg), "make {p}: {e}");
assert!(wrap(&s).is_none(), "make {p} made a wrap");
assert_eq!(undo(&s), start, "make {p} added history");
}
// Omitted and null values: Make's 6 pt default.
s.execute("object.textWrap.make", &json!({"offset": null, "invert": null})).unwrap();
assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 6.0, invert: false }));
s.execute("object.textWrap.options", &json!({"offset": 40, "invert": true})).unwrap();
let before = undo(&s);
for (p, msg) in &refused {
let e = s.execute("object.textWrap.options", p).unwrap_err().to_string();
assert!(e.contains(msg), "options {p}: {e}");
assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 40.0, invert: true }), "options {p}");
assert_eq!(undo(&s), before, "options {p} added history");
}
// Null options read the current ones without an undo step; a null one keeps its value.
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": null, "invert": null})).unwrap(), json!({"offset": 40.0, "invert": true}));
assert_eq!(undo(&s), before);
assert_eq!(
s.execute("object.textWrap.options", &json!({"offset": null, "invert": false})).unwrap(),
json!({"offset": 40.0, "invert": false})
);
// The range's ends are accepted by both commands.
for (command, offset) in
[("object.textWrap.options", 1000), ("object.textWrap.options", -1000), ("object.textWrap.make", 1000), ("object.textWrap.make", -1000)]
{
s.execute(command, &json!({ "offset": offset })).unwrap();
assert_eq!(wrap(&s).unwrap().offset, f64::from(offset), "{command} {offset}");
}
// A stored offset outside the range (from a file) is kept when only Invert Wrap changes.
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(id)).unwrap().extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 5000.0, invert: false });
assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true}));
}
#[test]
fn text_flows_on_both_sides_of_a_centred_object() {
let mut s = Session::new();
+24 -18
View File
@@ -616,6 +616,21 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed }))
}
/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as
/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced
/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's
/// transform); `None` when the piece has no path.
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> {
let path = PathData::from_bezpath(outline);
if path.is_empty() {
return None;
}
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, path, None);
vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
Some(node)
}
fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
let roots = selected_roots(s)?;
let ids = s.edit("Create Outlines", |d, sel| {
@@ -623,6 +638,8 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
if texts.is_empty() {
return Err(EngineError::Other("Create Outlines: select text objects".into()));
}
// Outlining a graph's labels does not move or scale its plot at the next redraw.
let graphs = super::graph::graphs_holding(d, &texts);
let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone());
let ended = super::dimension::end_links(d, &roots);
let mut new_sel: Vec<NodeId> = roots.iter().copied().filter(|r| !texts.contains(r)).collect();
@@ -658,14 +675,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
children.push(Arc::new(d.reid(&art)));
break 'glyph;
}
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
if path.is_empty() {
break 'glyph;
if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) {
children.push(Arc::new(node));
}
let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, path, None);
node.appearance = st.appearance().into();
children.push(Arc::new(node));
}
run_end.insert(g.run, children.len());
}
@@ -674,13 +686,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// nothing there either).
let mut ruby: Vec<(usize, Arc<Node>)> = vec![];
for g in &lay.ruby {
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
if path.is_empty() {
continue;
}
let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, path, None);
node.appearance = st.appearance().into();
let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue };
// After the glyphs of its run and of the runs before it.
let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0);
ruby.push((at, Arc::new(node)));
@@ -705,10 +711,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// Underline and strikethrough bars become paths of their run's paint too (#847).
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
all.extend(bar.iter());
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None);
node.appearance = st.appearance().into();
children.push(Arc::new(node));
if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) {
children.push(Arc::new(node));
}
}
// The object's own fills and strokes (not its characters') paint the whole outline:
// those below the Characters row under the characters, the others over them, with
@@ -750,6 +755,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
}
// Outlined frames of threaded text leave their threads with the text they show.
super::threads::leave_threads(d, &threaded);
super::graph::keep_placed(d, &graphs);
sel.set(new_sel);
Ok(out)
})?;
+314 -18
View File
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smart Punctuation…",
["Type"],
None,
"{quotes?: true (straight quotes become the Document Setup quotes), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), scope?: \"selection\"|\"document\"} → {changed}",
"{fiLigatures?: false (ff, fi, ffi → the ligatures U+FB00, U+FB01, U+FB03), flLigatures?: false (ff, fl, ffl → U+FB00, U+FB02, U+FB04), quotes?: true (straight quotes become the Document Setup quotes), spaces?: false (two or more spaces after a period → one), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), fractions?: false (1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character, with no digit, slash or decimal point next to them, → ½, ¼, ¾ …), scope?: \"selection\"|\"document\"} the selected type, or every text object with scope document or nothing selected; a ligature or a fraction is written only where the run's font has a glyph for it. Nothing to replace records no undo step → {changed: text objects changed, replaced: {fiLigatures, flLigatures, quotes, spaces, dashes, ellipses, fractions}: how many of each were replaced}",
has_doc,
smart_punctuation
),
@@ -268,24 +268,227 @@ fn change_case(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Smart Punctuation ----------
#[derive(Default)]
struct PunctState {
prev: Option<char>,
/// What Smart Punctuation replaces: each option of its dialog.
struct Punct {
/// ff, fi and ffi become the ligatures U+FB00, U+FB01 and U+FB03.
fi_ligatures: bool,
/// ff, fl and ffl become the ligatures U+FB00, U+FB02 and U+FB04.
fl_ligatures: bool,
/// Straight quotes become these quotes (the Document Setup quotes).
quotes: Option<Quotes>,
/// Two or more spaces after a period become one.
spaces: bool,
/// `--` becomes an en dash and `---` an em dash.
dashes: bool,
/// `...` becomes an ellipsis.
ellipses: bool,
/// `1/2` and the other fractions [`FRACTIONS`] lists become their one-character forms.
fractions: bool,
}
/// Dashes (`--` en, `---` em), ellipses and, with `quotes`, typographer's quotes.
pub(crate) fn smarten(text: &str, prev: &mut Option<char>, quotes: Option<&Quotes>, dashes: bool, ellipsis: bool) -> String {
let mut s = text.to_string();
if dashes {
s = s.replace("---", "—").replace("--", "–");
/// How many of each replacement Smart Punctuation made.
#[derive(Default)]
struct PunctCounts {
fi_ligatures: usize,
fl_ligatures: usize,
quotes: usize,
spaces: usize,
dashes: usize,
ellipses: usize,
fractions: usize,
}
/// The text before the run being rewritten, across the runs of one text object.
#[derive(Default)]
struct PunctState {
/// The character before the run.
prev: Option<char>,
/// The number of spaces since the last period, while only spaces follow it.
after_period: Option<usize>,
/// An inline graphic comes right before the run.
after_graphic: bool,
}
/// The fractions Expert Fractions writes as one character: every fraction Unicode encodes as a
/// vulgar fraction with a numerator of 1 to 7 and a denominator of 2 to 10.
const FRACTIONS: [(&str, char); 18] = [
("1/2", '½'),
("1/3", '⅓'),
("2/3", '⅔'),
("1/4", '¼'),
("3/4", '¾'),
("1/5", '⅕'),
("2/5", '⅖'),
("3/5", '⅗'),
("4/5", '⅘'),
("1/6", '⅙'),
("5/6", '⅚'),
("1/7", '⅐'),
("1/8", '⅛'),
("3/8", '⅜'),
("5/8", '⅝'),
("7/8", '⅞'),
("1/9", '⅑'),
("1/10", '⅒'),
];
/// `s` with every `from` replaced by `to`, adding the number replaced to `n`.
fn replace_counted(s: String, from: &str, to: &str, n: &mut usize) -> String {
let found = s.matches(from).count();
if found == 0 {
return s;
}
if ellipsis {
s = s.replace("...", "…");
*n += found;
s.replace(from, to)
}
/// Smart Spaces: `text` without the second and later spaces after a period, adding the number of
/// periods whose spaces it shortened to `n`. `after` carries the spaces after a period from one run
/// to the next.
fn smart_spaces(text: &str, after: &mut Option<usize>, n: &mut usize) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match (c, *after) {
(' ', Some(k)) => {
*after = Some(k + 1);
if k >= 1 {
if k == 1 {
*n += 1;
}
continue;
}
}
('.', _) => *after = Some(0),
_ => *after = None,
}
out.push(c);
}
match quotes {
Some(q) => q.apply(&s, prev),
out
}
/// The fraction `cs` starts with, and its length in characters: one of [`FRACTIONS`] that no digit,
/// slash or decimal part follows, so `1/25`, `1/2/2026` and `1/2.5` are left as they are. A digit
/// counts in any script.
fn fraction_at(cs: &[char]) -> Option<(usize, char)> {
FRACTIONS.iter().find_map(|(text, f)| {
let len = text.chars().count();
if cs.len() < len || !cs[..len].iter().copied().eq(text.chars()) {
return None;
}
let ends = match &cs[len..] {
[c, ..] if c.is_numeric() || *c == '/' => false,
['.' | ',', d, ..] if d.is_numeric() => false,
_ => true,
};
ends.then_some((len, *f))
})
}
/// Expert Fractions: `text` with each fraction [`fraction_at`] finds, and no digit, slash or
/// decimal point before, written as one character when `covers` it. `prev` is the character before
/// `text`, and `next` the two characters after it (in the next runs), so a fraction at the end of
/// a run is checked against what follows it.
fn expert_fractions(text: &str, prev: Option<char>, next: [Option<char>; 2], covers: &mut impl FnMut(char) -> bool, n: &mut usize) -> String {
let mut cs: Vec<char> = text.chars().collect();
let len_text = cs.len();
cs.extend(next.into_iter().flatten());
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < len_text {
let before = if i == 0 { prev } else { Some(cs[i - 1]) };
let free = !before.is_some_and(|c| c.is_numeric() || matches!(c, '/' | '.' | ','));
let found = fraction_at(&cs[i..]).filter(|(len, f)| i + len <= len_text && covers(*f));
if free && let Some((len, f)) = found {
out.push(f);
*n += 1;
i += len;
continue;
}
out.push(cs[i]);
i += 1;
}
out
}
/// The ligatures and their letters, longest first, with whether each comes with the ff, fi, ffi
/// option (else with the ff, fl, ffl option). ff comes with both.
const LIGATURES: [(&str, char, bool); 5] =
[("ffi", '\u{FB03}', true), ("ffl", '\u{FB04}', false), ("ff", '\u{FB00}', true), ("fi", '\u{FB01}', true), ("fl", '\u{FB02}', false)];
/// The ligature options: `text` with the letters of each ligature an option `o` asks for written
/// as the ligature, the longest first, when `covers` it.
fn ligatures(text: &str, o: &Punct, covers: &mut impl FnMut(char) -> bool, n: &mut PunctCounts) -> String {
let cs: Vec<char> = text.chars().collect();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < cs.len() {
let found = (cs[i] == 'f').then(|| {
LIGATURES.iter().find(|(letters, lig, fi)| {
let on = if *letters == "ff" {
o.fi_ligatures || o.fl_ligatures
} else if *fi {
o.fi_ligatures
} else {
o.fl_ligatures
};
let len = letters.chars().count();
on && cs.len() - i >= len && cs[i..i + len].iter().copied().eq(letters.chars()) && covers(*lig)
})
});
if let Some(&(letters, lig, fi)) = found.flatten() {
out.push(lig);
// ff counts with the ff, fi, ffi option when that option is on.
if fi && (letters != "ff" || o.fi_ligatures) {
n.fi_ligatures += 1;
} else {
n.fl_ligatures += 1;
}
i += letters.chars().count();
continue;
}
out.push(cs[i]);
i += 1;
}
out
}
/// One run's text with the replacements `o` asks for, counted in `n`. Ligatures and fractions are
/// written only where the run's font has a glyph for them. `next` holds the two characters after
/// the run.
fn smarten(text: &str, style: &CharStyle, next: [Option<char>; 2], o: &Punct, st: &mut PunctState, n: &mut PunctCounts) -> String {
let mut s = if o.spaces { smart_spaces(text, &mut st.after_period, &mut n.spaces) } else { text.to_string() };
if o.dashes {
s = replace_counted(s, "---", "—", &mut n.dashes);
s = replace_counted(s, "--", "–", &mut n.dashes);
}
if o.ellipses {
s = replace_counted(s, "...", "…", &mut n.ellipses);
}
// The run's font, looked up once and only for a ligature or a fraction.
let mut face = None;
let mut covers = |c: char| {
face.get_or_insert_with(|| {
vectorcraft_text::FontDb::global().face_version(&style.font_family, &style.font_style, style.font_version.as_deref())
})
.as_ref()
.is_some_and(|f| f.covers(c))
};
if o.fractions && s.contains('/') {
let before = if st.after_graphic { None } else { st.prev };
s = expert_fractions(&s, before, next, &mut covers, &mut n.fractions);
}
st.after_graphic = false;
if (o.fi_ligatures || o.fl_ligatures) && s.contains('f') {
s = ligatures(&s, o, &mut covers, n);
}
match &o.quotes {
Some(q) => {
let out = q.apply(&s, &mut st.prev);
n.quotes += s.chars().zip(out.chars()).filter(|(a, b)| a != b).count();
out
}
None => {
*prev = s.chars().last().or(*prev);
st.prev = s.chars().last().or(st.prev);
s
}
}
@@ -293,12 +496,20 @@ pub(crate) fn smarten(text: &str, prev: &mut Option<char>, quotes: Option<&Quote
fn smart_punctuation(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.smartPunctuation";
let (d, e) = (switch_or(p, "dashes", true, C)?, switch_or(p, "ellipsis", true, C)?);
let quotes = switch_or(p, "quotes", true, C)?;
let mut o = Punct {
fi_ligatures: switch_or(p, "fiLigatures", false, C)?,
fl_ligatures: switch_or(p, "flLigatures", false, C)?,
quotes: None,
spaces: switch_or(p, "spaces", false, C)?,
dashes: switch_or(p, "dashes", true, C)?,
ellipses: switch_or(p, "ellipsis", true, C)?,
fractions: switch_or(p, "fractions", false, C)?,
};
let document = choice(p, C, "scope", &["selection", "document"])? == Some("document");
let st = s.doc()?;
// Quotes in the document's style (Document Setup → Type).
let q = quotes.then_some(st.doc.setup.quotes);
o.quotes = quotes.then_some(st.doc.setup.quotes);
let ids = if document || st.selection.is_empty() {
let mut v = vec![];
st.doc.walk(|n| {
@@ -310,8 +521,93 @@ fn smart_punctuation(s: &mut Session, p: &Value) -> Result<Value> {
} else {
text_ids(&st.doc, &st.selection.objects)
};
let n = edit_runs::<PunctState>(s, "Smart Punctuation", &ids, |text, st| smarten(text, &mut st.prev, q.as_ref(), d, e))?;
Ok(json!({ "changed": n }))
let mut n = PunctCounts::default();
let changed = super::overprint::edit_counted(s, "Smart Punctuation", |d| {
let mut changed = 0;
for id in &ids {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
let mut st = PunctState::default();
let mut any = false;
// The ruby spans' ends, in the plain text as it was. Each run is rewritten in pieces
// between them, so no replacement crosses one, and `moved` records where each end and
// each run's start lands in the new text.
let mut edges: Vec<usize> = t.ruby.iter().flat_map(|r| [r.start, r.end]).collect();
edges.sort_unstable();
edges.dedup();
let mut moved = vec![];
let (mut old_at, mut new_at) = (0, 0);
// Inline graphics are art, not characters to rewrite. Each run sees the first two
// characters of the runs after it, up to the next inline graphic, as they were.
for i in 0..t.runs.len() {
let len = t.runs[i].text.len();
moved.push((old_at, new_at));
if t.runs[i].inline.is_some() {
// A graphic separates the characters on either side of it for Smart Spaces and
// Expert Fractions; quotes still read the character before it.
st.after_period = None;
st.after_graphic = true;
(old_at, new_at) = (old_at + len, new_at + len);
continue;
}
let mut after = t.runs[i + 1..].iter().take_while(|r| r.inline.is_none()).flat_map(|r| r.text.chars());
let following = [after.next(), after.next()];
// Smart Spaces counts no space across a ruby span's end, so it removes no space on
// the other side of one.
if edges.binary_search(&old_at).is_ok() {
st.after_period = None;
}
let r = &mut t.runs[i];
let mut cuts: Vec<usize> =
edges.iter().filter(|&&e| e > old_at && e < old_at + len && r.text.is_char_boundary(e - old_at)).map(|e| e - old_at).collect();
cuts.push(len);
let mut new = String::with_capacity(len);
let mut from = 0;
for cut in cuts {
if from > 0 {
moved.push((old_at + from, new_at + new.len()));
st.after_period = None;
}
let mut after = r.text[cut..].chars().chain(following.into_iter().flatten());
let next = [after.next(), after.next()];
new.push_str(&smarten(&r.text[from..cut], &r.style, next, &o, &mut st, &mut n));
from = cut;
}
(old_at, new_at) = (old_at + len, new_at + new.len());
if new != r.text {
r.text = new;
any = true;
}
}
moved.push((old_at, new_at));
if any {
changed += 1;
// Each ruby end moves with the text before it; an end inside a character keeps its
// distance from the last place recorded before it.
let to_new = |v: usize| {
let k = moved.partition_point(|&(old, _)| old <= v).saturating_sub(1);
moved.get(k).map_or(v, |&(old, new)| new + (v - old.min(v)))
};
for span in &mut t.ruby {
(span.start, span.end) = (to_new(span.start), to_new(span.end));
}
t.normalize_ruby();
refresh_bounds(t);
}
}
Ok(changed)
})?;
Ok(json!({
"changed": changed,
"replaced": {
"fiLigatures": n.fi_ligatures,
"flLigatures": n.fl_ligatures,
"quotes": n.quotes,
"spaces": n.spaces,
"dashes": n.dashes,
"ellipses": n.ellipses,
"fractions": n.fractions,
},
}))
}
// ---------- Area / Point conversion ----------
+4 -4
View File
@@ -222,11 +222,11 @@ pub fn written_elsewhere(path: &str) -> bool {
!cfg!(windows) && foreign && current().is_some()
}
/// Does a command param named `key` hold a file or folder path: `path`, `paths`, `file`, `files`,
/// `folder`, or a name ending in `Path`, `Paths`, `File`, `Files` or `Folder` (`diffPath`,
/// `destinationFolder`)?
/// Does a command param named `key` hold a file or folder path in a command that gives it no other
/// meaning ([`crate::cmd::key_location`]: `path`, `file`, `diffPath`, `destinationFolder` and the
/// like)? [`crate::cmd::ParamsPlace`] tells what it holds in a given command.
pub fn is_path_key(key: &str) -> bool {
matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end))
crate::cmd::key_location(key).is_some()
}
/// May `path` be written here? Always, without roots in force.
+3
View File
@@ -24,6 +24,9 @@ pub struct Interaction {
/// The perspective transform the previews make (`perspective.transform` params): Transform
/// Again repeats it once the drag is committed.
pub perspective_again: Option<Value>,
/// A preview drew an object on, or attached one to, a plane held by Automatic Plane
/// Positioning: the plane goes back to its place once the drag is committed.
pub(crate) plane_placed: bool,
/// A transform or a perspective edit with `copy` keeps the copies it made of the snapshot here
/// ([`PreviewCopies`]).
pub(crate) copies: Option<Arc<PreviewCopies>>,
+3
View File
@@ -329,6 +329,8 @@ impl Session {
// Ruler guides a reader left in the saved list become nodes on their layers.
doc.guides_into_nodes();
cmd::dimension::conform(&mut doc);
// A plane held by Automatic Plane Positioning when the file was saved is back in its place.
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc);
self.reset_tool_for_doc_switch();
let mut st = DocState::new(doc, path);
st.history.limit = self.prefs.history_states as usize;
@@ -357,6 +359,7 @@ impl Session {
doc.resolve_inline_art();
doc.guides_into_nodes();
cmd::dimension::conform(&mut doc);
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc);
// In the back, type set in a font named like a composite font is measured again below, in
// the document's own composite fonts, not in the front document's.
let back = self.active != Some(index);
+9
View File
@@ -289,6 +289,7 @@ impl Session {
variables_highlight: st.variables_highlight.clone(),
isolation: st.isolation,
perspective_again: None,
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
});
@@ -319,6 +320,7 @@ impl Session {
it.preview_paint = None;
it.color_mode_paints = None;
it.deferred_color_mode = None;
it.plane_placed = false;
if selection_changed {
st.selection.clone_from(&it.selection);
}
@@ -378,6 +380,7 @@ impl Session {
after.clone_from(&paint);
}
let perspective_again = it.perspective_again.take();
let plane_placed = it.plane_placed;
let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false);
// Alt pressed or released during a move drag turns it into a copy or back: name it for
// what it did in the end.
@@ -395,6 +398,12 @@ impl Session {
preview.1.get("dy").and_then(Value::as_f64).unwrap_or(0.0),
);
st.keep_interaction(it);
// The drag drew an object on, or attached one to, the plane Automatic Plane Positioning
// held: the plane is back in its place now, as view state (undoing the drag holds it again).
if plane_placed && changed && vectorcraft_tools::distort::perspective::PerspectiveGrid::positioning(&st.doc) {
vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(Arc::make_mut(&mut st.doc));
st.revision += 1;
}
if preview.0 == "object.transform" && changed {
let m = cmd::matrix_param(&preview.1, "matrix");
if let Some(m) = m {
+1
View File
@@ -128,6 +128,7 @@ mod pdffidelity;
mod pdfmarks;
mod pdfpresets;
mod pdfraster;
mod persp_infer;
mod persp_planes;
pub(super) mod persp_select;
mod persp_text;
+36
View File
@@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() {
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_");
}
/// `openLocation` (Open Location after Export) is remembered in the document's export settings,
/// outside presets; null removes it, and only true or false is taken.
#[test]
fn open_location_is_remembered_in_the_export_settings() {
let mut s = session();
let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone();
let r = run(&mut s, "assets.settings.set", json!({"openLocation": false}));
assert_eq!(open(&mut s), false);
assert!(r["settings"].get("openLocation").is_none(), "{r}");
// Create Sub-folders, on for a document without settings, stays on.
assert_eq!(r["settings"]["subfolders"], true, "{r}");
run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}}));
run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"}));
assert_eq!(open(&mut s), false, "a preset leaves it as it is");
run(&mut s, "assets.settings.set", json!({"openLocation": null}));
assert_eq!(open(&mut s), Value::Null);
for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] {
assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}");
}
}
/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export
/// for Screens opens with it off too; given with an export preset, the preset's folders stay.
#[test]
fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() {
let mut s = session();
let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone();
run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}}));
for preset in ["Logo Package", "Items"] {
run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false}));
assert_ne!(folders(&mut s), "none", "{preset}");
run(&mut s, "assets.settings.set", json!({"subfolders": false}));
assert_eq!(folders(&mut s), "none", "{preset}");
}
}
/// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on
/// for a folder per row; with Create Sub-folders off every file goes into the folder itself,
/// mobile and density rows too.
+139
View File
@@ -1490,6 +1490,93 @@ fn shape_builder_open_filled_paths_cut_without_open_filled_as_closed() {
assert!((area(&s, NodeId(r["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6);
}
/// The fill rows of an open path's appearance (bottom first) for the open-path tests below, with
/// a 1 pt black stroke on top: a painted fill under an unpainted top fill, a painted fill that is
/// hidden, one with an opacity of 0, and a painted fill under a hidden painted top fill.
fn open_path_fill_stacks() -> [(&'static str, Vec<AppearanceItem>, bool); 4] {
use vectorcraft_doc::{FillLayer, StrokeLayer};
let fill = |p: Paint, visible: bool, opacity: f32| {
let mut f = FillLayer::new(p);
f.visible = visible;
f.opacity = opacity;
AppearanceItem::Fill(f)
};
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0));
[
("a painted fill under an unpainted top fill", vec![fill(red(), true, 1.0), fill(Paint::None, true, 1.0), stroke()], true),
("a hidden painted fill", vec![fill(red(), false, 1.0), stroke()], false),
("a painted fill with an opacity of 0", vec![fill(red(), true, 0.0), stroke()], false),
("a painted fill under a hidden painted top fill", vec![fill(red(), true, 1.0), fill(blue(), false, 1.0), stroke()], true),
]
}
/// Consider Open Filled Paths as Closed: an open path counts as filled when any of its fill rows
/// draws (shown, painted and above 0% opacity), whichever row is on top. The map, a merge inside
/// the area and what a merge keeps of the path follow the rows that draw; with the option off, none
/// of the paths closes.
#[test]
fn shape_builder_closes_open_paths_by_the_fill_rows_that_draw() {
for (what, items, closes) in open_path_fill_stacks() {
let mut s = session();
let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(p).unwrap().appearance.items = items;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
let r = s.execute("shapeBuilder.regions", &json!({})).unwrap();
assert_eq!(
(r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()),
if closes { (1, 0) } else { (0, 1) },
"{what}: {r}"
);
let r = s.execute("shapeBuilder.regions", &json!({"openFilledAsClosed": false})).unwrap();
assert_eq!((r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), (0, 1), "{what}, option off: {r}");
let n = node(&s, p);
for on in [true, false] {
let inputs = vectorcraft_tools::builder::merge_inputs(&[&n], on);
assert_eq!(inputs.iter().map(|i| i.fill_closes).collect::<Vec<_>>(), vec![closes && on], "{what}, option {on}");
}
let merged = s.execute("shapeBuilder.merge", &json!({"points": [[75, 25]]}));
if closes {
assert!((area(&s, NodeId(merged.unwrap()["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6, "{what}");
} else {
assert!(merged.is_err(), "{what}: the open path encloses no region");
}
}
}
/// Clicking Stroke Splits the Path on the middle side of an open U cuts it along the outline its
/// drawn fill closes: with a fill row that draws, what is left runs on from the cut round the
/// implied closing edge (the top side, then the bottom side); without one, what is left is the
/// open path's two ends in path order (the bottom side, then the top side).
#[test]
fn shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw() {
for (what, items, closes) in open_path_fill_stacks() {
let mut s = session();
let r =
s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}]})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(p).unwrap().appearance.items = items;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
let r = s.execute("shapeBuilder.merge", &json!({"points": [[101, 50]], "splitStroke": true})).unwrap();
let out = ids(&r);
assert_eq!(shapes_of(&s, &out), vec![(false, 4, 200.0), (false, 2, 100.0)], "{what}");
let (rest, _) = outline(&node(&s, out[0]));
let starts: Vec<(f64, f64)> = rest.subpaths.iter().map(|sp| (sp.anchors[0].p.x.round(), sp.anchors[0].p.y.round())).collect();
let order = if closes { vec![(100.0, 100.0), (0.0, 0.0)] } else { vec![(0.0, 0.0), (100.0, 100.0)] };
assert_eq!(starts, order, "{what}");
}
}
/// Pick Color From Color Swatches: the merged shape takes the current fill, not the fill of the
/// object under the first point; setting the current fill without `ids` leaves the selection's.
#[test]
@@ -4105,6 +4192,58 @@ fn shape_builder_uses_the_filled_faces_of_a_live_paint_group() {
assert!((stroked_length(&s, &out) - 600.0).abs() < 1.0, "{}", stroked_length(&s, &out));
}
/// The Shape Builder takes a Live Paint face or edge when any of its fill or stroke rows draws,
/// whichever row is on top: a painted lower row under an unpainted top row counts, and a part
/// whose only painted row is hidden, transparent or (for an edge) 0 pt wide, or whose own opacity
/// is 0, does not.
#[test]
fn shape_builder_takes_the_live_paint_faces_and_edges_that_draw() {
use vectorcraft_doc::{FillLayer, StrokeLayer};
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let hidden = |mut i: AppearanceItem| {
match &mut i {
AppearanceItem::Fill(f) => f.visible = false,
AppearanceItem::Stroke(st) => st.visible = false,
}
i
};
let clear = |mut i: AppearanceItem| {
match &mut i {
AppearanceItem::Fill(f) => f.opacity = 0.0,
AppearanceItem::Stroke(st) => st.opacity = 0.0,
}
i
};
let mut s = session();
let g = live(&mut s);
let lower_fill = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), fill(Paint::None)], 1.0);
let hidden_fill = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red()))], 1.0);
let clear_fill = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![clear(fill(red()))], 1.0);
let lower_stroke = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 2.0), stroke(Paint::None, 1.0)], 1.0);
let hidden_stroke = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![hidden(stroke(red(), 2.0))], 1.0);
let thin_stroke = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0);
let clear_stroke = set_live_part(&mut s, g, None, Some((50.0, 50.0)), vec![clear(stroke(red(), 2.0))], 1.0);
let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0);
let parts = [lower_fill, hidden_fill, clear_fill, lower_stroke, hidden_stroke, thin_stroke, clear_stroke, clear_edge];
assert_eq!(parts.iter().collect::<std::collections::HashSet<_>>().len(), parts.len());
let d = s.doc().unwrap();
let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true);
let taken: Vec<NodeId> = leaves.iter().map(|l| l.id).collect();
assert!(taken.contains(&lower_fill) && taken.contains(&lower_stroke), "a painted lower row draws: {taken:?}");
for id in [hidden_fill, clear_fill, hidden_stroke, thin_stroke, clear_stroke, clear_edge] {
assert!(!taken.contains(&id), "{id:?} draws nothing: {taken:?}");
}
// A face with a painted fill whose own opacity is 0 is left out too.
let mut s = session();
let g = live(&mut s);
let clear_face = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![fill(red())], 0.0);
let d = s.doc().unwrap();
let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true);
assert!(!leaves.iter().any(|l| l.id == clear_face), "a face with an opacity of 0 draws nothing");
}
/// An edge that closes on itself is a line around its face, not a second shape over it.
#[test]
fn shape_builder_takes_a_closed_live_paint_edge_as_a_line() {
+36 -1
View File
@@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() {
assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0);
assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png");
assert!(s.execute("links.list", &json!({"show": "broken"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "size"})).is_err());
assert!(s.execute("links.list", &json!({"sort": "date"})).is_err());
}
#[test]
fn sort_by_size_lists_the_smallest_file_first() {
let dir = Folder::new("list-size");
let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))];
let mut s = session();
for (name, bytes) in &files {
let path = dir.file(name);
write(&path, bytes);
place(&mut s, &path);
}
let e = dir.file("e.png");
write(&e, &png(1, 1, RED));
place_embedded(&mut s, &e);
let names = |s: &mut Session| -> Vec<String> {
let l = run(s, "links.list", json!({"sort": "size"}));
l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect()
};
// Smallest first, equal sizes by name, the embedded image (no file) last.
let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect();
want.sort();
assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}");
let mut want: Vec<String> = want.iter().map(|(_, n)| n.to_string()).collect();
want.push("e.png".into());
assert_eq!(names(&mut s), want);
// A missing file sorts by the size the document keeps of it.
std::fs::remove_file(dir.file("a.png")).unwrap();
assert_eq!(names(&mut s), want);
// A modified file sorts by its size now.
let bigger = png(900, 900, BLUE);
assert!(bigger.len() > files[0].1.len());
write(&dir.file("c.png"), &bigger);
let got = names(&mut s);
assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]);
}
#[test]
+147 -1
View File
@@ -2234,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() {
("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")),
("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")),
("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")),
("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")),
("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")),
("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")),
("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")),
("type.smartPunctuation", json!({"scope": 5}), scope.clone()),
("type.smartPunctuation", json!({"scope": "page"}), scope),
("type.changeCase", json!({"case": 5}), string("case")),
@@ -3563,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() {
for id in [t, r] {
select_with_a_step_to_redo(&mut s, &[id]);
let before = history(&s);
assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}");
let r = s.execute("type.smartPunctuation", &json!({})).unwrap();
assert_eq!(r["changed"], 0, "{id:?}");
assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}");
assert_eq!(history(&s), before, "{id:?}");
}
assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…");
}
/// Does the face text `font` draws with have a glyph for every character of `chars`?
fn font_covers(font: &str, chars: &str) -> bool {
let face = vectorcraft_text::FontDb::global().face(font, "Regular");
face.is_some_and(|f| chars.chars().all(|c| f.covers(c)))
}
/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in
/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are.
#[test]
fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() {
let mut s = session();
assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions");
let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5.";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let undo = history(&s).0;
let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true});
let r = s.execute("type.smartPunctuation", &all).unwrap();
assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5.");
let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2});
assert_eq!(r, json!({"changed": 1, "replaced": replaced}));
assert_eq!(history(&s).0, undo + 1);
}
/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted
/// with this option), and the other options are off unless asked for.
#[test]
fn smart_punctuation_fl_ligatures_alone() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2");
assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0}));
}
/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's
/// other replacements still happen.
#[test]
fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() {
let mut s = session();
let mono = "JetBrains Mono";
assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh");
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap();
assert_eq!(plain(&s, t), "fit 1/7 a–b");
let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]);
assert_eq!(counts, (&json!(0), &json!(0), &json!(1)));
}
/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5
/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced.
#[test]
fn expert_fractions_look_past_the_end_of_a_run() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap());
for (start, end) in [(0, 3), (5, 8), (11, 14)] {
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap();
}
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x");
assert_eq!(r["replaced"]["fractions"], 1);
}
/// An inline graphic separates the text on either side of it: the space after it is not a second
/// space after the period before it, and the digit before it does not stop a fraction after it.
#[test]
fn an_inline_graphic_separates_smart_spaces_and_fractions() {
let mut s = session();
let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0);
sel(&mut s, &[r]);
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap());
s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap();
s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap();
let texts = |s: &Session| match node(s, t).kind {
NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::<String>(),
_ => String::new(),
};
assert_eq!(texts(&s), "A. [g] B 7[g]1/2");
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap();
assert_eq!(texts(&s), "A. [g] B 7[g]½");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1)));
}
/// Smart Spaces keeps one space after each period, also when the spaces start in the next run,
/// and leaves single spaces and spaces after other characters alone.
#[test]
fn smart_spaces_keeps_one_space_after_a_period() {
let mut s = session();
let t = text(&mut s, "A. B. C. D E");
// "C." is in a run of its own, and the spaces after it start the next one.
s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap();
assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1));
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap();
assert_eq!(plain(&s, t), "A. B. C. D E");
assert_eq!(r["replaced"]["spaces"], 2);
}
/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them
/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both
/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after
/// a period with ruby of its own stays.
#[test]
fn smart_punctuation_keeps_ruby_on_its_characters() {
let mut s = session();
let spans = |s: &Session, t| match node(s, t).kind {
NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::<Vec<_>>(),
_ => vec![],
};
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] {
s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap();
}
let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap();
assert_eq!(plain(&s, t), "‘A’. base fit X. Y");
assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0)));
let text = plain(&s, t);
let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect();
assert_eq!(on, ["A", "base", "i", " "]);
}
/// Expert Fractions leaves a fraction next to a digit of another script as it is.
#[test]
fn expert_fractions_skip_fractions_next_to_digits_of_any_script() {
let mut s = session();
let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2";
let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap());
sel(&mut s, &[t]);
let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap();
assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½");
assert_eq!(r["replaced"]["fractions"], 1);
}
#[test]
fn convert_point_area_roundtrip() {
let mut s = session();
+72
View File
@@ -775,6 +775,78 @@ fn create_outlines_draws_the_type_objects_own_paint() {
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
}
/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled
/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20
/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space).
fn transformed_gradient_type(s: &mut Session, fill: Value) -> NodeId {
let t = run(s, "text.create", json!({"x": 30, "y": 110, "text": "HIH", "size": 40}))["id"].as_u64().unwrap();
run(s, "select.set", json!({"ids": [t]}));
run(s, "type.ruby", json!({"text": "ab"}));
run(s, "text.setFormat", json!({"ids": [t], "underline": true, "strikethrough": true}));
run(s, "paint.setFill", fill);
run(s, "paint.setStroke", json!({"color": "#008000"}));
run(s, "stroke.set", json!({"weight": 2}));
run(s, "object.scale", json!({"ids": [t], "sx": 150, "sy": 150}));
run(s, "object.rotate", json!({"ids": [t], "angle": 20}));
NodeId(t)
}
/// Create Outlines draws what the type drew: a gradient on the characters that has no vector of
/// its own keeps one gradient across every glyph, ruby glyph and bar, fitted to the layout's box,
/// and one with a vector keeps it where it was, both with the type's scale and rotation. The
/// characters' stroke keeps the weight it was drawn at.
#[test]
fn create_outlines_keeps_a_character_gradient_across_the_type() {
let placed = json!({"gradient": {"kind": "linear", "start": [40, 100], "end": [110, 100],
"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}});
for fill in [red_blue(), placed] {
let mut s = session();
let t = transformed_gradient_type(&mut s, fill.clone());
let NodeKind::Text(text) = &node(&s, t).kind else { panic!("not type") };
assert!(!text.ruby.is_empty() && text.runs.iter().all(|r| r.style.underline && r.style.strikethrough), "{fill}");
// The characters' stroke is kept in text space and drawn scaled by the type's transform.
let weight = text.runs[0].style.stroke_layer().width;
let drawn = weight * vectorcraft_doc::Scaling::factor(text.xf).unwrap_or(1.0);
assert!((drawn - weight).abs() > 0.1, "the type's transform scales: {weight} {drawn}");
let before = render(&s);
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 60, "{fill}: {n} pixels differ");
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
// Every glyph, ruby glyph and bar takes the same gradient, placed, and the stroke at the
// weight it was drawn at.
let mut gradients = vec![];
let mut widths = vec![];
node(&s, NodeId(g)).walk(&mut |c: &Node| {
if let Paint::Gradient(gr) = c.appearance.fill_paint() {
gradients.push(gr.clone());
}
widths.extend(c.appearance.stroke().map(|st| st.width));
});
assert!(gradients.len() >= 6, "{fill}: three glyphs, ruby and two bars: {}", gradients.len());
assert!(gradients.iter().all(|gr| gr.is_placed() && *gr == gradients[0]), "{fill}: {gradients:?}");
assert!(widths.len() == gradients.len() && widths.iter().all(|w| (w - drawn).abs() < 1e-9), "{fill}: {drawn} {widths:?}");
}
}
/// Expand outlines the type before its fills expand, so a gradient on its characters that has no
/// vector of its own expands across the whole type, as the canvas draws it, and the query reports
/// it.
#[test]
fn expand_keeps_a_character_gradient_across_the_type() {
let mut s = session();
transformed_gradient_type(&mut s, red_blue());
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(true), json!(true), json!(true)), "{info}");
let before = render(&s);
run(&mut s, "object.expand", json!({}));
let after = render(&s);
assert_eq!(gradients_and_type(&s), (0, 0), "outlined and expanded");
let d = mean_diff(&before, &after);
assert!(d < 0.5, "{d}");
}
/// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which
/// Object turns into paths of its whole outline: a gradient only when that outline's box needs no
/// more runs than are written.
+273
View File
@@ -0,0 +1,273 @@
//! Automatic Plane Positioning: Shift held over an anchor point of art in perspective or over a
//! gridline intersection moves the active plane through it for now (`perspective.plane.infer`),
//! the two Perspective Grid Options that turn the targets on and off, and what ends it.
use serde_json::json;
use vectorcraft_geom::{Point, Vec2};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::tests_persp_select::{attached, bounds_of, drag, grid, persp_session, plane_pts, undo_len};
use crate::*;
fn shift() -> Mods {
Mods { shift: true, ..Default::default() }
}
/// The top anchor of path `id` (on the right wall at depth 0): its page point and its height.
fn top_anchor(s: &Session, id: NodeId) -> (Point, f64) {
let page: Vec<Point> = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
let plane = plane_pts(s, id, Plane::Right, 0.0);
page.into_iter().zip(plane).map(|(p, q)| (p, q.y)).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap()
}
fn hover(s: &mut Session, p: Point, mods: Mods) {
s.pointer(&PointerEvent::new(PointerKind::Move, p.x, p.y).with_mods(mods), ViewInfo::default()).unwrap();
}
fn revision(s: &Session) -> u64 {
s.doc().unwrap().revision
}
#[test]
fn shift_over_an_anchor_holds_the_active_plane_at_its_height_until_an_object_is_drawn() {
let (mut s, id) = persp_session();
let v = ViewInfo::default();
let (anchor, height) = top_anchor(&s, id);
assert!(height > 10.0, "{height}");
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
s.select_tool("perspectiveSelection", v).unwrap();
let steps = undo_len(&s);
// Without Shift the pointer only hovers.
hover(&mut s, anchor, Mods::default());
assert_eq!(grid(&s).inferred, None);
hover(&mut s, anchor, shift());
let g = grid(&s);
assert!(g.inferred.is_some());
assert!((g.offset(Plane::Ground) - height).abs() < 1e-6, "{} {height}", g.offset(Plane::Ground));
assert_eq!((g.ground_offset, g.shown_planes(), undo_len(&s)), (0.0, vec![Plane::Ground], steps));
// Held there already, another hover over the anchor changes nothing.
let rev = revision(&s);
hover(&mut s, anchor, shift());
assert_eq!(revision(&s), rev);
// The Rectangle tool draws on the plane where it is held, and the plane stays put for the drag.
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 400.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 470.0, 430.0), v).unwrap();
assert!(grid(&s).inferred.is_some(), "held while the object is drawn");
s.pointer(&PointerEvent::new(PointerKind::Up, 470.0, 430.0), v).unwrap();
let drawn = s.doc().unwrap().selection.objects[0];
assert_ne!(drawn, id);
let (plane, depth) = attached(&s, drawn).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
// Drawn, the plane is back in its place and the other planes show: one undo step for the drag.
let g = grid(&s);
assert_eq!((g.inferred, g.offset(Plane::Ground), g.shown_planes().len(), undo_len(&s)), (None, 0.0, 3, steps + 1));
// Undoing the drag holds the plane again; Escape with the Perspective Selection tool ends that.
s.execute("edit.undo", &json!({})).unwrap();
assert!(grid(&s).inferred.is_some());
s.select_tool("perspectiveSelection", v).unwrap();
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert_eq!(grid(&s).inferred, None);
}
#[test]
fn shift_during_a_drag_still_constrains_the_move() {
let (mut s, id) = persp_session();
let v = ViewInfo::default();
s.select_tool("perspectiveSelection", v).unwrap();
let before = plane_pts(&s, id, Plane::Right, 0.0);
let h = grid(&s).homography(Plane::Right).unwrap();
// From the middle of the object, along the wall and a little up.
let start = bounds_of(&before).center();
let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap());
drag(&mut s, &[from, to, to], shift());
assert_eq!(grid(&s).inferred, None, "with a button down Shift constrains the move");
for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) {
assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "{a:?} → {b:?}");
}
}
#[test]
fn a_gridline_intersection_brings_each_plane_made_active_through_it() {
let (mut s, _) = persp_session();
let (g, steps) = (grid(&s), undo_len(&s));
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
let at = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y], "tolerance": 1})).unwrap();
assert_eq!((r["active"].as_bool(), r["source"].as_str(), r["plane"].as_str()), (Some(true), Some("gridline"), Some("left")));
for (got, want) in r["point"].as_array().unwrap().iter().zip([0.0, 2.0 * g.cell, 3.0 * g.cell]) {
assert!((got.as_f64().unwrap() - want).abs() < 1e-6, "{r}");
}
for (plane, want) in [("ground", 2.0 * g.cell), ("right", 3.0 * g.cell), ("left", 0.0)] {
s.execute("perspective.plane.set", &json!({"plane": plane})).unwrap();
let r = s.execute("perspective.plane.infer", &json!({})).unwrap();
assert!((r["offset"].as_f64().unwrap() - want).abs() < 1e-6 && r["active"] == json!(true) && r.get("source").is_none(), "{plane}: {r}");
}
let held = grid(&s);
assert_eq!((held.left_offset, held.right_offset, held.ground_offset, undo_len(&s)), (0.0, 0.0, 0.0, steps));
// Nothing within reach leaves the plane where it is held.
let rev = revision(&s);
let mid = held.to_page(Plane::Left, Point::new(3.5 * g.cell, 2.5 * g.cell)).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [mid.x, mid.y], "tolerance": 0.5})).unwrap();
assert!(r["active"] == json!(true) && r.get("source").is_none() && revision(&s) == rev, "{r}");
// With no active plane nothing is held.
s.execute("perspective.plane.set", &json!({"plane": "none"})).unwrap();
assert_eq!(grid(&s).inferred, None);
assert!(s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y]})).is_err(), "no active plane");
assert_eq!(s.execute("perspective.plane.infer", &json!({})).unwrap()["active"], json!(false));
}
#[test]
fn the_two_options_turn_the_targets_on_and_off_and_are_kept() {
let (mut s, id) = persp_session();
assert!(s.prefs.perspective_widget.anchor_point && s.prefs.perspective_widget.gridline_intersection, "both on by default");
let (anchor, _) = top_anchor(&s, id);
let infer = |s: &mut Session| s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01}));
assert_eq!(infer(&mut s).unwrap()["source"], json!("anchor"));
s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap();
let r = s.execute("perspective.widget.options", &json!({"anchorPoint": false})).unwrap();
assert_eq!((r["anchorPoint"].as_bool(), r["gridlineIntersection"].as_bool(), r["show"].as_bool()), (Some(false), Some(true), Some(true)));
assert!(infer(&mut s).unwrap().get("source").is_none(), "the anchor is no target now");
assert_eq!(grid(&s).inferred, None);
let back: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
assert!(!back.perspective_widget.anchor_point && back.perspective_widget.gridline_intersection);
s.execute("perspective.widget.options", &json!({"gridlineIntersection": false})).unwrap();
assert!(infer(&mut s).is_err(), "both off");
for bad in [json!({"anchorPoint": "yes"}), json!({"gridlineIntersection": 1})] {
assert!(s.execute("perspective.widget.options", &bad).is_err(), "{bad}");
}
assert!(!s.prefs.perspective_widget.anchor_point, "a refused value changes nothing");
s.execute("prefs.set", &json!({"key": "perspectiveWidget", "value": {"anchorPoint": true}})).unwrap();
assert!(s.prefs.perspective_widget.anchor_point && !s.prefs.perspective_widget.gridline_intersection);
// Preferences saved before the options existed read as both on.
let old: vectorcraft_tools::distort::perspective::widget::WidgetOptions = serde_json::from_value(json!({"show": false})).unwrap();
assert!(old.anchor_point && old.gridline_intersection && !old.show);
}
#[test]
fn bad_params_are_refused_and_leave_the_grid_as_it_is() {
let (mut s, id) = persp_session();
let (anchor, _) = top_anchor(&s, id);
let rev = revision(&s);
for bad in [
json!({"at": "here"}),
json!({"at": [1]}),
json!({"at": [anchor.x, anchor.y], "tolerance": -1}),
json!({"at": [anchor.x, anchor.y], "tolerance": "wide"}),
json!({"at": [anchor.x, anchor.y], "clear": true}),
json!({"clear": "yes"}),
] {
assert!(s.execute("perspective.plane.infer", &bad).is_err(), "{bad}");
}
assert_eq!((grid(&s).inferred, revision(&s)), (None, rev));
// Clearing when nothing is held changes nothing.
assert_eq!(s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap()["active"], json!(false));
assert_eq!(revision(&s), rev);
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
assert!(s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y]})).is_err(), "hidden grid");
}
/// A session whose ground plane is held at the height of the attached rectangle's top anchor.
fn held_session() -> (Session, NodeId, f64) {
let (mut s, id) = persp_session();
let (anchor, height) = top_anchor(&s, id);
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
let r = s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})).unwrap();
assert_eq!(r["source"], json!("anchor"));
(s, id, height)
}
#[test]
fn attaching_an_object_ends_it_and_the_object_sits_where_the_plane_was_held() {
let (mut s, _, height) = held_session();
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let flat = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [flat.0]})).unwrap();
let (plane, depth) = attached(&s, flat).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
assert_eq!((grid(&s).inferred, grid(&s).ground_offset), (None, 0.0));
// An attach of nothing, or to a plane it doesn't hold, leaves it held.
let (mut s, ..) = held_session();
s.execute("perspective.attach", &json!({"ids": []})).unwrap();
assert!(grid(&s).inferred.is_some());
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let other = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [other.0], "plane": "right"})).unwrap();
assert_eq!(attached(&s, other).map(|a| a.0), Some(Plane::Right));
assert!(grid(&s).inferred.is_some());
// A move of an object already in perspective leaves it held; one brought into perspective ends it.
let (mut s, id, height) = held_session();
s.execute("perspective.move", &json!({"ids": [id.0], "from": [460, 400], "to": [470, 400]})).unwrap();
assert!(grid(&s).inferred.is_some());
let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap();
let flat = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.move", &json!({"ids": [flat.0], "from": [430, 410], "to": [440, 410]})).unwrap();
let (plane, depth) = attached(&s, flat).unwrap();
assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}");
assert_eq!(grid(&s).inferred, None);
}
#[test]
fn moving_a_plane_hiding_the_grid_and_reopening_the_file_end_it() {
// A moved plane moves from where it is held and is placed there for good, in one undo step;
// undoing the move holds it again.
let (mut s, _, height) = held_session();
let steps = undo_len(&s);
s.execute("perspective.plane.move", &json!({"plane": "ground", "by": 10})).unwrap();
let g = grid(&s);
assert_eq!((g.inferred, undo_len(&s)), (None, steps + 1));
assert!((g.ground_offset - (height + 10.0)).abs() < 1e-6, "{}", g.ground_offset);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).inferred.is_some(), grid(&s).ground_offset), (true, 0.0));
// A refused move leaves it held.
let (mut s, ..) = held_session();
assert!(s.execute("perspective.plane.move", &json!({"plane": "ground", "offset": 1, "objects": "all"})).is_err());
assert!(grid(&s).inferred.is_some());
// A plane dragged while it is held, then the drag canceled, is held again.
let (mut s, ..) = held_session();
s.begin_interaction("Move Plane").unwrap();
s.preview("perspective.plane.move", &json!({"plane": "ground", "by": 20})).unwrap();
assert_eq!(grid(&s).inferred, None);
s.cancel_interaction().unwrap();
assert!(grid(&s).inferred.is_some());
// Move Plane to Match Object.
let (mut s, id, _) = held_session();
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
assert_eq!((grid(&s).inferred, grid(&s).plane), (None, Plane::Right));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((grid(&s).inferred.is_some(), grid(&s).plane), (true, Plane::Ground), "undo holds it again");
// With the plane placed at the object already, matching only puts the held plane back there.
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
assert!(grid(&s).inferred.is_some());
let steps = undo_len(&s);
s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap();
assert_eq!((grid(&s).inferred, grid(&s).offset(Plane::Right), undo_len(&s)), (None, 0.0, steps));
// Hide Grid.
let (mut s, ..) = held_session();
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
assert_eq!(grid(&s).inferred, None);
// The grid's definition changing leaves it held, and it is not `perspective.grid.set`'s to set.
let (mut s, ..) = held_session();
let held = grid(&s).inferred;
s.execute("perspective.grid.set", &json!({"cell": 31, "inferred": [1, 2, 3]})).unwrap();
assert_eq!(grid(&s).inferred, held);
// `perspective.grid.set` hiding the grid or choosing no plane ends it.
for patch in [json!({"visible": false}), json!({"plane": "none"})] {
let (mut s, ..) = held_session();
s.execute("perspective.grid.set", &patch).unwrap();
assert_eq!(grid(&s).inferred, None, "{patch}");
}
// Another preset leaves it held, as other changes to the grid's definition do.
let (mut preset, ..) = held_session();
let before = grid(&preset).inferred;
preset.execute("perspective.grid.preset", &json!({"kind": 3})).unwrap();
assert_eq!((grid(&preset).kind, grid(&preset).inferred), (3, before));
// A file saved while a plane is held opens with the plane in its place.
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
let back = vectorcraft_format::load(&saved).unwrap();
assert!(PerspectiveGrid::positioning(&back), "the saved file still holds the point");
s.add_document(back, None);
assert_eq!(grid(&s).inferred, None);
assert_eq!(grid(&s).cell, 31.0);
}
+4 -1
View File
@@ -520,7 +520,10 @@ fn the_plane_widget_stays_on_screen_and_takes_clicks_with_any_tool() {
click(&mut s, q, view);
assert_eq!(grid(&s).plane, Plane::Ground);
// Perspective Grid Options move it to another corner or hide it.
assert_eq!(run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), json!({"show": true, "position": "bottomRight"}));
assert_eq!(
run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})),
json!({"show": true, "position": "bottomRight", "anchorPoint": true, "gridlineIntersection": true})
);
let r = face(&s, view, WidgetCorner::BottomRight, Plane::Left);
assert!(r.x > 100.0 + 450.0 && r.y > 50.0 + 300.0, "{r:?}");
click(&mut s, r, view);
@@ -599,6 +599,100 @@ fn with_link_a_pdf_page_places_linked() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// The colour at the centre of `r` in `doc`.
fn colour_at(doc: &Document, r: Rect) -> [u8; 3] {
let img = vectorcraft_render::Renderer::new().render_region(doc, r, 1.0, true);
let [red, g, b, _] = img.pixel((r.width() / 2.0) as u32, (r.height() / 2.0) as u32);
[red, g, b]
}
#[test]
fn link_pages_opens_each_picked_pdf_page_as_a_linked_placed_document() {
let dir = Folder::new("open-pdf-link-pages");
let src = dir.file("flyer.pdf");
pdf_source(&src, "pdf", &[RED, BLUE, RED], 0);
let mut s = Session::new();
let r = s.execute("document.open", &json!({"path": src, "linkPages": true, "pages": "2-3"})).unwrap();
assert_eq!((r["format"].as_str(), r["restored"].as_bool()), (Some("pdf"), Some(false)), "{r}");
let st = s.doc().unwrap();
assert_eq!(st.path, None, "Save asks for a name instead of writing over the PDF");
let d = &st.doc;
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(136.0, 0.0, 236.0, 50.0)]);
let layers: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
assert_eq!(layers, ["Page 2", "Page 3"]);
let mut ids = vec![];
for (layer, (page, board)) in d.layers.iter().zip([(2, boards[0]), (3, boards[1])]) {
let kids = layer.children().unwrap();
assert_eq!(kids.len(), 1);
let p = placed(&s, kids[0].id);
assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(page), false), "{p:?}");
assert_eq!(bounds(&s, kids[0].id), board);
ids.push(kids[0].id);
}
assert!(near(colour_at(d, boards[0]), BLUE));
assert!(near(colour_at(d, boards[1]), RED));
let links = s.execute("links.list", &json!({})).unwrap()["links"].clone();
assert_eq!(links.as_array().map(Vec::len), Some(2), "{links}");
assert!(links.as_array().unwrap().iter().all(|row| row["document"] == true && row["status"] == "ok"), "{links}");
// Embed makes a page editable art.
s.execute("links.embed", &json!({"ids": [ids[0].0]})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(ids[0]).unwrap().kind_label(), "Clip Group");
assert_eq!(bounds(&s, ids[0]), boards[0]);
assert!(near(colour_at(d, boards[0]), BLUE));
// Every page, with the art's bounds as the artboard.
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards.len(), 3);
assert!(d.layers.iter().flat_map(|l| l.children().unwrap()).all(|n| matches!(&n.kind, NodeKind::PlacedDocument(p) if p.bounding)));
}
#[test]
fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
use vectorcraft_testkit::pdf::{PdfPage, pdf};
let dir = Folder::new("open-pdf-link-pages-cmyk");
let src = dir.file("cmyk.pdf");
let page = || PdfPage::new(100.0, 50.0, "0 0.5 1 0 k 0 0 100 50 re f");
write(&src, &pdf(&[page(), page(), page()], None));
let mut s = Session::new();
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.color_mode, vectorcraft_doc::ColorMode::Cmyk, "pages painted in CMYK open as a CMYK document");
let blobs: Vec<_> = d.images.values().map(|b| b.bytes.clone()).collect();
assert_eq!(blobs.len(), 3);
assert!(blobs.iter().all(|b| std::sync::Arc::ptr_eq(b, &blobs[0])), "one copy of the file for every page");
s.execute("document.open", &json!({"path": src, "linkPages": true, "colorMode": "rgb"})).unwrap();
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
}
#[test]
fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() {
let dir = Folder::new("open-pdf-link-pages-refused");
let src = dir.file("flyer.pdf");
pdf_source(&src, "pdf", &[RED, BLUE], 0);
let bytes = std::fs::read(&src).unwrap();
let logo = dir.file("logo.vectorcraft");
source(&logo, 100.0, 50.0, RED, 0);
let mut s = Session::new();
let cases = [
(json!({"name": "flyer.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "linkPages": true}), "needs the file's path"),
(json!({"path": logo, "linkPages": true}), "isn't a PDF"),
(json!({"path": src, "linkPages": true, "password": "secret"}), "password"),
(json!({"path": src, "linkPages": true, "textAs": "outlines"}), "textAs: outlines"),
(json!({"path": src, "linkPages": "yes"}), "linkPages must be true or false"),
(json!({"path": src, "linkPages": true, "pages": "3"}), "pages:"),
];
for (p, says) in cases {
let e = s.execute("document.open", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
assert!(s.documents().is_empty(), "nothing opened");
// Off, the pages open as editable art.
s.execute("document.open", &json!({"path": src, "linkPages": false})).unwrap();
assert!(!s.doc().unwrap().doc.has_placed());
}
#[test]
fn a_changed_pdf_is_modified_and_update_links_reads_it_again() {
let dir = Folder::new("placed-pdf-update");
+103 -41
View File
@@ -2265,6 +2265,36 @@ fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n'));
}
#[test]
fn remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames() {
for command in ["object.lock", "object.hide"] {
for held_first in [false, true] {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
let (held, other) = if held_first { (a, b) } else { (b, a) };
let unrelated = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
let unrelated = NodeId(unrelated);
s.execute(command, &json!({"ids": [held.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("{command}, held first: {held_first}");
let steps = undo_labels(&s).len();
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text());
assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "{case}: every frame's returns go");
assert_eq!(obj(&s, unrelated).plain_text(), "One\nTwo", "{case}: other type is as it was");
// No return is left: another call fails and adds no undo step.
assert!(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).is_err());
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
}
}
}
#[test]
fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
@@ -2306,41 +2336,72 @@ fn convert_to_text_takes_the_whole_story_that_select_all_selected() {
}
}
/// Whether no paragraph of type `id` is a list.
fn no_list(s: &Session, id: NodeId) -> bool {
let t = obj(s, id);
(0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none())
}
/// The bullets held as characters in the frames `ids`.
fn bullet_chars(s: &Session, ids: &[NodeId]) -> usize {
ids.iter().map(|id| obj(s, *id).plain_text().matches("\u{2022}\t").count()).sum()
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() {
// Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story.
for named in [false, true] {
let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame();
s.execute("object.lock", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
// The first frame ends with a paragraph return, so the paragraph that starts the locked
// frame takes in the first frame's empty last part and starts its text there.
let in_a = obj(&s, a).plain_text();
assert!(in_a.ends_with('\n'));
let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count();
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})");
assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert");
assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0)));
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted");
let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count();
assert_eq!(markers, own, "the locked frame's first paragraph keeps its list");
// The converted text is longer, so the story flows on into the locked frame; its own
// paragraphs stay a list.
let last = tb.paragraph_count() - 2;
assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})");
assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n"));
assert!(s.tool_options().get("story").is_some(), "the whole story stays selected");
fn convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames() {
// Over MCP without ids, as the Paragraph panel sends it with every frame of the story, and with
// ids naming only the held frame.
for command in ["object.lock", "object.hide"] {
for held_first in [false, true] {
for call in ["none", "story", "held"] {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
let (held, other) = if held_first { (a, b) } else { (b, a) };
let unrelated =
s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap();
let unrelated = NodeId(unrelated);
s.execute("text.setFormat", &json!({"ids": [unrelated.0], "list": "bullet"})).unwrap();
let unrelated_before = obj(&s, unrelated);
s.execute(command, &json!({"ids": [held.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("{command}, held first: {held_first}, ids: {call}");
let p = match call {
"none" => json!({}),
"story" => json!({"ids": [a.0, b.0]}),
_ => json!({"ids": [held.0]}),
};
let steps = undo_labels(&s).len();
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step");
assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed");
assert!(no_list(&s, held), "{case}: the held frame leaves its list");
assert_eq!(obj(&s, unrelated), unrelated_before, "{case}: other type is as it was");
if call == "held" {
// The other frame's paragraphs whose text starts there keep their list.
assert!(!no_list(&s, other), "{case}: the frame not named keeps its list");
continue;
}
assert!(no_list(&s, other), "{case}: the other frame leaves its list");
assert_eq!(bullet_chars(&s, &[a, b]), 12, "{case}: each paragraph's bullet is held once as characters");
assert!(s.tool_options().get("story").is_some(), "{case}: the whole story stays selected");
// Nothing is a list any more: another call changes nothing and adds no undo step.
s.execute("text.convertListToText", &p).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text");
assert!(!no_list(&s, a) && !no_list(&s, b), "{case}: undo restores the lists");
}
}
}
}
#[test]
fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() {
for named in [false, true] {
fn convert_to_text_of_the_whole_story_converts_a_paragraph_that_runs_across_a_locked_frame() {
// The paragraph that runs from the first frame into the second starts in the locked frame, or
// ends in it.
for (named, lock_first) in [(false, true), (true, true), (false, false), (true, false)] {
let mut s = session();
let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40));
let a = NodeId(
@@ -2354,22 +2415,23 @@ fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked
s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap();
let in_a = obj(&s, a).plain_text();
assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second");
s.execute("object.lock", &json!({"ids": [a.0]})).unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let (locked, other) = if lock_first { (a, b) } else { (b, a) };
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0}));
s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0}));
assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0]));
let case = format!("ids named: {named}, first frame locked: {lock_first}");
let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) };
let r = s.execute("text.convertListToText", &p).unwrap();
assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})");
// The two paragraphs that start in the editable frame, and the empty one that ends the story.
assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert");
assert_eq!(r["ids"], json!([a.0, b.0]), "{case}: both frames are changed");
// The five paragraphs with text, and the empty one that ends the story.
assert_eq!(r["converted"], json!(6), "{case}: every paragraph of the story converts");
let (ta, tb) = (obj(&s, a), obj(&s, b));
assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was");
assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list");
assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list");
assert!(!tb.plain_text().starts_with('\u{2022}'));
assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2);
assert!(no_list(&s, a) && no_list(&s, b), "{case}: the story leaves its list");
assert_eq!(bullet_chars(&s, &[a, b]), 5, "{case}: each paragraph's bullet is held once as characters");
assert!(ta.plain_text().contains("\u{2022}\tGamma"), "{case}: the paragraph across the frames takes its bullet where its text starts");
assert!(!tb.plain_text().starts_with('\u{2022}'), "{case}");
}
}
+3 -1
View File
@@ -429,6 +429,7 @@ impl Session {
},
screen: view.screen,
plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position),
plane_targets: self.prefs.perspective_widget.targets(),
precise_cursors: self.precise_cursors(),
global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()),
};
@@ -1543,7 +1544,7 @@ impl Session {
if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) {
return None;
}
let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone());
let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed);
(st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields)
};
let (overlays, transform_box) = if self.preview(cmd, p).is_ok() {
@@ -1565,6 +1566,7 @@ impl Session {
it.preview = interaction_fields.0;
it.copies = interaction_fields.1;
it.perspective_again = interaction_fields.2;
it.plane_placed = interaction_fields.3;
}
}
self.pending_paint = paint;
+127 -19
View File
@@ -5,6 +5,7 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_engine::cmd::{Location, ParamsPlace};
use vectorcraft_engine::{Session, command_specs};
use vectorcraft_testkit::catch_quiet;
use vectorcraft_testkit::fixtures::Fixture;
@@ -272,44 +273,46 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value
cases
}
/// The strings in `v`, the value at `at` in a case of command `id`, that name a place on disk
/// outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when `named` (it is
/// under a key that names a file or folder), and in objects at any depth, the values under such
/// keys ([`names_location`]).
fn outside_locations(id: &str, at: &str, v: &Value, named: bool, dir: &std::path::Path, out: &mut std::collections::BTreeSet<String>) {
/// The strings in `v`, the value at `at` (found at `place`) in a case of command `id`, that name a
/// place on disk outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when
/// `named` (it is under a key that names a file or folder), and in objects at any depth, the values
/// under such keys as the command reads them (`vectorcraft_engine::cmd::ParamsPlace`).
fn outside_locations(
id: &str,
at: &str,
v: &Value,
place: ParamsPlace,
named: bool,
dir: &std::path::Path,
out: &mut std::collections::BTreeSet<String>,
) {
match v {
Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => {
out.insert(format!("{id} {at}: {v}"));
}
Value::Array(a) => {
let step = ParamsPlace::step(a);
for (i, x) in a.iter().enumerate() {
outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out);
outside_locations(id, &format!("{at}[{i}]"), x, place.item(i, step), named, dir, out);
}
}
Value::Object(o) => {
let carried = ParamsPlace::carried(o);
for (k, x) in o {
outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out);
let (below, location) = place.member(k, carried);
outside_locations(id, &format!("{at}.{k}"), x, below, location.is_some(), dir, out);
}
}
_ => {}
}
}
/// Does `key` name a file or folder, in command `spec` when given: a key in
/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps
/// for `spec`.
fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool {
match spec {
Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(),
None => vectorcraft_engine::cmd::key_location(key).is_some(),
}
}
/// Every string the sweeps send under a key that names a file or folder, in the command catalog
/// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside
/// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or
/// writes in the working directory. `every_command_with_junk_params` sends every such key of every
/// command alone in at least one case ([`junk_cases`]).
/// command alone in at least one case ([`junk_cases`]). Which catalog keys name a file or folder is
/// checked on its own by [`catalog_path_keys_match_location_policy`].
#[test]
fn sweep_cases_name_files_only_inside_the_temp_folder() {
let dir = vectorcraft_testkit::TempDir::new("sweep");
@@ -330,7 +333,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() {
for p in &cases {
let Some(o) = p.as_object() else { continue };
for (k, v) in o {
outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside);
let (below, location) = ParamsPlace::top(Some(c)).member(k, None);
outside_locations(c.id, k, v, below, location.is_some(), &dir, &mut outside);
}
}
}
@@ -339,6 +343,104 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() {
assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n"));
}
/// The param keys that name a file or a folder, and which.
const LOCATION_KEYS: &[(&str, Location)] = &[
("path", Location::File),
("paths", Location::File),
("file", Location::File),
("files", Location::File),
("diffPath", Location::File),
("folder", Location::Folder),
("dir", Location::Folder),
("directory", Location::Folder),
("destinationFolder", Location::Folder),
("sourceFolder", Location::Folder),
("fontsFolder", Location::Folder),
("pluginsFolder", Location::Folder),
("recoveryFolder", Location::Folder),
("templatesFolder", Location::Folder),
];
/// Param keys that read like a file or folder key ([`reads_like_a_location`]) and name neither:
/// web links, an export's grouping of its files, and choices and switches.
const NOT_LOCATIONS: &[&str] = &[
"url",
"copyrightUrl",
"folders",
"alignToPath",
"wholePaths",
"emptyTextPaths",
"sortPaths",
"alterPaths",
"includeLinkedFiles",
"linksFolder",
];
/// Commands and the key in [`LOCATION_KEYS`] that, at the top of their params, names part of the
/// document (a path of its art, a result field), not a file.
const DOCUMENT_PARTS: &[(&str, &str)] = &[
("object.setLiveShape", "path"),
("path.reverse", "paths"),
("object.pathfinder.options", "paths"),
("object.maskImage", "path"),
("text.createInPath", "path"),
("symbol.instance.setAppearance", "path"),
("symbol.instance.selectPart", "path"),
("object.objectsOnPath.attach", "path"),
("svgInteractivity.info", "files"),
("addon.cleanup.rejoin", "paths"),
];
/// Does param key `k` read like one that names a file, a folder or a link: a bare name for one, or a
/// name that ends like one?
fn reads_like_a_location(k: &str) -> bool {
const ENDS: &[&str] = &["Path", "Paths", "File", "Files", "Folder", "Folders", "Dir", "Directory", "Url", "URL"];
matches!(k, "path" | "paths" | "file" | "files" | "folder" | "folders" | "dir" | "directory" | "url") || ENDS.iter().any(|end| k.ends_with(end))
}
/// Every key of every command that reads like a file or folder key (in its params description, the
/// commands its `…` entries name and its schema) is in [`LOCATION_KEYS`] or [`NOT_LOCATIONS`], so a
/// command that adds one fails here until it is sorted. The generic classifications
/// (`vectorcraft_engine::cmd::key_location`, `vectorcraft_engine::file_access::is_path_key`) agree
/// with those lists, and each command reads such a key as they say (`location_in`), less
/// [`DOCUMENT_PARTS`].
#[test]
fn catalog_path_keys_match_location_policy() {
use vectorcraft_engine::cmd::{key_location, location_in, params::takes_key};
let catalog: Vec<(&vectorcraft_engine::CommandSpec, Vec<String>)> = command_specs().iter().map(|c| (c, command_param_keys(c))).collect();
let mut keys: std::collections::BTreeSet<String> =
catalog.iter().flat_map(|(_, keys)| keys.iter().filter(|k| reads_like_a_location(k)).cloned()).collect();
keys.extend(LOCATION_KEYS.iter().map(|(k, _)| k.to_string()).chain(NOT_LOCATIONS.iter().map(|k| k.to_string())));
let mut wrong = vec![];
for k in &keys {
let want = LOCATION_KEYS.iter().find(|(l, _)| l == k).map(|(_, l)| *l);
if want.is_none() && !NOT_LOCATIONS.contains(&k.as_str()) {
wrong.push(format!("`{k}` is in neither LOCATION_KEYS nor NOT_LOCATIONS"));
continue;
}
if key_location(k) != want {
wrong.push(format!("key_location(`{k}`) is {:?}, not {want:?}", key_location(k)));
}
if vectorcraft_engine::file_access::is_path_key(k) != want.is_some() {
wrong.push(format!("is_path_key(`{k}`) is {}", want.is_none()));
}
for (c, named) in &catalog {
if !named.contains(k) && !(c.params.contains('…') && takes_key(c.params, k)) {
continue;
}
let here = if DOCUMENT_PARTS.contains(&(c.id, k.as_str())) { None } else { want };
if location_in(c, k) != here {
wrong.push(format!("{}: location_in(`{k}`) is {:?}, not {here:?}", c.id, location_in(c, k)));
}
}
}
for (id, key) in DOCUMENT_PARTS {
let named = catalog.iter().any(|(c, _)| c.id == *id && c.params.contains(key));
assert!(named, "{id} doesn't name `{key}`");
}
assert!(wrong.is_empty(), "{} keys are classified unlike the reviewed lists:\n{}", wrong.len(), wrong.join("\n"));
}
/// The cases sweep keys the command catalog names as files and folders: `document.open`'s
/// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s
/// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s
@@ -914,6 +1016,12 @@ fn structured_junk() {
("addon.cutting.banner", json!({"hem": 0, "grommetInset": 0, "spacing": 0.01, "allArtboards": true})),
("addon.cutting.banner", json!({"spacing": "1 mm", "grommets": false, "swatch": 5, "left": null})),
("addon.cutting.banner", json!({"top": false, "right": false, "bottom": false, "left": false, "allArtboards": false})),
("addon.cutting.nest", json!({"width": 1e6, "height": 1e6, "margin": 1e5, "spacing": 1e5, "roll": true})),
("addon.cutting.nest", json!({"width": 1e-300, "height": f64::MAX, "margin": -1, "spacing": "1 mm", "artboard": u64::MAX})),
("addon.cutting.nest", json!({"width": 0, "height": 0, "margin": 0, "spacing": 0, "usePreviewBounds": "no", "patterns": 1})),
("addon.cutting.nest", json!({"roll": null, "artboard": -1, "width": "1 in", "height": [1]})),
("addon.cutting.nest", json!({"rotate": true, "roll": true, "width": 1e-6, "margin": 0, "spacing": 0, "usePreviewBounds": true})),
("addon.cutting.nest", json!({"rotate": "yes", "width": f64::NAN, "spacing": -0.0})),
// Type Tools add-on.
("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})),
("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})),
+160
View File
@@ -1187,6 +1187,32 @@ fn a_symbol_definition_is_written_only_with_room_for_its_instance() {
}
}
/// A live instance inside a stained instance's art, whose definition has no room left, is left out
/// without upsetting the art around it: with room for any number of objects the export finishes,
/// within that room.
#[test]
fn a_definition_without_room_inside_drawn_art_is_left_out() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let leaf = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaf) });
let inner = instance(&mut doc, "Leaf", Affine::translate((5.0, 5.0)));
let side = square(&mut doc, Rect::new(20.0, 0.0, 30.0, 10.0), Color::gray(0.5));
let art = group(&mut doc, vec![inner, side], false);
doc.symbols.push(Symbol { dynamic: false, name: "Branch".into(), art: Arc::new(art) });
let mut stained = instance(&mut doc, "Branch", Affine::translate((50.0, 10.0)));
stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
doc.insert(Some(layer), usize::MAX, stained).unwrap();
add_rect(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0));
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
for max in 0..read {
let out = export_within(&doc, &opts(), max).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "art is left out with room for {max} of {read} objects");
let objects = crate::import::objects_read(&out.program).unwrap();
assert!(objects <= max, "{objects} objects read with room for {max}");
}
}
/// A symbol definition without room for its group, asked for by an instance in art drawn for an
/// object (a stained instance's art), is left out and leaves the writing of that art as it was.
#[test]
@@ -10168,6 +10194,119 @@ fn envelopes_past_the_readers_checks_are_written_as_their_art() {
assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
}
/// A document of `envelopes` envelopes and `images` embedded images with one Warp, the images first
/// when `images_first`, saved and opened again: the live envelopes, the images with their Warp live
/// and all the objects it opens with, the save's warnings and the open's notes.
fn envelopes_and_warped_images(envelopes: usize, images: usize, images_first: bool) -> (usize, usize, usize, Vec<String>, Vec<String>) {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let add_images = |doc: &mut Document| {
for _ in 0..images {
let photo = warped_photo(doc, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]);
doc.insert(Some(layer), usize::MAX, photo).unwrap();
}
};
if images_first {
add_images(&mut doc);
}
for _ in 0..envelopes {
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
}
if !images_first {
add_images(&mut doc);
}
let (p, warnings) = private_data(&doc, &opts()).unwrap();
let (back, notes) = crate::ai_alone(&p.data).unwrap();
let a = back.layers[0].children().unwrap();
let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count();
let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count();
(live, warped, a.len(), warnings, notes)
}
/// Images with a Warp take the reader's checks as envelopes do: past them, an image is written as
/// its drawn look, with a warning, and the file opens with every object written live still live.
#[test]
fn warped_images_past_the_readers_checks_are_written_as_their_drawn_look() {
// GUARDS: images with a Warp were written live past the checks the envelopes left, and the
// file opened with the last one as its drawn look and no warning on saving.
let limit = crate::import::ENVELOPE_CHECKS;
let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, false);
assert_eq!((live, warped, all), (limit - 1, 1, limit + 1), "{warnings:?} {notes:?}");
assert!(warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
}
/// An image with a Warp whose pixels can't be read is written as its gray outline, which the reader
/// doesn't check: it leaves its check to the objects after it.
#[test]
fn a_warped_image_written_as_its_outline_takes_no_check() {
// GUARDS: an image written as its gray outline took a check, and the image after it lost its Warp.
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let limit = crate::import::ENVELOPE_CHECKS;
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
for _ in 0..limit - 1 {
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
}
let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0}));
let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None);
broken.appearance = Appearance { effects: vec![arc()], ..Appearance::default() }.into();
doc.insert(Some(layer), usize::MAX, broken).unwrap();
let photo = warped_photo(&mut doc, vec![arc()]);
doc.insert(Some(layer), usize::MAX, photo).unwrap();
let (p, warnings) = private_data(&doc, &opts()).unwrap();
assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}");
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
let (back, notes) = crate::ai_alone(&p.data).unwrap();
let a = back.layers[0].children().unwrap();
let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count();
assert_eq!(warped, 1, "{notes:?}");
}
/// Past the reader's checks, an image with a Warp whose pixels can't be read is still written as its
/// gray outline, with the warning for its pixels and not the one for the checks.
#[test]
fn an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels() {
// GUARDS: an image whose pixels can't be read was warned about as past the checks.
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let limit = crate::import::ENVELOPE_CHECKS;
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
for _ in 0..limit {
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
}
let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None);
broken.appearance = Appearance { effects: vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))], ..Appearance::default() }.into();
doc.insert(Some(layer), usize::MAX, broken).unwrap();
let (_, warnings) = private_data(&doc, &opts()).unwrap();
assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}");
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
}
/// Envelopes after images with a Warp get the checks the images left: past them, an envelope is
/// written as its art, with a warning.
#[test]
fn envelopes_get_the_checks_warped_images_left() {
// GUARDS: envelopes were written live past the checks the images with a Warp before them left.
let limit = crate::import::ENVELOPE_CHECKS;
let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, true);
assert_eq!((live, warped, all), (limit - 2, 2, limit + 1), "{warnings:?} {notes:?}");
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
}
/// Every Envelope Options switch and the ends of Fidelity come back as saved.
#[test]
fn envelope_options_and_fidelity_are_read_back() {
@@ -10695,4 +10834,25 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}");
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
}
// The outer clipping object ends at x = 100 and the clipping path's fill starts at x = 101: the
// fill is cut away and writes nothing, and its 4 pt stroke, which reaches x = 99, keeps the
// options, whether or not the fill's lock state is written before it.
for locked in [false, true] {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(101.0, 20.0, 150.0, 80.0)));
cutter.appearance = Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 4.0).into();
cutter.locked = locked;
let cutter = wrapped(cutter, 5.0, true);
let member = square(&mut doc, Rect::new(110.0, 30.0, 140.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
let inner = group(&mut doc, vec![cutter, member], true);
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
let frame = group(&mut doc, vec![frame], false);
let outer = group(&mut doc, vec![frame, inner], true);
doc.insert(Some(layer), usize::MAX, outer).unwrap();
let text = program(&doc);
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "locked {locked}: {text}");
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
}
}
+6 -5
View File
@@ -30,7 +30,7 @@ pub(super) use brushes::BRUSHES;
pub(super) use envelopes::ENVELOPES;
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects};
#[cfg(test)]
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance};
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
pub(super) use images::PAYLOAD;
#[cfg(test)]
@@ -281,9 +281,9 @@ pub(super) struct Writer<'a> {
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
/// ([`Self::envelope`]).
deform: bool,
/// How many more envelopes may be written live: as many as the reader checks in one file
/// ([`crate::import::ENVELOPE_CHECKS`]).
envelopes_left: usize,
/// 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>)>,
@@ -357,7 +357,7 @@ impl<'a> Writer<'a> {
brush_set: brushes::Brushes::default(),
brushes_live: true,
deform: false,
envelopes_left: crate::import::ENVELOPE_CHECKS,
checks_left: crate::import::ENVELOPE_CHECKS,
objects: 0,
left_out: 0,
definition_objects: 0,
@@ -662,6 +662,7 @@ impl<'a> Writer<'a> {
&& self.clip.is_none()
&& !self.in_symbol
&& let Some(orig) = self.styled.get(&n.id).cloned()
&& self.check_left(&orig)
&& let Some(name) = self.object_style(n, &orig)
{
return self.styled_object(n, &orig, &name);
@@ -26,7 +26,7 @@ use super::{MAX_NEST, Writer, Xy, hide};
use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number};
use crate::ps;
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the
/// reader's).
@@ -287,7 +287,7 @@ impl Writer<'_> {
/// another shape, or some of it is left out for the object limit ([`Self::take_objects`]).
pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool {
let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false };
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 {
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 {
return false;
}
let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false };
@@ -339,7 +339,7 @@ impl Writer<'_> {
return false;
}
self.deform = true;
self.envelopes_left -= 1;
self.checks_left -= 1;
true
}
+13 -4
View File
@@ -121,29 +121,37 @@ impl Samples {
}
impl Writer<'_> {
/// Whether [`Self::image`] can read `im`'s pixels, rather than write its gray outline.
pub(super) fn image_readable(&mut self, im: &ImageObject) -> bool {
let doc = self.doc;
doc.image_blob(im).and_then(|b| self.samples(b)).is_some()
}
/// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a
/// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on
/// `%_` lines (other than a styled object's copy on the layers, [`Self::styled_object`]) and in
/// a symbol's art. One whose pixels can't be read is its outline filled mid gray. Where the art is
/// cut to a clipping path, the image is in a clipping group of that path; a raster of pixels
/// written whole already is then the part of them that the path shows ([`ai_ops::image_window`]).
pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) {
/// True when the image is written as an image.
pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) -> bool {
let doc = self.doc;
let blob = doc.image_blob(im);
let read = blob.and_then(|b| self.samples(b));
let Some((samples, deep)) = read.as_deref() else {
let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1)));
self.warn(IMAGES);
return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy);
self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy);
return false;
};
// A region that has nothing left hides the image.
if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) {
return;
return false;
}
// The image, and where it is cut, the clipping group and its clipping path.
let clipping = self.clip.as_ref().map_or(0, |c| 1 + super::object_count(c.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()));
if !self.take_objects(1 + clipping) {
return;
return false;
}
if *deep {
self.warn(IMAGE_DEPTH);
@@ -217,6 +225,7 @@ impl Writer<'_> {
self.end_group("Q", Xy::PLAIN);
}
self.clip = cut;
true
}
/// An embedded image whose pixels `xf` places in the document: `%AI5_File:`,
+25 -2
View File
@@ -23,6 +23,7 @@ pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas,
pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps";
pub(in crate::ai_editing) const PANEL_EMPTY: &str =
"a Graphic Styles panel with no style written opens from the editing data with a new document's styles";
pub(in crate::ai_editing) const WARPED_IMAGES: &str = "images with a Warp after the first 256 envelopes and images with a Warp are written as their drawn look, without their Warp, in the editing data for other apps";
pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are left out of the editing data for other apps on type, images, symbol instances, knockout shapes and other objects that aren't written with their graphic style";
/// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style.
@@ -719,6 +720,24 @@ impl Writer<'_> {
items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c)))
}
/// Whether `orig` may be written with its art style as far as the reader's checks go: an image
/// with a Warp takes one of them, as an envelope does ([`Self::envelope`]); with none left, it is
/// written as its drawn look, with a warning. One whose pixels can't be read takes none: it is
/// written as its gray outline ([`Self::image`]).
pub(super) fn check_left(&mut self, orig: &Node) -> bool {
if !warped_image(orig) || self.checks_left > 0 {
return true;
}
let doc = self.doc;
if let NodeKind::Image(im) = &orig.kind
&& !self.image_readable(&doc.shown_image(orig, im))
{
return true;
}
self.warn(WARPED_IMAGES);
false
}
/// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and
/// hidden state; its drawn look (a group of its vector art as baking left it, without shadows,
/// glows or feathers, the object's transparency
@@ -729,7 +748,8 @@ impl Writer<'_> {
/// `1 (name) XW`.
/// The look's group and the object itself are counted first ([`Self::take_objects`]): without
/// room for them, nothing is written, and the object counts neither as written with its graphic
/// style nor as written with a brush on its stroke.
/// style nor as written with a brush on its stroke. An image written as an image takes one of
/// the reader's checks ([`Self::check_left`]).
pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) {
let own = match &orig.kind {
NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()),
@@ -787,9 +807,12 @@ impl Writer<'_> {
match &orig.kind {
NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy),
NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy),
// The reader checks the object only when it is an image, not its gray outline.
NodeKind::Image(im) => {
let was = std::mem::replace(&mut self.styled_copy, on_layers);
self.image(&self.doc.shown_image(orig, im), xy);
if self.image(&self.doc.shown_image(orig, im), xy) {
self.checks_left = self.checks_left.saturating_sub(1);
}
self.styled_copy = was;
}
NodeKind::Group { children, .. } => {
+1
View File
@@ -631,6 +631,7 @@ impl<'a> Reader<'a> {
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
spec.series_paints = paints;
spec.placed = Some(placed);
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c));
tag_series(art, &tags);
art.extras_mut().graph = Some(Box::new(spec));
true
+1 -1
View File
@@ -98,7 +98,7 @@ pub(crate) struct Interp<'a> {
/// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in
/// a font of its own (see `text`).
pub kshow_font: Option<DictRef>,
/// The `cshow` procedure running over type in a CIDFont only named, with the font it sees as
/// The `cshow` procedure running over a composite font's type, with the font it sees as
/// current (see `text`).
pub cshow: Option<super::text::CShowFont>,
pub g: GState,
+65
View File
@@ -136,6 +136,31 @@ fn codes_map_by_their_codespace_with_notdef_fallbacks() {
width("<01>", 30.0);
}
/// `cshow` over a CMap runs its procedure once for each code, whatever its length, with the
/// code's last byte and its width (PLRM 3rd ed., `cshow`).
#[test]
fn cshow_runs_once_for_each_cmap_code() {
let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP;
let check = |cond: &str| check(&format!("{fonts} /TestFont 50 selectfont {cond}"));
check("[ {pop pop} <418001> cshow ] dup length 2 eq exch aload pop 1 eq exch 65 eq and and");
check("0 {pop exch pop add} <418001> cshow 55 sub abs 0.01 lt");
check(
"{pop pop pop currentfont /CIDFontName get /seen exch def rootfont /FontName get /root exch def} <41> cshow seen /TestCID eq root /TestFont eq and",
);
// With the CIDFont current, the byte the procedure was given shows the glyph of its code's
// CID: <8001>'s last byte draws CID 2, not code 01's CID 1. Another string is an error.
let shown = "{pop pop ( ) dup 0 4 -1 roll put show} <418001> cshow";
check(&format!("gsave nulldevice 10 20 moveto {shown} currentpoint grestore pop 65 sub abs 0.01 lt"));
check("gsave nulldevice 10 20 moveto {{pop pop pop (B) show} <41> cshow} stopped grestore");
let r = import(&program(true, &format!("/TestFont 50 selectfont 10 20 moveto {shown}"))).unwrap();
let want = import(&program(true, "/TestFont 50 selectfont 10 20 moveto <418001> show")).unwrap();
let (p, q) = (paths(&r), paths(&want));
assert_eq!(p.len(), 2, "{p:?}");
for (a, b) in p.iter().zip(&q) {
assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01 && (a.height() - b.height()).abs() < 0.01, "{p:?} {q:?}");
}
}
/// `kshow` over a CMap runs its procedure between each two codes with their values, whatever
/// their length, and the next character follows where it moves the point (PLRM 3rd ed., `kshow`).
#[test]
@@ -188,6 +213,22 @@ fn type2_cidfonts_draw_their_truetype_glyphs_through_cidmap() {
}
}
/// A `cshow` procedure over a Type 2 CIDFont without a `FontMatrix` sees the CIDFont current at
/// the scale its glyphs are drawn at: an em of the composite font's size, as with the identity.
#[test]
fn cshow_over_a_type2_cidfont_without_a_matrix_sees_it_at_its_drawn_scale() {
let (h, i) = (glyph('H').0, glyph('I').0);
let with = cid2_font(&format!("<0000{h:04x}{i:04x}>"));
let without = with.replace("/FontMatrix [1 0 0 1 0 0] def", "");
assert_ne!(with, without);
for fonts in [with, without] {
check(&format!(
"{fonts}/T2 /Identity-H [/TestCID2] composefont 50 scalefont setfont \
{{pop pop pop currentfont /FontMatrix get 0 get /m exch def}} <0001> cshow m 50 sub abs 0.01 lt"
));
}
}
/// `Identity-V`: each glyph an em below the one before (writing mode 1).
#[test]
fn identity_v_sets_glyphs_downwards() {
@@ -385,6 +426,30 @@ fn cmaps_map_codes_to_base_fonts_codes_and_glyph_names() {
})
.collect();
assert_eq!(text, "ABC");
// A `cshow` procedure that shows the byte it was given, in the base font current while it
// runs, shows the character the code maps to, as `show` does.
let body = format!(
"{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 20 scalefont setfont 10 20 moveto \
{{pop pop ( ) dup 0 4 -1 roll put show}} <001000110012> cshow"
);
let r = super::tests::read(&body);
let text: String = all(&r.document)
.iter()
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => Some(t.plain_text()),
_ => None,
})
.collect();
assert_eq!(text, "ABC");
let body = format!(
"{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto \
{{pop pop ( ) dup 0 4 -1 roll put show}} <000100020003> cshow"
);
let q = paths(&super::tests::read(&body));
assert_eq!(q.len(), 3, "{q:?}");
for (a, b) in p.iter().zip(&q) {
assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01, "{p:?} {q:?}");
}
}
/// A CID-keyed font over a predefined Unicode CMap the file doesn't define, its CIDFont only
+39
View File
@@ -119,6 +119,45 @@ fn widthshow_matches_a_composite_character_by_font_number_and_code() {
check(format!("{} {} sub abs 0.01 lt", end(2), 10.0 + 100.0 * wh));
}
/// `cshow` runs its procedure once for each character of a composite font, not for each byte,
/// with the last byte of its code and its width, and with the descendant that draws it as the
/// current font while `rootfont` gives the composite font (PLRM 3rd ed., `cshow` and `rootfont`).
#[test]
fn cshow_runs_once_for_each_composite_character_in_its_descendant() {
let (_, wh) = glyph('H');
let (_, wi) = glyph('I');
let check = |cond: String| super::tests::check(&format!("{} /Comp findfont 50 scalefont setfont {cond}", fonts()));
check("[ {pop pop} (\\000\\001\\000\\002) cshow ] dup length 2 eq exch aload pop 2 eq exch 1 eq and and".into());
check(format!("0 {{pop exch pop add}} (\\000\\001\\000\\002) cshow {} sub abs 0.01 lt", 50.0 * (wh + wi)));
check("{pop pop pop currentfont /FontName get /seen exch def rootfont /FontName get /root exch def} (\\000\\001) cshow seen /T42 eq root /Comp eq and".into());
check("{pop pop pop} (\\000\\001) cshow currentfont /FontName get /Comp eq".into());
// A character the procedure shows in the descendant is as wide as the composite font sets it.
check(format!(
"gsave nulldevice 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} (\\000\\001\\000\\002) cshow currentpoint grestore pop {} sub abs 0.01 lt",
10.0 + 50.0 * (wh + wi)
));
// A character in font number 1 still gives only the last byte of its code, not 258.
let two = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def");
super::tests::check(&format!("{two} /Comp findfont 50 scalefont setfont [ {{pop pop}} (\\001\\002) cshow ] dup length 1 eq exch 0 get 2 eq and"));
}
/// A `cshow` procedure over a Type 42 descendant without a `FontMatrix` sees it current at the
/// scale its characters are drawn at: another character it measures there is as wide as the
/// composite font sets it, as with the identity.
#[test]
fn cshow_over_a_type42_descendant_without_a_matrix_sees_it_at_its_drawn_scale() {
let (_, wi) = glyph('I');
let with = fonts();
let without = with.replacen("/FontType 42 def /FontMatrix [1 0 0 1 0 0] def", "/FontType 42 def", 1);
assert_ne!(with, without);
for fonts in [with, without] {
super::tests::check(&format!(
"{fonts} /Comp findfont 50 scalefont setfont {{pop pop pop (\\002) stringwidth pop /w exch def}} (\\000\\001) cshow w {} sub abs 0.01 lt",
50.0 * wi
));
}
}
/// `kshow` runs its procedure between each two characters of a composite font, with the values of
/// their codes (font number times 256 plus code), and the next character follows where it moves
/// the current point (PLRM 3rd ed., `kshow`).
+79 -8
View File
@@ -251,6 +251,15 @@ impl Interp<'_> {
self.g.font = root;
return r;
}
// In a composite font the file carries, once for each character it maps.
if let Some(glyphs) = self.composite_glyphs(&s)? {
let root = self.g.font.clone();
let before = self.cshow.take();
let r = self.composite_cshow(&glyphs, &proc, root.clone());
self.cshow = before;
self.g.font = root;
return r;
}
for b in s {
let v = self.width_of(&[b])?;
self.push(Obj::Int(i64::from(b)))?;
@@ -992,6 +1001,7 @@ impl Spacing {
/// A character of a composite font: the descendant font that draws it, its code there (its last
/// byte for a CID), its CID and the notdef mapping's (`FMapType` 9), the composite font's matrix
/// (over the descendant's own) and whether it is set vertically (`WMode` 1).
#[derive(Clone)]
struct Mapped {
font: DictRef,
/// The byte that picked the descendant (the font number).
@@ -1006,6 +1016,13 @@ struct Mapped {
value: u32,
}
impl Mapped {
/// The last byte of the character's code in the shown string (what `cshow` gives its procedure).
fn last(&self) -> u8 {
(self.value & 0xff) as u8
}
}
/// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes
/// with their characters, the font it is set in, whether it runs down a column, and whether each
/// code moves the point one em (down a column, or in a CMap VectorCraft can't read).
@@ -1016,13 +1033,15 @@ struct NamedCid {
ems: bool,
}
/// A `cshow` procedure running over type in a CIDFont only named ([`Interp::named_cshow`]): the
/// CIDFont it sees as current, the composite font `rootfont` gives while that CIDFont is current,
/// and the type of the code it was given.
/// A `cshow` procedure running over a composite font's type ([`Interp::named_cshow`],
/// [`Interp::composite_cshow`]): the descendant it sees as current, the composite font `rootfont`
/// gives while that descendant is current, and the code it was given: over a CIDFont only named,
/// its type; over a composite font the file carries, the character it maps to.
pub(super) struct CShowFont {
selected: DictRef,
root: DictRef,
code: NamedCid,
code: Option<NamedCid>,
mapped: Option<Mapped>,
}
/// What drawing a glyph does with it.
@@ -1069,6 +1088,22 @@ impl Interp<'_> {
/// codes mapped to a descendant and a CID, §5.11.5); `None` for other fonts and mappings,
/// which are set as type in the font of the composite font's name.
fn composite_glyphs(&mut self, s: &[u8]) -> Res<Option<Vec<Mapped>>> {
// Inside a `cshow` procedure over a composite font the file carries, with the descendant
// it selected current, the one byte the procedure was given stands for the character its
// code maps to: a CMap's CID, base-font code or glyph name. In a CIDFont any other string
// is a `rangecheck` error (PLRM 3rd ed., `cshow`: the glyph of the selected CID); in a
// base font it is shown as it is.
if let Some(c) = self.cshow.as_ref()
&& let Some(mapped) = c.mapped.as_ref()
&& self.g.font.as_ref().is_some_and(|f| f.same(&c.selected))
{
if s == [mapped.last()] {
return Ok(Some(vec![mapped.clone()]));
}
if mapped.cid.is_some() {
return ps_err("rangecheck", "a string shown in cshow");
}
}
let Some(font) = self.g.font.clone() else { return Ok(None) };
let map = {
let f = font.borrow();
@@ -1220,17 +1255,18 @@ impl Interp<'_> {
/// that code when `code` and with none otherwise, while the CIDFont it selected is current.
fn cshow_code(&self, code: bool) -> Option<NamedCid> {
let c = self.cshow.as_ref()?;
let given = c.code.as_ref()?;
if !self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) {
return None;
}
let mut codes = Decoded::default();
if code {
let mut chars = c.code.codes.text.chars();
for &(value, n) in &c.code.codes.codes {
let mut chars = given.codes.text.chars();
for &(value, n) in &given.codes.codes {
codes.push(value, chars.by_ref().take(n));
}
}
Some(NamedCid { codes, font: c.code.font.clone(), vertical: c.code.vertical, ems: c.code.ems })
Some(NamedCid { codes, font: given.font.clone(), vertical: given.vertical, ems: given.ems })
}
/// The CMap's name, the composite font, the CIDFont's name and the writing mode of
@@ -1318,7 +1354,7 @@ impl Interp<'_> {
self.push(Obj::Int(i64::from(code & 0xff)))?;
self.push_num(v.x)?;
self.push_num(v.y)?;
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: one });
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: Some(one), mapped: None });
self.g.font = Some(selected.clone());
let go = self.body(proc);
self.g.font = root.clone();
@@ -1329,6 +1365,41 @@ impl Interp<'_> {
Ok(())
}
/// `cshow`'s procedure `proc` run for each character `glyphs` of composite font `root` maps,
/// with the last byte of its code and its width (PLRM 3rd ed., `cshow`). While it runs the
/// descendant that draws the character, at the size the composite font sets it, is the current
/// font and `rootfont` gives `root`. The current font is restored when the procedure completes.
fn composite_cshow(&mut self, glyphs: &[Mapped], proc: &Obj, root: Option<DictRef>) -> Res {
let Some(composite) = root.clone() else { return Ok(()) };
for g in glyphs {
let v = self.composite_glyph(g, Point::ZERO, Draw::No)?;
self.push(Obj::Int(i64::from(g.last())))?;
self.push_num(v.x)?;
self.push_num(v.y)?;
// Scaling the descendant copies its dictionary for every character: charged by its
// size, so a huge font dictionary in a loop runs out of the budget.
let entries = g.font.borrow().len();
self.spend(entries as u64)?;
// Without a matrix, a Type 42 font or a Type 2 CIDFont is in ems, as `composite_glyph`
// and `cid_glyph_at` draw it.
let selected = {
let f = g.font.borrow();
let default = if units(&f) == 1.0 { 1.0 } else { 0.001 };
let mut d = f.clone();
d.insert(Key::name("FontMatrix"), matrix_obj(g.outer * font_matrix(&f, default)));
DictRef::new(d)
};
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: None, mapped: Some(g.clone()) });
self.g.font = Some(selected);
let go = self.body(proc);
self.g.font = root.clone();
if !go? {
break;
}
}
Ok(())
}
/// How far codes `codes` of type `named` move the current point (user space) when
/// [`Self::show_named_cid`] shows them with no extra spacing.
fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res<Vec2> {
+21
View File
@@ -1634,6 +1634,27 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() {
let ds = d.to_string();
// The wrap object carries the options and the area type resolved its shape.
assert!(ds.contains("\"wrap\":{\"invert\":false,\"offset\":8.0}") && ds.contains("\"wrap\":[{\"invert\":false,\"offset\":8.0"), "{area}");
// An offset outside -1000 to 1000 pt, an invert or a release that is not true or false is an
// error, with release too, and the wrap and the selection stay as they were.
let r = call(&mut s, 20, "run_command", json!({"command": "select.set", "params": {"ids": [g]}}));
assert_eq!(r["isError"], false, "{r}");
for (id, args) in [
(21, json!({"ids": [c], "offset": 5000})),
(22, json!({"ids": [c], "offset": "8"})),
(23, json!({"ids": [c], "invert": "true"})),
(24, json!({"ids": [c], "release": "true"})),
(25, json!({"ids": [c], "release": true, "offset": -5000})),
] {
let r = call(&mut s, id, "text_wrap", args.clone());
assert_eq!(r["isError"], true, "{args}: {r}");
assert!(doc_json(&mut s).to_string().contains("\"wrap\":{\"invert\":false,\"offset\":8.0}"), "{args}");
}
// The graph is still the selection: a wrap made without ids goes on it, not on the circle.
let r = call(&mut s, 26, "text_wrap", json!({"offset": 9}));
assert_eq!(r["isError"], false, "{r}");
let made: Value = serde_json::from_str(&text_of(&r)).unwrap();
assert_eq!(made["ids"], json!([g]), "{r}");
call(&mut s, 27, "text_wrap", json!({"release": true}));
call(&mut s, 15, "text_wrap", json!({"ids": [c], "release": true}));
assert!(!doc_json(&mut s).to_string().contains("\"offset\":8.0"));
}
+1 -1
View File
@@ -507,7 +507,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"text_wrap",
"Text wrap",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap.",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.",
obj(
json!({
"ids": {"type": "array", "items": {"type": "integer"}},
+25 -7
View File
@@ -20,6 +20,29 @@ pub(super) const MAX_SIDE_WINDOW: &str =
/// The `traceViews` argument of the artboard renders.
pub(super) const TRACE_VIEWS: &str = "Draw Image Trace objects in the view set with imageTrace.setView (outlines, the source image…), as the app's window does; by default they draw their tracing result, as exports do";
/// The `text_wrap` tool's `release` and its `offset` and `invert` for `object.textWrap.make`, checked
/// before the tool changes the selection: an omitted or null value is left out, an `offset` that is
/// not a number or lies outside [`vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE`] is an error, and so is
/// an `invert` or `release` that is not true or false.
fn text_wrap_args(a: &Args) -> Result<(bool, Value), String> {
let mut p = json!({});
for k in ["offset", "invert", "release"] {
let Some(v) = a.get(k).filter(|v| !v.is_null()) else { continue };
if k == "offset" {
let range = vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE;
let n = v.as_f64().ok_or_else(|| format!("`{k}` must be a number, not {v}"))?;
if !range.contains(&n) {
return Err(format!("`{k}` must be from {} to {}", range.start(), range.end()));
}
} else if !v.is_boolean() {
return Err(format!("`{k}` must be true or false"));
}
p[k] = v.clone();
}
let release = p.as_object_mut().and_then(|m| m.remove("release")).is_some_and(|v| v == true);
Ok((release, p))
}
/// `traceViews`: false when absent.
pub(super) fn trace_views(a: &Args) -> Result<bool, String> {
match a.get("traceViews") {
@@ -261,16 +284,11 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<ToolResult, Str
j(exec(b, "graph.create", p)?)
}
"text_wrap" => {
let (release, p) = text_wrap_args(a)?;
select_ids(b, a)?;
if a.get("release").and_then(Value::as_bool) == Some(true) {
if release {
return j(exec(b, "object.textWrap.release", json!({}))?);
}
let mut p = json!({});
for k in ["offset", "invert"] {
if let Some(v) = a.get(k) {
p[k] = v.clone();
}
}
j(exec(b, "object.textWrap.make", p)?)
}
"undo" => j(exec(b, "edit.undo", json!({}))?),
+22 -11
View File
@@ -138,6 +138,7 @@ impl Exporter<'_> {
}
let doc = self.doc;
let out = self.out.clone();
let profiles = !out.standard.cmyk_only();
let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| {
let cmyk_image = blob.is_cmyk();
if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk {
@@ -147,12 +148,12 @@ impl Exporter<'_> {
let icc = out.cmyk_image_icc(blob);
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref())
} else {
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels())
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles)
};
if let Some(w) = r.warning {
self.warn(w);
}
r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit))
r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles))
});
if img.is_none() {
self.warn(UNDECODED);
@@ -316,9 +317,13 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option<Vec<u8>> {
}
/// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged),
/// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a
/// sample is written at 8 bits ([`png_8_bit`]).
pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option<Image> {
/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in
/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an
/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB
/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of
/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of
/// 16 bits a sample is written at 8 bits ([`png_8_bit`]).
pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> {
// The header's size first: the writer's decoders allocate what it declares, and the encoded
// bytes of an image that is far larger than any the app reads may be a few kilobytes.
let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions();
@@ -326,7 +331,17 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee
return None;
}
let bytes = blob.bytes.as_ref().clone();
// The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the
// profile is malformed, such a JPEG is written without its profile, and an image of another
// format is decoded and written without it. The color space is read from the header's bytes
// 16..20 even in a profile cut short, as the PDF writer reads it.
let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) {
Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)),
_ => false,
});
let direct = match blob.mime.as_str() {
"image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(),
_ if strip => None,
"image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()),
"image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(),
"image/jpeg" | "image/jpg" => Image::from_jpeg(bytes.clone().into(), interpolate).ok(),
@@ -334,11 +349,7 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee
"image/webp" => Image::from_webp(bytes.clone().into(), interpolate).ok(),
_ => None,
};
direct.or_else(|| {
let rgba = image::load_from_memory(&bytes).ok()?.to_rgba8();
let (w, h) = rgba.dimensions();
Some(Image::from_rgba8(rgba.into_raw(), w, h))
})
direct.or_else(|| crate::images::decoded_image(&bytes, interpolate, sixteen_bit, profiles))
}
#[cfg(test)]
@@ -357,7 +368,7 @@ mod tests {
let crc =
!png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }));
png[29..33].copy_from_slice(&crc.to_be_bytes());
assert!(super::embed(&ImageBlob::png(png), false, true).is_none());
assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none());
}
#[test]
+1 -1
View File
@@ -325,7 +325,7 @@ impl Exporter<'_> {
let img = match self.images.get(&cache) {
Some(img) => img.clone(),
None => {
let img = embed(&image.blob, self.interpolate, self.sixteen_bit);
let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only());
self.images.insert(cache, img.clone());
img
}
+110 -26
View File
@@ -29,8 +29,8 @@ use vectorcraft_doc::resample::{Resample, premultiply, resized, unpremultiply};
use crate::output::{CmykPixels, Pixels};
use crate::{CompressionSettings, Downsample, ImageCodec, JpegQuality, MonoCodec};
/// Raw 8-bit pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, with the
/// ICC profile the colour samples are in, if any.
/// Raw pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, of 8 bits a
/// sample or of 16 (big-endian), with the ICC profile the colour samples are in, if any.
#[derive(Clone, Hash)]
struct Raw {
color: Arc<Vec<u8>>,
@@ -38,6 +38,7 @@ struct Raw {
width: u32,
height: u32,
space: ImageColorspace,
bits: BitsPerComponent,
icc: Option<Arc<Vec<u8>>>,
}
@@ -51,7 +52,7 @@ impl CustomImage for Raw {
}
fn bits_per_component(&self) -> BitsPerComponent {
BitsPerComponent::Eight
self.bits
}
fn size(&self) -> (u32, u32) {
@@ -67,24 +68,86 @@ impl CustomImage for Raw {
}
}
/// `icc` when it is a well-formed profile ([`valid_icc`]) of the colour space `space` names: `GRAY`
/// for grey samples, `RGB ` for RGB ones. `None` for other profiles and spaces.
fn icc_for(icc: Option<Vec<u8>>, space: ImageColorspace) -> Option<Arc<Vec<u8>>> {
let want = match space {
ImageColorspace::Luma => *b"GRAY",
ImageColorspace::Rgb => *b"RGB ",
ImageColorspace::Cmyk | ImageColorspace::DeviceN => return None,
};
icc.filter(|icc| valid_icc(icc, want)).map(Arc::new)
}
/// The ICC profile image `bytes` carries: a TIFF's tag 34675 (read by the TIFF decoder itself,
/// which reads tags of any size), another format's as its decoder reads it. `None` without one.
pub(crate) fn source_icc(bytes: &[u8]) -> Option<Vec<u8>> {
let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
if reader.format() == Some(ImageFormat::Tiff) {
return vectorcraft_doc::cmyk::tiff_icc_profile(bytes);
}
let mut decoder = reader.into_decoder().ok()?;
decoder.icc_profile().ok().flatten().filter(|icc| !icc.is_empty())
}
/// A `width` × `height` image of straight (not premultiplied) RGBA pixels, written as RGB (as
/// CMYK when `pixels` converts to CMYK), or as grey when every pixel is grey, with an alpha
/// channel only when some pixel isn't opaque. `interpolate` asks viewers to smooth it when
/// enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels.
fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>) -> Option<Image> {
/// channel only when some pixel isn't opaque. With an RGB `icc` profile, pixels that `pixels`
/// doesn't convert stay RGB and carry it; a grey one tags grey pixels. `interpolate` asks viewers
/// to smooth it when enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels.
fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>, icc: Option<Vec<u8>>) -> Option<Image> {
let px = rgba.as_chunks::<4>().0;
if px.len() as u64 != width as u64 * height as u64 || px.is_empty() {
return None;
}
let (color, space) = if neutral(rgba) {
let rgb_icc = pixels.is_none() && icc.as_deref().is_some_and(|icc| valid_icc(icc, *b"RGB "));
let (color, space) = if neutral(rgba) && !rgb_icc {
(px.iter().map(|p| p[0]).collect(), ImageColorspace::Luma)
} else if let Some(cmyk) = pixels.and_then(|p| p.cmyk(rgba)) {
(cmyk, ImageColorspace::Cmyk)
} else {
(px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb)
};
let icc = icc_for(icc.filter(|_| pixels.is_none()), space);
let alpha = px.iter().any(|p| p[3] < 255).then(|| Arc::new(px.iter().map(|p| p[3]).collect()));
Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, icc: None }, interpolate).ok()
Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, bits: BitsPerComponent::Eight, icc }, interpolate).ok()
}
/// Decoded image `img` written losslessly as it is: grey or RGB samples (other kinds as RGB), with
/// an alpha channel only when some pixel isn't opaque, at 16 bits a sample when it has more than 8
/// and `sixteen_bit` allows it (PDF 1.5 and later), else at 8; tagged with ICC profile `icc` when
/// that is a profile of the samples' colour space (`GRAY` or `RGB `). `None` when it has no pixels.
pub(crate) fn from_decoded(img: DynamicImage, icc: Option<Vec<u8>>, interpolate: bool, sixteen_bit: bool) -> Option<Image> {
let (width, height) = (img.width(), img.height());
if width == 0 || height == 0 {
return None;
}
let kind = img.color();
let space = if kind.has_color() { ImageColorspace::Rgb } else { ImageColorspace::Luma };
let n = if kind.has_color() { 3 } else { 1 };
let deep = sixteen_bit && kind.bits_per_pixel() > 8 * u16::from(kind.channel_count());
let (color, alpha, bits) = if deep {
let s = if kind.has_color() { img.into_rgba16().into_raw() } else { img.into_luma_alpha16().into_raw() };
let px = s.chunks_exact(n + 1);
let color = px.clone().flat_map(|p| p[..n].iter().flat_map(|v| v.to_be_bytes())).collect();
let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u16::MAX)).then(|| px.flat_map(|p| p[n].to_be_bytes()).collect());
(color, alpha, BitsPerComponent::Sixteen)
} else {
let s = if kind.has_color() { img.into_rgba8().into_raw() } else { img.into_luma_alpha8().into_raw() };
let px = s.chunks_exact(n + 1);
let color = px.clone().flat_map(|p| p[..n].iter().copied()).collect();
let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u8::MAX)).then(|| px.map(|p| p[n]).collect());
(color, alpha, BitsPerComponent::Eight)
};
let raw = Raw { color: Arc::new(color), alpha: alpha.map(Arc::new), width, height, space, bits, icc: icc_for(icc, space) };
Image::from_custom(raw, interpolate).ok()
}
/// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when
/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as
/// [`from_decoded`] writes it. `None` when it can't be decoded.
pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> {
from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit)
}
/// Are all of the RGBA pixels `rgba` grey?
@@ -104,26 +167,28 @@ fn lossless(
icc: Option<&[u8]>,
) -> Option<Image> {
let icc = icc.map(|icc| Arc::new(icc.to_vec()));
Image::from_custom(Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, icc }, interpolate).ok()
let raw = Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, bits: BitsPerComponent::Eight, icc };
Image::from_custom(raw, interpolate).ok()
}
/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image
/// it holds is still written.
pub(crate) const MAX_EMBED_PIXELS: u64 = 1 << 27;
/// The most bytes a CMYK profile carried by an image is written with (16 MiB).
/// The most bytes an ICC profile carried by an image is written with (16 MiB).
const MAX_ICC: usize = 16 << 20;
/// The CMYK ICC profile image `blob` carries ([`ImageBlob::cmyk_icc_profile`]), when it is one a
/// CMYK image can be tagged with: at most [`MAX_ICC`] bytes, the size its header declares, the
/// `acsp` signature, an input, display, output or colour space profile of CMYK colours, and a tag
/// table whose tags lie within it. `None` for other images and other profiles.
/// CMYK image can be tagged with ([`valid_icc`]). `None` for other images and other profiles.
pub(crate) fn cmyk_icc(blob: &ImageBlob) -> Option<Vec<u8>> {
blob.cmyk_icc_profile().filter(|icc| valid_cmyk_icc(icc))
blob.cmyk_icc_profile().filter(|icc| valid_icc(icc, *b"CMYK"))
}
/// Is `icc` a CMYK profile as [`cmyk_icc`] describes?
fn valid_cmyk_icc(icc: &[u8]) -> bool {
/// Is `icc` a profile an image of colour space `space` (`GRAY`, `RGB ` or `CMYK`) can be tagged
/// with: at most [`MAX_ICC`] bytes, the size its header declares, the `acsp` signature, an input,
/// display, output or colour space profile of `space` colours, and a tag table whose tags lie
/// within it?
pub(crate) fn valid_icc(icc: &[u8], space: [u8; 4]) -> bool {
let be = |at: usize| icc.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes);
let fits = |at: u32, len: u32| u64::from(at) + u64::from(len) <= icc.len() as u64;
if icc.len() > MAX_ICC || be(0).and_then(|n| usize::try_from(n).ok()) != Some(icc.len()) {
@@ -131,7 +196,7 @@ fn valid_cmyk_icc(icc: &[u8]) -> bool {
}
let class = icc.get(12..16);
if icc.get(36..40) != Some(b"acsp".as_slice())
|| icc.get(16..20) != Some(b"CMYK".as_slice())
|| icc.get(16..20) != Some(space.as_slice())
|| ![b"scnr", b"mntr", b"prtr", b"spac"].iter().any(|c| class == Some(c.as_slice()))
{
return false;
@@ -151,7 +216,7 @@ pub(crate) fn from_rgba_in(mut rgba: Vec<u8>, width: u32, height: u32, interpola
if let Some(p) = pixels {
p.rgb_in_place(&mut rgba);
}
from_rgba(&rgba, width, height, interpolate, pixels)
from_rgba(&rgba, width, height, interpolate, pixels, None)
}
/// A `width` × `height` image of CMYK ink amounts `inks` (four bytes a pixel), converted by
@@ -306,9 +371,17 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic
/// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask:
/// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours
/// converted by `convert` (colour images). `interpolate` lets viewers smooth it. An image that
/// can't be decoded is kept as it is.
pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>) -> Recoded {
/// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile
/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces).
/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is.
pub(crate) fn recode(
bytes: &[u8],
size: (f64, f64),
c: &CompressionSettings,
interpolate: bool,
convert: Option<&Pixels>,
profiles: bool,
) -> Recoded {
let keep = Recoded { image: None, warning: None };
let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep };
let jpeg = reader.format() == Some(ImageFormat::Jpeg);
@@ -337,6 +410,11 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in
return Recoded { image: None, warning: rule.instead };
}
let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep };
// Pixels that keep their colours keep the profile they are in; converted ones are in the
// destination's.
let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" };
let icc = (profiles && convert.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want));
let rgb_icc = icc.is_some() && kind == Kind::Color;
let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8();
if kind == Kind::Mono {
// Resampling greys the edges: back to black and white.
@@ -351,16 +429,18 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in
let (width, height) = rgba.dimensions();
let opaque = rgba.pixels().all(|p| p[3] == 255);
let jpeg = jpeg_quality(&rule, jpeg).filter(|_| opaque).and_then(|q| {
// Grey pixels stay grey; colour ones go to CMYK when the output converts to CMYK.
let grey = kind != Kind::Color || neutral(&rgba);
// Grey pixels stay grey, unless they keep an RGB profile; colour ones go to CMYK when the
// output converts to CMYK.
let grey = kind != Kind::Color || (neutral(&rgba) && !rgb_icc);
let (samples, space) = match convert.filter(|_| !grey).and_then(|p| p.cmyk(&rgba)) {
Some(cmyk) => (cmyk, ImageColorspace::Cmyk),
None if grey => (rgba.pixels().map(|p| p[0]).collect(), ImageColorspace::Luma),
None => (rgba.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb),
};
to_jpeg(&samples, space, width, height, q, interpolate, None)
let icc = icc_for(icc.clone(), space);
to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice))
});
let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert));
let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc));
Recoded { image, warning: rule.instead }
}
@@ -514,7 +594,11 @@ fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, qual
}
ImageColorspace::Rgb | ImageColorspace::Luma => {
let t = if space == ImageColorspace::Rgb { ExtendedColorType::Rgb8 } else { ExtendedColorType::L8 };
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality).encode(samples, width, height, t).ok()?;
let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality);
if let Some(icc) = icc {
image::ImageEncoder::set_icc_profile(&mut encoder, icc.to_vec()).ok()?;
}
encoder.encode(samples, width, height, t).ok()?;
}
ImageColorspace::DeviceN => return None,
}
+288 -2
View File
@@ -5,7 +5,7 @@
use std::io::Cursor;
use craft_pdf::syntax::object::{Name, Object};
use craft_pdf::syntax::object::{Array, Name, Object, Stream};
use image::{DynamicImage, ImageFormat};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
@@ -266,6 +266,292 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() {
assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None);
assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all");
let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap();
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None);
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true);
assert!(r.image.is_none(), "kept as it is");
}
/// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in
/// all, with an empty tag table, every byte after the tag count different from its neighbors.
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]);
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc[128..132].copy_from_slice(&0u32.to_be_bytes());
icc
}
/// `img` encoded as `format` carrying ICC profile `icc`.
fn tagged(img: &DynamicImage, icc: &[u8], format: ImageFormat) -> Vec<u8> {
use image::ImageEncoder as _;
let mut out = Vec::new();
match format {
ImageFormat::Tiff => {
let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out));
enc.set_icc_profile(icc.to_vec()).unwrap();
img.write_with_encoder(enc).unwrap();
}
ImageFormat::Jpeg => {
let mut enc = image::codecs::jpeg::JpegEncoder::new(&mut out);
enc.set_icc_profile(icc.to_vec()).unwrap();
img.write_with_encoder(enc).unwrap();
}
_ => {
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
enc.set_icc_profile(icc.to_vec()).unwrap();
img.write_with_encoder(enc).unwrap();
}
}
out
}
/// An image XObject as it is written.
#[derive(Debug, PartialEq)]
struct Written {
/// Its colour space's name: `ICCBased` for an ICC-based one.
space: String,
/// The profile an ICC-based colour space holds.
icc: Option<Vec<u8>>,
bits: u8,
filter: String,
smask: bool,
}
/// Each image XObject of `pdf` other than soft masks.
fn image_spaces(pdf: &[u8]) -> Vec<Written> {
let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap();
let images: Vec<Stream<'_>> = file
.objects()
.into_iter()
.filter_map(|o| match o {
Object::Stream(s) if s.dict().get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s),
_ => None,
})
.collect();
let masks: Vec<Vec<u8>> = images.iter().filter_map(|s| s.dict().get::<Stream<'_>>(b"SMask")).map(|m| m.raw_data().to_vec()).collect();
let mut out = vec![];
for s in images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())) {
let d = s.dict();
let (space, icc) = match (d.get::<Name<'_>>(b"ColorSpace"), d.get::<Array<'_>>(b"ColorSpace")) {
(Some(n), _) => (n.as_str().to_string(), None),
(_, Some(a)) => {
let mut it = a.flex_iter();
let name = it.next::<Name<'_>>().unwrap().as_str().to_string();
(name, it.next::<Stream<'_>>().map(|s| s.decoded().unwrap().into_owned()))
}
_ => (String::new(), None),
};
let filter = d.get::<Name<'_>>(b"Filter").map(|n| n.as_str().to_string()).unwrap_or_default();
let (bits, smask) = (d.get::<u8>(b"BitsPerComponent").unwrap_or(0), d.get::<Stream<'_>>(b"SMask").is_some());
out.push(Written { space, icc, bits, filter, smask });
}
out
}
/// The decoded samples of each image XObject of `pdf` other than soft masks.
fn image_samples(pdf: &[u8]) -> Vec<Vec<u8>> {
let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap();
let images: Vec<Stream<'_>> = file
.objects()
.into_iter()
.filter_map(|o| match o {
Object::Stream(s) if s.dict().get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s),
_ => None,
})
.collect();
let masks: Vec<Vec<u8>> = images.iter().filter_map(|s| s.dict().get::<Stream<'_>>(b"SMask")).map(|m| m.raw_data().to_vec()).collect();
images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())).map(|s| s.decoded().unwrap().into_owned()).collect()
}
/// The raw (still encoded) data of each image XObject of `pdf`.
fn image_data(pdf: &[u8]) -> Vec<Vec<u8>> {
let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap();
file.objects()
.into_iter()
.filter_map(|o| match o {
Object::Stream(s) if s.dict().get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s.raw_data().to_vec()),
_ => None,
})
.collect()
}
/// A PNG or JPEG embedded as it is whose gray or RGB profile is malformed is written without it,
/// the JPEG with its JPEG data unchanged: a profile whose header declares another size, one without
/// the `acsp` signature, one whose tag table runs past its end, and one cut short after 64 bytes.
#[test]
fn a_malformed_profile_is_left_out_of_a_png_or_jpeg_kept_as_it_is() {
for (space, img, device) in [(b"RGB ", colour(), "DeviceRGB"), (b"GRAY", colour().grayscale(), "DeviceGray")] {
let mut malformed = [icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600)];
malformed[0][..4].copy_from_slice(&601u32.to_be_bytes());
malformed[1][36..40].copy_from_slice(b"xxxx");
malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes());
malformed[3].truncate(64);
malformed[3][..4].copy_from_slice(&64u32.to_be_bytes());
for (i, icc) in malformed.iter().enumerate() {
for (format, mime, filter) in [(ImageFormat::Png, "image/png", "FlateDecode"), (ImageFormat::Jpeg, "image/jpeg", "DCTDecode")] {
let what = format!("{device}, {format:?}, malformed profile {i}");
let bytes = tagged(&img, icc, format);
let mut settings = PdfSettings::default();
settings.compression.compress_text = false;
let pdf = export_with_report(&doc(bytes.clone(), mime), &PdfOptions { settings, ..Default::default() }).unwrap().bytes;
let spaces = image_spaces(&pdf);
let plain = spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none() && spaces[0].filter == filter;
assert!(plain, "{what}: {spaces:?}");
if format == ImageFormat::Jpeg {
assert!(image_data(&pdf) == [bytes], "{what}: the JPEG data unchanged");
}
}
}
}
}
/// In PDF/X-1a a tagged gray JPEG kept as JPEG is written with its JPEG data, without its profile.
#[test]
fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() {
let jpeg = tagged(&colour().grayscale(), &icc_profile(b"GRAY", 300), ImageFormat::Jpeg);
let d = doc(jpeg.clone(), "image/jpeg");
for compression in [json!({}), json!({"gray": {"compression": "jpeg"}})] {
let mut settings: PdfSettings =
serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap();
settings.compression.compress_text = false;
let bytes = export_with_report(&d, &PdfOptions { settings, ..Default::default() }).unwrap().bytes;
crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{compression}: {e}"));
let spaces = image_spaces(&bytes);
let dct = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none() && spaces[0].filter == "DCTDecode";
assert!(dct, "{compression}: {spaces:?}");
assert!(image_data(&bytes) == [jpeg.clone()], "{compression}: the JPEG data unchanged");
}
}
/// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based
/// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as
/// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels
/// the Output settings convert, and a profile of another colour space, are written without it.
#[test]
fn tagged_tiffs_keep_their_icc_profile() {
let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300));
let mut clear = colour().to_rgba8();
clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0]));
let tiff = |img: &DynamicImage, icc: &[u8]| doc(tagged(img, icc, ImageFormat::Tiff), "image/tiff");
let export = |d: &Document, settings: Value| {
let mut settings: PdfSettings = serde_json::from_value(settings).unwrap();
settings.compression.compress_text = false;
let r = export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
image_spaces(&r.bytes)
};
let icc_based = |icc: &[u8], bits: u8, filter: &str, smask: bool| {
vec![Written { space: "ICCBased".into(), icc: Some(icc.to_vec()), bits, filter: filter.into(), smask }]
};
let flate = "FlateDecode";
let cases = [
("RGB", tiff(&colour(), &rgb), json!({}), icc_based(&rgb, 8, flate, false)),
("gray", tiff(&colour().grayscale(), &gray), json!({}), icc_based(&gray, 8, flate, false)),
(
"RGB, 16 bits",
tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb),
json!({"compatibility": "1.7"}),
icc_based(&rgb, 16, flate, false),
),
(
"RGB, 16 bits, PDF 1.4",
tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb),
json!({"compatibility": "1.4"}),
icc_based(&rgb, 8, flate, false),
),
("RGBA", tiff(&clear.clone().into(), &rgb), json!({}), icc_based(&rgb, 8, flate, true)),
(
"RGB, resampled",
tiff(&colour(), &rgb),
json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}),
icc_based(&rgb, 8, flate, false),
),
(
"gray, resampled",
tiff(&colour().grayscale(), &gray),
json!({"compression": {"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}),
icc_based(&gray, 8, flate, false),
),
("RGB, JPEG", tiff(&colour(), &rgb), json!({"compression": {"color": {"compression": "jpeg"}}}), icc_based(&rgb, 8, "DCTDecode", false)),
(
"gray, JPEG",
tiff(&colour().grayscale(), &gray),
json!({"compression": {"gray": {"compression": "jpeg"}}}),
icc_based(&gray, 8, "DCTDecode", false),
),
(
"PNG, resampled",
doc(tagged(&colour(), &rgb, ImageFormat::Png), "image/png"),
json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}),
icc_based(&rgb, 8, flate, false),
),
];
for (what, d, settings, want) in cases {
assert_eq!(export(&d, settings), want, "{what}");
}
// 16-bit samples are written big-endian from PDF 1.5 on, and reduced to 8 bits before it.
// Their high and low bytes differ, so a swapped or truncated stream does not match.
let deep = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(600, 600, |x, y| {
image::Rgb([((x * 109 + y) % 65_521) as u16, ((y * 257 + 3) ^ 0x5a) as u16, ((x * y) % 65_521) as u16])
}));
let sixteen: Vec<u8> = deep.to_rgb16().iter().flat_map(|v| v.to_be_bytes()).collect();
for (compatibility, want) in [("1.7", sixteen), ("1.4", deep.to_rgb8().into_raw())] {
let mut settings: PdfSettings = serde_json::from_value(json!({ "compatibility": compatibility })).unwrap();
settings.compression.compress_text = false;
let r = export_with_report(&tiff(&deep, &rgb), &PdfOptions { settings, ..Default::default() }).unwrap();
assert!(image_samples(&r.bytes) == [want], "16-bit samples, PDF {compatibility}");
}
// A gray image in an RGB profile stays RGB to keep it, resampled too.
let neutral = tiff(&DynamicImage::ImageRgb8(colour().grayscale().to_rgb8()), &rgb);
for settings in [json!({}), json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}})] {
assert_eq!(export(&neutral, settings.clone()), icc_based(&rgb, 8, flate, false), "neutral RGB, {settings}");
}
// A profile of another colour space is left out.
let spaces = export(&tiff(&colour(), &gray), json!({}));
assert!(spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(), "RGB in a gray profile: {spaces:?}");
// A malformed profile is left out, the image kept as it is, resampled or compressed with JPEG:
// one whose header declares another size, one without the `acsp` signature, and one whose tag
// table runs past its end.
let mut malformed = [rgb.clone(), rgb.clone(), rgb.clone()];
malformed[0][..4].copy_from_slice(&601u32.to_be_bytes());
malformed[1][36..40].copy_from_slice(b"xxxx");
malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes());
let compressions =
[json!({}), json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"color": {"compression": "jpeg"}})];
for (i, icc) in malformed.iter().enumerate() {
for compression in &compressions {
let spaces = export(&tiff(&colour(), icc), json!({ "compression": compression }));
assert!(
spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(),
"malformed profile {i}, {compression}: {spaces:?}"
);
}
}
// Converted pixels are in the destination's colours, not the image's profile.
for destination in [vectorcraft_color::cms::DISPLAY_P3, vectorcraft_color::cms::GENERIC_CMYK] {
let spaces = export(&tiff(&colour(), &rgb), json!({"output": {"conversion": "destination", "destination": destination}}));
assert!(spaces.len() == 1 && spaces[0].icc.as_deref() != Some(rgb.as_slice()), "converted to {destination}: {spaces:?}");
}
// PDF/X-1a allows no ICC-based color spaces: a tagged gray TIFF (8 or 16 bits), PNG or JPEG is
// written in DeviceGray, kept as it is, resampled or compressed with JPEG, and the file passes
// the PDF/X-1a check.
let compressions = [json!({}), json!({"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"gray": {"compression": "jpeg"}})];
let tiff16 = tiff(&DynamicImage::ImageLuma16(colour().to_luma16()), &gray);
let png = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png");
let jpeg = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg");
for (format, d) in [("TIFF", tiff(&colour().grayscale(), &gray)), ("TIFF, 16 bits", tiff16), ("PNG", png), ("JPEG", jpeg)] {
for compression in &compressions {
let mut settings: PdfSettings =
serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap();
settings.compression.compress_text = false;
let r = export_with_report(&d, &PdfOptions { settings, ..Default::default() });
let bytes = r.unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}")).bytes;
crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}"));
let spaces = image_spaces(&bytes);
let gray = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none();
assert!(gray, "PDF/X-1a, {format}, {compression}: {spaces:?}");
}
}
}
+2 -6
View File
@@ -28,16 +28,12 @@ const ADAM7: [(u32, u32, u32, u32); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4,
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
pub fn pixels_per_metre(ppi: f64) -> u32 {
(ppi / 0.0254).round().clamp(1.0, u32::MAX as f64) as u32
vectorcraft_doc::ppi::pixels_per_metre(ppi)
}
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
let mut out = Vec::with_capacity(21);
// x, y, unit 1 = metre.
chunk(&mut out, b"pHYs", &[x.as_slice(), y.as_slice(), &[1]].concat());
out
vectorcraft_doc::ppi::phys_chunk(x, y)
}
/// Encode straight-alpha RGBA8 pixels (`width`×`height`, row-major) as a PNG file.
+15
View File
@@ -43,6 +43,7 @@ pub(super) use prepass::Edits;
use prepass::{Extras, labels, prepass};
pub use prepass::{MAX_FOREIGN, MAX_FOREIGN_VALUE};
mod budget;
mod css;
mod css_transform;
mod depth;
@@ -136,10 +137,14 @@ pub(crate) fn import_finding(
return Err(too_deep());
}
let xml = parse(svg)?;
// Before the style cascade of `depth::height` and the prepass, which keeps the declarations of
// each element it reads; measured again below on the text usvg reads when that differs.
let styles = budget::check(&xml, budget::MAX_COPIED_STYLES, depth::MAX_ELEMENT_DEPTH)?;
let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else {
return Err(too_deep());
};
let (svg, found) = prepass(svg, &scan.markers, &xml, opts)?;
let rewritten = matches!(svg, Cow::Owned(_));
// The prepass's edits are in the text: the XML is read again only when it made any.
let xml = match &svg {
Cow::Borrowed(_) => xml,
@@ -154,7 +159,14 @@ pub(crate) fn import_finding(
let mut warnings = found.warnings;
let text_xml = found.text_source.as_deref().map(parse).transpose()?;
let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings);
// Before usvg copies what `<use>`s show and the style values of each copy: the text usvg reads.
let styles = match &src {
Cow::Borrowed(_) if !rewritten => styles,
Cow::Borrowed(_) => budget::check(&xml, budget::MAX_COPIED_STYLES, usize::MAX)?,
Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::MAX_COPIED_STYLES, usize::MAX)?,
};
let files = found.files;
files.copied_styles(styles);
let tree = {
let opt = usvg::Options {
dpi: units.dpi as f32,
@@ -164,6 +176,9 @@ pub(crate) fn import_finding(
};
usvg::Tree::from_str(&src, &opt).map_err(|e| SvgError::Parse(e.to_string()))?
};
if let Some(err) = files.refused() {
return Err(err);
}
let size = tree.size();
let k = units.k;
let mut doc = Document::new(size.width() as f64 * k, size.height() as f64 * k);
+502
View File
@@ -0,0 +1,502 @@
//! What usvg makes of an SVG, measured in the XML before usvg runs: how many elements it makes,
//! and how many bytes of style values it copies into them.
//!
//! usvg makes an element of each SVG element, and of each element a `<use>` shows a copy of, by
//! copying what the `<use>` refers to. Each copy gets its own copy of every declaration the style
//! sheets and the `style` attribute give the element, so a long style on an element that `<use>`s
//! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more
//! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after
//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or
//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead.
//!
//! The copies are counted, never made: each element's count is worked out once and added up, so a
//! `<use>` of an element costs one addition, however many elements its copy holds. References
//! follow usvg 0.48.1 (`parser/svgtree/parse.rs`): an id names the first element that has it, an
//! unprefixed `href` wins over `xlink:href`, and a `<use>` of itself, of the `<use>` its own copy
//! starts from, or of an element holding a `<use>` of the element or of the `<use>`, is left out.
//! Any other loop of references makes usvg copy without end, so an SVG with one is refused. usvg
//! looks for those `<use>`s inside an element only in the SVG namespace: in an SVG without one, a
//! `<use>` that leads back to the `<use>` its copy starts from is refused here too, though usvg
//! would leave it out.
//!
//! The style sheets' rules are matched against each element once, as usvg matches them against
//! each copy.
use std::collections::{HashMap, HashSet};
use usvg::roxmltree;
use super::{MAX_NODES, SVG_NS, XNode};
use crate::{MAX_ELEMENT_DEPTH, SvgError};
/// Most elements usvg may make of an SVG: [`MAX_NODES`], and below the 1,000,000 elements past
/// which usvg stops (its count includes a root of its own).
pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 };
/// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it
/// shows, all together: VectorCraft's own limit.
pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20;
/// What usvg keeps for each value it copies besides its bytes (the count and length of a shared
/// string).
const COPY: u64 = 16;
/// The longhands a `font` shorthand resets before setting the ones it gives, and the most bytes of
/// each reset value (`normal`).
const FONT_RESETS: u64 = 12;
const RESET_VALUE: u64 = 6;
/// The longhands a `font` shorthand sets from its own text.
const FONT_PARTS: u64 = 6;
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
/// The elements usvg reads (`EId` in usvg's `parser/svgtree/names.rs`); it skips the others with
/// everything inside them.
const ELEMENTS: [&str; 53] = [
"a",
"circle",
"clipPath",
"defs",
"ellipse",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"filter",
"g",
"image",
"line",
"linearGradient",
"marker",
"mask",
"path",
"pattern",
"polygon",
"polyline",
"radialGradient",
"rect",
"stop",
"style",
"svg",
"switch",
"symbol",
"text",
"textPath",
"tref",
"tspan",
"use",
];
/// The name of element `n` when usvg reads it: in the SVG namespace or none, and one of
/// [`ELEMENTS`].
fn svg_name<'a>(n: XNode<'a, '_>) -> Option<&'a str> {
let name = n.tag_name();
(n.is_element() && matches!(name.namespace(), None | Some(SVG_NS)) && ELEMENTS.contains(&name.name())).then(|| name.name())
}
/// An element as the style sheets' selectors see it, as usvg matches them.
struct Element<'a, 'i>(XNode<'a, 'i>);
impl simplecss::Element for Element<'_, '_> {
fn parent_element(&self) -> Option<Self> {
self.0.parent_element().map(Self)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.0.prev_sibling_element().map(Self)
}
fn has_local_name(&self, name: &str) -> bool {
self.0.tag_name().name() == name
}
fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator<'_>) -> bool {
self.0.attribute(name).is_some_and(|value| operator.matches(value))
}
fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool {
matches!(class, simplecss::PseudoClass::FirstChild) && self.0.prev_sibling_element().is_none()
}
}
/// The bytes usvg copies for one declaration: three markers for `marker`, the resets and longhands
/// for `font`, its value for any other. Counted for every declaration, the ones usvg then drops (a
/// property it doesn't read, a value an earlier one overrides) too.
fn copied(declaration: &simplecss::Declaration) -> u64 {
let len = declaration.value.len() as u64;
match declaration.name {
"marker" => 3 * (COPY + len),
"font" => (FONT_RESETS + FONT_PARTS) * COPY + FONT_RESETS * RESET_VALUE + len,
_ => COPY + len,
}
}
/// What usvg makes of one element: elements (text nodes included) and bytes of copied styles.
#[derive(Clone, Copy, Default)]
struct Cost {
elements: u64,
bytes: u64,
}
impl Cost {
fn add(self, other: Cost) -> Cost {
Cost { elements: self.elements.saturating_add(other.elements), bytes: self.bytes.saturating_add(other.bytes) }
}
}
/// What a `<use>` shows: nothing, the element it refers to with all it holds, or only that
/// element (a `<use>` whose own reference leads back to the `<use>` showing it).
enum Shows<'a, 'i> {
Nothing,
All(XNode<'a, 'i>),
Bare(XNode<'a, 'i>),
}
struct Measure<'a, 'i> {
/// The first element of each id.
ids: HashMap<&'a str, XNode<'a, 'i>>,
sheet: simplecss::StyleSheet<'a>,
/// The elements that hold a `<use>` of themselves.
holds_use_of_itself: HashSet<roxmltree::NodeId>,
/// The `<use>`s of each element, by the element.
used_by: HashMap<roxmltree::NodeId, Vec<XNode<'a, 'i>>>,
/// The bytes of text in each element a `<tref>` shows.
tref_text: HashMap<roxmltree::NodeId, u64>,
}
impl<'a, 'i> Measure<'a, 'i> {
fn new(xml: &'a roxmltree::Document<'i>) -> Self {
let mut ids = HashMap::new();
for n in xml.descendants() {
if let Some(id) = n.attribute("id") {
ids.entry(id).or_insert(n);
}
}
// The style sheets usvg reads: `<style>` elements of no type or of `text/css`, the first
// text of each.
let mut sheet = simplecss::StyleSheet::new();
for n in xml.descendants().filter(|n| n.has_tag_name("style")) {
if n.attribute("type").is_none_or(|t| t == "text/css")
&& let Some(text) = n.text()
{
sheet.parse_more(text);
}
}
let mut m = Measure { ids, sheet, holds_use_of_itself: HashSet::new(), used_by: HashMap::new(), tref_text: HashMap::new() };
for u in xml.descendants().filter(|n| n.has_tag_name((SVG_NS, "use"))) {
let Some(target) = m.target(u) else { continue };
if u.ancestors().skip(1).any(|a| a == target) {
m.holds_use_of_itself.insert(target.id());
}
m.used_by.entry(target.id()).or_default().push(u);
}
m
}
/// The element `<use>` `u` refers to, as usvg resolves it.
fn target(&self, u: XNode<'a, 'i>) -> Option<XNode<'a, 'i>> {
let link = u
.attributes()
.find(|a| a.name() == "href" && a.namespace().is_none())
.or_else(|| u.attributes().find(|a| a.name() == "href" && a.namespace() == Some(XLINK_NS)))?;
let id = svgtypes::IRI::from_str(link.value()).ok()?.0;
self.ids.get(id).copied()
}
/// What `<use>` `u` shows: see the module docs.
fn shows(&self, u: XNode<'a, 'i>) -> Shows<'a, 'i> {
let Some(link) = self.target(u) else { return Shows::Nothing };
if link == u || svg_name(link).is_none() {
return Shows::Nothing;
}
let inside = |v: &XNode| v.ancestors().skip(1).any(|a| a == link);
if self.holds_use_of_itself.contains(&link.id()) || self.used_by.get(&u.id()).is_some_and(|uses| uses.iter().any(inside)) {
return Shows::Nothing;
}
if svg_name(link) == Some("use") && self.target(link) == Some(u) {
return Shows::Bare(link);
}
Shows::All(link)
}
/// The bytes of style values usvg copies into one copy of element `n`.
fn styles(&self, n: XNode) -> u64 {
let mut bytes = 0u64;
for rule in self.sheet.rules.iter().filter(|r| r.selector.matches(&Element(n))) {
bytes = rule.declarations.iter().map(copied).fold(bytes, u64::saturating_add);
}
if let Some(style) = n.attribute("style") {
bytes = simplecss::DeclarationTokenizer::from(style).map(|d| copied(&d)).fold(bytes, u64::saturating_add);
}
bytes
}
/// Element `n` alone.
fn own(&self, n: XNode) -> Cost {
Cost { elements: 1, bytes: self.styles(n) }
}
/// `<text>` `t` and what usvg makes of what it holds: at most an element of each element, and
/// a copy of each run of text and of the text each `<tref>` shows.
fn text(&mut self, t: XNode<'a, 'i>) -> Cost {
let mut cost = self.own(t);
for d in t.descendants().skip(1) {
if d.is_text() {
let len = d.text().map_or(0, str::len) as u64;
cost = cost.add(Cost { elements: 1, bytes: COPY + len });
} else if svg_name(d).is_some() {
cost = cost.add(self.own(d));
if svg_name(d) == Some("tref") {
cost = cost.add(Cost { elements: 1, bytes: COPY + self.tref(d) });
}
}
}
cost
}
/// The bytes of text `<tref>` `r` shows.
fn tref(&mut self, r: XNode<'a, 'i>) -> u64 {
let link = r.attribute((XLINK_NS, "href")).or_else(|| r.attribute("href"));
let Some(target) = link.and_then(|l| svgtypes::IRI::from_str(l).ok()).and_then(|iri| self.ids.get(iri.0).copied()) else { return 0 };
*self.tref_text.entry(target.id()).or_insert_with(|| {
target.descendants().filter(|n| n.is_text()).filter_map(|n| n.text()).map(|t| t.len() as u64).fold(0, u64::saturating_add)
})
}
}
/// The bytes of style values usvg would copy into the elements of `xml`, when that is no more
/// than `bytes_left` and it makes no more than [`MAX_SVG_ELEMENTS`] elements of it, nested no
/// deeper than `depth` (counted as `depth::height` counts, which finds at least as much).
pub(super) fn check(xml: &roxmltree::Document, bytes_left: u64, depth: usize) -> Result<u64, SvgError> {
match measure(xml, MAX_SVG_ELEMENTS as u64, bytes_left, depth) {
Ok(cost) => Ok(cost.bytes),
Err(Past::Elements) => Err(SvgError::TooLarge(MAX_SVG_ELEMENTS)),
Err(Past::Bytes) => Err(SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize)),
Err(Past::Depth) => Err(SvgError::TooDeep(MAX_ELEMENT_DEPTH)),
}
}
/// The limit [`measure`] stopped at.
#[derive(Debug, PartialEq)]
enum Past {
Elements,
Bytes,
Depth,
}
/// What usvg makes of `xml`, up to `elements` elements and `bytes` bytes of copied styles, its
/// elements and the copies `<use>`s show nested up to `depth` deep. Without recursion; each
/// element is measured once.
fn measure(xml: &roxmltree::Document, elements: u64, bytes: u64, depth: usize) -> Result<Cost, Past> {
let mut m = Measure::new(xml);
let mut costs: HashMap<roxmltree::NodeId, Cost> = HashMap::new();
// The elements entered and not yet left: one entered again is a loop.
let mut open: HashSet<roxmltree::NodeId> = HashSet::new();
enum Step<'a, 'i> {
Enter(XNode<'a, 'i>),
/// An element, what its cost adds up (its children, or what a `<use>` shows), and the one
/// element a `<use>` shows alone.
Leave(XNode<'a, 'i>, Vec<XNode<'a, 'i>>, Option<XNode<'a, 'i>>),
}
let root = xml.root_element();
let mut stack = vec![Step::Enter(root)];
while let Some(step) = stack.pop() {
match step {
Step::Enter(n) => {
if costs.contains_key(&n.id()) || svg_name(n).is_none_or(|name| name == "style") {
continue;
}
if !open.insert(n.id()) {
// usvg copies a loop until it nests past what it reads.
return Err(Past::Depth);
}
// The elements entered and not yet left are the ones it is nested in.
if open.len() > depth {
return Err(Past::Depth);
}
let (parts, bare) = match svg_name(n) {
Some("text") => (vec![], None),
Some("use") => match m.shows(n) {
Shows::All(link) => (vec![link], None),
Shows::Bare(link) => (vec![], Some(link)),
Shows::Nothing => (vec![], None),
},
_ => (n.children().filter(|c| svg_name(*c).is_some_and(|name| name != "style")).collect(), None),
};
stack.push(Step::Leave(n, parts.clone(), bare));
stack.extend(parts.into_iter().map(Step::Enter));
}
Step::Leave(n, parts, bare) => {
open.remove(&n.id());
let mut cost = match svg_name(n) {
Some("text") => m.text(n),
_ => m.own(n),
};
if let Some(link) = bare {
cost = cost.add(m.own(link));
}
for part in parts {
cost = cost.add(costs.get(&part.id()).copied().unwrap_or_default());
}
if cost.elements > elements {
return Err(Past::Elements);
}
if cost.bytes > bytes {
return Err(Past::Bytes);
}
costs.insert(n.id(), cost);
}
}
}
Ok(costs.get(&root.id()).copied().unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
fn svg(body: &str) -> String {
format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10">{body}</svg>"#)
}
/// What [`measure`] makes of `text` with no limits, as (elements, bytes).
fn cost(text: &str) -> (u64, u64) {
let xml = roxmltree::Document::parse(text).unwrap();
let c = measure(&xml, u64::MAX, u64::MAX, usize::MAX).unwrap_or_else(|p| panic!("{p:?}"));
(c.elements, c.bytes)
}
fn past(text: &str, elements: u64, bytes: u64) -> Option<Past> {
measure(&roxmltree::Document::parse(text).unwrap(), elements, bytes, usize::MAX).err()
}
/// Groups `g0` to `g{levels}`: `g0` a rectangle styled `style`, each other two `<use>`s of the
/// one before; one `<use>` of the last shown.
fn chain(levels: usize, style: &str) -> String {
let links: String = (1..=levels).map(|i| format!("<g id='g{i}'><use href='#g{0}'/><use xlink:href='#g{0}'/></g>", i - 1)).collect();
svg(&format!("<defs><g id='g0'><rect width='1' height='1' style='{style}'/></g>{links}</defs><use href='#g{levels}'/>"))
}
#[test]
fn copies_are_counted_with_their_styles_up_to_each_limit() {
// svg, defs, g0 and its rect (2), g1 with two uses of g0 (1 + 2 × 3), the shown use (1 + 7).
// Five rects, each copying `red` (3 bytes and a copy's 16).
let one = chain(1, "fill:red");
assert_eq!(cost(&one), (19, 5 * 19));
assert_eq!(past(&one, 19, 95), None);
assert_eq!(past(&one, 18, 95), Some(Past::Elements));
assert_eq!(past(&one, 19, 94), Some(Past::Bytes));
// Each level doubles what the shown use holds, without making any of it.
let (elements, _) = cost(&chain(60, ""));
assert!(elements > 1 << 60, "{elements}");
assert_eq!(past(&chain(60, ""), MAX_SVG_ELEMENTS as u64, u64::MAX), Some(Past::Elements));
assert_eq!(past(&chain(40, "font-family:a"), u64::MAX, MAX_COPIED_STYLES), Some(Past::Bytes));
}
#[test]
fn the_element_limit_stays_below_where_usvg_stops() {
assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 });
}
#[test]
fn style_sheet_rules_count_where_they_match() {
let groups = "<g class='a'/>".repeat(4);
// `g` matches the four groups (16 + 3 each), `.b` none, `svg` the root (16 + 4).
let (_, bytes) = cost(&svg(&format!("<style>g{{fill:red}} .b{{fill:blue}} svg{{fill:none}}</style>{groups}")));
assert_eq!(bytes, 4 * 19 + 20);
// A style sheet of another type is not read; the style element itself makes nothing.
assert_eq!(cost(&svg(&format!("<style type='text/x'>g{{fill:red}}</style>{groups}"))), (5, 0));
// `marker` sets three properties; `font` resets twelve and sets six from its text.
let (_, marker) = cost(&svg("<path style='marker:url(#m)'/>"));
let (_, font) = cost(&svg("<path style='font:12px a'/>"));
assert_eq!((marker, font), (3 * (16 + 7), 18 * 16 + 12 * 6 + 6));
}
#[test]
fn references_usvg_leaves_out_copy_nothing() {
// A use of itself, of a group holding it, of what isn't there or isn't SVG.
let (n, _) = cost(&svg("<use id='u' href='#u'/><g id='a'><g><use href='#a'/></g></g><use href='#none'/><x id='x'/><use href='#x'/>"));
assert_eq!(n, 1 + 1 + 3 + 1 + 1);
// Two uses of each other: each shows the other alone.
assert_eq!(cost(&svg("<use id='u1' href='#u2'/><use id='u2' href='#u1'/>")).0, 1 + 2 + 2);
// A group holding a use of the use that shows it: that use shows nothing, and the one the
// group holds shows it alone.
let back = svg("<g id='g'><use id='inner' href='#outer'/></g><use id='outer' href='#g'/>");
assert_eq!(cost(&back).0, 1 + 3 + 1);
// The unprefixed href wins, and an id names its first element.
let first = svg("<g id='a'><rect/><rect/></g><g id='a'/><rect id='b'/><use xlink:href='#a' href='#b'/><use href='#a'/>");
assert_eq!(cost(&first).0, 1 + 3 + 1 + 1 + 2 + 4);
}
#[test]
fn a_loop_usvg_copies_without_end_is_refused_as_usvg_refuses_it() {
let looped = svg("<g id='a'><use href='#b'/></g><g id='b'><use href='#a'/></g>");
assert_eq!(past(&looped, u64::MAX, u64::MAX), Some(Past::Depth));
assert!(usvg::Tree::from_str(&looped, &usvg::Options::default()).is_err());
// Without the loop, usvg reads it.
let open = svg("<g id='a'><use href='#b'/></g><g id='b'><rect width='1' height='1'/></g>");
assert!(past(&open, u64::MAX, u64::MAX).is_none() && usvg::Tree::from_str(&open, &usvg::Options::default()).is_ok());
}
/// A chain of `<use>`s nested past the depth is too deep, as `depth::height` finds it, before
/// what the chain makes is added up; one within the depth `depth::height` gives is not.
#[test]
fn copies_nested_past_the_depth_are_too_deep() {
let links: String = (0..3000).map(|i| format!("<g id='u{i}'><use href='#u{}'/></g>", i + 1)).collect();
let deep = svg(&format!("<defs>{links}<rect id='u3000' width='1' height='1'/></defs><use href='#u0'/>"));
let xml = roxmltree::Document::parse(&deep).unwrap();
assert_eq!(measure(&xml, u64::MAX, u64::MAX, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth));
assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none());
assert!(matches!(check(&xml, MAX_COPIED_STYLES, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_))));
for text in [chain(5, ""), svg("<g><g><use href='#r'/></g></g><rect id='r'/>")] {
let xml = roxmltree::Document::parse(&text).unwrap();
let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0);
assert!(measure(&xml, u64::MAX, u64::MAX, height).is_ok(), "{height} {text}");
}
}
#[test]
fn text_counts_its_runs_and_what_trefs_show() {
let (n, bytes) = cost(&svg("<g id='t'>abcd</g><text>xy<tspan>z</tspan><tref href='#t'/></text>"));
// svg, g (its text is not counted outside a text), text, its runs "xy" and "z", tspan, tref and its text.
assert_eq!(n, 1 + 1 + 1 + 2 + 1 + 1 + 1);
assert_eq!(bytes, (16 + 2) + (16 + 1) + (16 + 4));
}
/// A long style sheet rule that matches many elements is refused before the import's own style
/// cascade (which keeps the declarations of each element) reads them, in an SVG and in an SVG
/// image it shows.
#[test]
fn a_long_rule_on_many_elements_is_refused_before_the_cascade_reads_it() {
let groups = svg(&format!("<style>g{{font-family:{}}}</style>{}", "a".repeat(100_000), "<g/>".repeat(1000)));
let image = svg(&format!(r#"<image href="data:image/svg+xml;base64,{}" width="10" height="10"/>"#, crate::base64_encode(groups.as_bytes())));
for text in [groups, image] {
let before = super::super::css::selector_tests();
let err = super::super::import(&text, &crate::ImportOptions::default(), MAX_NODES).err();
assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}");
assert_eq!(super::super::css::selector_tests(), before);
}
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ thread_local! {
/// [`SELECTOR_TESTS`] of this thread.
#[cfg(test)]
fn selector_tests() -> u64 {
pub(super) fn selector_tests() -> u64 {
SELECTOR_TESTS.get()
}
+57 -8
View File
@@ -21,7 +21,7 @@ use usvg::{ImageHrefResolver, ImageKind, roxmltree};
use vectorcraft_doc::LinkInfo;
use vectorcraft_doc::links::missing_placeholder;
use super::{Edits, depth, href};
use super::{Edits, budget, depth, href};
use crate::{ImportOptions, MAX_ELEMENT_DEPTH, MAX_SVGZ, SvgError};
/// Most nested SVG images an imported SVG may decode (#3564).
@@ -74,6 +74,12 @@ pub(in crate::import) struct Files {
/// The CMYK TIFF stored in place of a turned CMYK image, by the address of the PNG usvg got
/// (kept here too, so the address stays its own).
cmyk: Mutex<HashMap<usize, (Bytes, Bytes)>>,
/// The bytes of style values usvg copies into the elements of the SVG and of the SVG images
/// read so far ([`budget`]).
styles: AtomicU64,
/// Why an SVG image refused the whole SVG: what usvg would make of it is past [`budget`]'s
/// limits. The first one.
refused: Mutex<Option<SvgError>>,
}
/// Encoded image bytes, shared.
@@ -479,6 +485,17 @@ impl Files {
notes
}
/// The SVG holding the images copies `bytes` of style values ([`budget::check`]): its images
/// copy at most what is left.
pub(in crate::import) fn copied_styles(&self, bytes: u64) {
self.styles.store(bytes, Ordering::Relaxed);
}
/// The error of the first SVG image past [`budget`]'s limits, which refuses the SVG holding it.
pub(in crate::import) fn refused(&self) -> Option<SvgError> {
self.refused.lock().ok().and_then(|r| r.clone())
}
fn note_text(&self, svg: &str) {
if svg.contains("<text") {
self.text.store(true, Ordering::Relaxed);
@@ -559,6 +576,10 @@ impl Files {
/// [`Files::svg`]'s image once it is counted.
fn svg_tree(&self, text: &str, file: Option<Arc<SvgFile>>, opts: &usvg::Options) -> Option<ImageKind> {
// The SVG holding it is refused already: no more images are read.
if self.refused().is_some() {
return None;
}
// Measured as the SVG holding it is (`import`): the text before the XML reader.
let used = self.depth.load(Ordering::Relaxed);
let left = MAX_ELEMENT_DEPTH.saturating_sub(used);
@@ -566,9 +587,25 @@ impl Files {
return leave_out(&self.too_deep, true);
}
let xml = super::parse(text).ok()?;
// What usvg would make of it, measured as the SVG holding it is (`import`), before the
// style cascade of `depth::height`; its copied styles count with theirs while usvg reads
// it, and only when it decodes. Too deep, it is left out; past the other limits, the whole
// SVG is refused.
let spent = self.styles.load(Ordering::Relaxed);
let bytes = match budget::check(&xml, budget::MAX_COPIED_STYLES.saturating_sub(spent), left) {
Ok(bytes) => bytes,
Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true),
Err(e) => {
if let Ok(mut refused) = self.refused.lock() {
refused.get_or_insert(e);
}
return None;
}
};
let Some(height) = depth::height(&xml, left) else { return leave_out(&self.too_deep, true) };
// usvg's parser would overflow on it, as on the SVG holding it (`import`).
super::convolve_matrices_ok(&xml).ok()?;
self.styles.store(spent.saturating_add(bytes), Ordering::Relaxed);
self.depth.store(used + height, Ordering::Relaxed);
let within = self.within.lock().ok().map(|mut w| w.push(file)).is_some();
// usvg's `Tree::from_data_nested`, except that hrefs to files go to the resolver.
@@ -592,7 +629,11 @@ impl Files {
w.pop();
}
self.depth.store(used, Ordering::Relaxed);
let tree = tree.ok()?;
let Ok(tree) = tree else {
// Left out: neither it nor the images inside it count.
self.styles.store(spent, Ordering::Relaxed);
return None;
};
self.note_text(text);
Some(ImageKind::SVG(tree))
}
@@ -615,10 +656,11 @@ fn raster(format: image::ImageFormat) -> Option<RasterKind> {
/// orientation ([`vectorcraft_doc::cmyk::exif_orientation`], read for PNG, JPEG, GIF, WebP and
/// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`],
/// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes
/// and fits the image as it is shown. A CMYK TIFF also keeps its inks as a CMYK TIFF
/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG or TIFF that is turned keeps them
/// turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when the pixels can't be read, and for
/// a TIFF with more strips or tiles than the decoder can count
/// and fits the image as it is shown, with the resolution the file declares
/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also
/// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG
/// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when
/// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]), before any decoder opens it.
fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
use image::ImageFormat as F;
@@ -634,9 +676,13 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
}
let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff);
let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? };
let ppi = vectorcraft_doc::ppi::resolution(&bytes);
// The resolution describes the stored pixels; a quarter turn swaps its axes.
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
let shown_ppi = ppi.map(|(x, y)| if quarter { (y, x) } else { (x, y) });
let cmyk = match orientation {
Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, None).map(|(tiff, _)| tiff),
None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, None),
Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, shown_ppi).map(|(tiff, _)| tiff),
None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, ppi),
_ => None,
};
if let Some(orientation) = orientation {
@@ -644,6 +690,9 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
}
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?;
if let Some(ppi) = shown_ppi {
png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi);
}
Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk })
}
+4
View File
@@ -366,6 +366,10 @@ pub enum SvgError {
/// nested-image expansion bombs, #3564).
#[error("the SVG expands to more than {0} nested SVG images")]
TooManyImages(usize),
/// The style values the reader would copy into the elements the SVG expands to, `<use>`
/// copies and SVG images included, add up to more than this many megabytes.
#[error("the SVG's styles expand to more than {0} MB")]
StylesTooLarge(usize),
}
/// Export a document as an SVG string (linked images are not returned: see [`export_full`]).
+88 -3
View File
@@ -69,13 +69,21 @@ fn jpeg(orientation: Option<u16>) -> Vec<u8> {
/// an Orientation tag (274) of `orientation`. Its RowsPerStrip (278) value is at byte [`ROWS_AT`]
/// and its PlanarConfiguration (284, 1) value at [`PLANAR_AT`].
fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec<u8> {
let entries: u32 = if samples == 2 { 12 } else { 11 };
tiff_at(w, h, samples, data, orientation, None)
}
/// [`tiff`], declaring `ppi` (horizontal, vertical pixels per inch) when given, with XResolution
/// (282), YResolution (283) and ResolutionUnit (296, inches).
fn tiff_at(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16, ppi: Option<(u32, u32)>) -> Vec<u8> {
let entries = 11 + u32::from(samples == 2) + 3 * u32::from(ppi.is_some());
let ifd_end = 8 + 2 + entries * 12 + 4;
let bits_at = ifd_end;
let data_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 };
let ppi_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 };
let data_at = ppi_at + if ppi.is_some() { 16 } else { 0 };
let entry = |tag: u16, kind: u16, count: u32, value: u32| {
[&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat()
};
let resolution = |tags: [(u16, u16, u32); 2]| ppi.map(|_| tags.map(|(tag, kind, value)| entry(tag, kind, 1, value))).into_iter().flatten();
// Two SHORTs fit in the entry; more are written after the directory.
let bits = match samples {
1 => 8,
@@ -97,9 +105,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec<u8>
entry(277, 3, 1, u32::from(samples)),
entry(278, 4, 1, h),
entry(279, 4, 1, u32::try_from(data.len()).unwrap()),
entry(284, 3, 1, 1),
]
.into_iter()
.chain(resolution([(282, 5, ppi_at), (283, 5, ppi_at + 8)]))
.chain([entry(284, 3, 1, 1)])
.chain(ppi.map(|_| entry(296, 3, 1, 2)))
.chain(extra)
{
out.extend(e);
@@ -110,6 +120,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec<u8>
out.extend(8u16.to_le_bytes());
}
}
if let Some((x, y)) = ppi {
for v in [x, 1, y, 1] {
out.extend(v.to_le_bytes());
}
}
assert_eq!(out.len(), data_at as usize);
out.extend(data);
out
@@ -277,6 +292,76 @@ fn a_turned_jpeg_in_an_svg_image_imports_upright() {
assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)));
}
/// [`jpeg`] with its JFIF segment declaring `x` × `y` pixels per inch.
fn jpeg_at(orientation: Option<u16>, (x, y): (u16, u16)) -> Vec<u8> {
let mut jpg = jpeg(orientation);
let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap();
jpg[jfif + 7] = 1;
jpg[jfif + 8..jfif + 10].copy_from_slice(&x.to_be_bytes());
jpg[jfif + 10..jfif + 12].copy_from_slice(&y.to_be_bytes());
jpg
}
/// The resolution the stored image of `im` declares.
fn stored_ppi(d: &Document, im: &ImageObject) -> Option<(f64, f64)> {
vectorcraft_doc::ppi::resolution(&d.images[&im.key].bytes)
}
/// A raster that import writes again as PNG keeps the resolution its file declares, linked, as a
/// data URL and inside an SVG shown as an image: its axes swapped when the image turns a quarter,
/// in their order when it turns a half or is flipped.
#[test]
fn a_turned_raster_keeps_its_resolution() {
let dir = folder("ppi");
for (orientation, ppi) in [(6, (150.0, 300.0)), (8, (150.0, 300.0)), (3, (300.0, 150.0)), (2, (300.0, 150.0))] {
let jpg = jpeg_at(Some(orientation), (300, 150));
std::fs::write(dir.join("photo.jpg"), &jpg).unwrap();
let data = format!("data:image/jpeg;base64,{}", base64_encode(&jpg));
let inner = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><image href="{data}" width="80" height="80"/></svg>"#);
let nested = format!("data:image/svg+xml;base64,{}", base64_encode(inner.as_bytes()));
for href in ["photo.jpg", data.as_str(), nested.as_str()] {
let (d, im) = import_one(&format!(r#"<image href="{href}" width="80" height="80"/>"#), Some(&dir));
let what = format!("orientation {orientation}, {}", &href[..href.len().min(20)]);
assert_eq!(d.images[&im.key].mime, "image/png", "{what}");
assert_eq!(stored_ppi(&d, &im), Some(ppi), "{what}");
}
}
let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &[0, 0, 255, 255, 0, 0, 255, 255], 6, Some((300, 150)))));
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), None);
assert_eq!((im.width, im.height), (2, 4));
assert_eq!(stored_ppi(&d, &im), Some((150.0, 300.0)), "a turned TIFF");
}
/// A TIFF that is not turned is written as PNG with the resolution it declares; a raster that
/// declares none is stored without one.
#[test]
fn an_upright_tiff_keeps_its_resolution() {
let gray = [0, 0, 255, 255, 0, 0, 255, 255];
let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &gray, 1, Some((300, 150)))));
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), None);
assert_eq!(d.images[&im.key].mime, "image/png");
assert_eq!(stored_ppi(&d, &im), Some((300.0, 150.0)));
for bytes in [tiff(4, 2, 1, &gray, 1), jpeg(Some(6))] {
let href = format!("data:;base64,{}", base64_encode(&bytes));
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), None);
assert_eq!(stored_ppi(&d, &im), None, "no resolution is made up");
}
}
/// A CMYK TIFF stored with its inks keeps its resolution, swapped when it turns a quarter.
#[test]
fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() {
let (c, none) = ([255u8, 0, 0, 0], [0u8; 4]);
let data: Vec<u8> = [c, c, none, none, c, c, none, none].concat();
for (orientation, ppi) in [(1, (300.0, 150.0)), (6, (150.0, 300.0))] {
let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 4, &data, orientation, Some((300, 150)))));
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), None);
assert_eq!(d.images[&im.key].mime, "image/tiff", "orientation {orientation}");
assert!(d.images[&im.key].cmyk().is_some(), "orientation {orientation}: CMYK inks");
assert_eq!(stored_ppi(&d, &im), Some(ppi), "orientation {orientation}");
}
}
/// A turned JPEG that a linked SVG file links to is turned too.
#[test]
fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() {
+60
View File
@@ -851,6 +851,66 @@ fn nested_image_within_budget_imports_and_use_fan_out_is_refused() {
assert!(matches!(err, SvgError::TooLarge(15)), "{err:?}");
}
/// Groups `g0` to `g{levels}`: `g0` a rectangle styled `style`, each other two `<use>`s of the
/// one before; one `<use>` of the last shown.
fn use_chain(levels: usize, style: &str) -> String {
let links: String = (1..=levels).map(|i| format!(r##"<g id="g{i}"><use href="#g{0}"/><use href="#g{0}"/></g>"##, i - 1)).collect();
svg(&format!(r##"<defs><g id="g0"><rect width="1" height="1" style="{style}"/></g>{links}</defs><use href="#g{levels}"/>"##))
}
/// A style value of 100,000 bytes.
fn long_style() -> String {
format!("font-family:{}", "a".repeat(100_000))
}
/// A long style that a chain of `<use>`s copies, or that a style sheet rule gives to many
/// elements, is refused before usvg copies it; short styles import, a rule that matches nothing
/// costing nothing.
#[test]
fn styles_that_expand_past_the_limit_are_refused() {
let err = import_with(&use_chain(10, &long_style()), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}");
assert_eq!(err.to_string(), "the SVG's styles expand to more than 64 MB");
// 1,000 groups that one rule gives the long style, without any `<use>`.
let sheet = svg(&format!("<style>g{{{}}}</style>{}", long_style(), "<g/>".repeat(1000)));
let err = import_with(&sheet, &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}");
// The chain with a short style shows its 1,024 rectangles.
let (d, _) = import_with(&use_chain(10, "fill:red"), &ImportOptions::default()).unwrap();
assert_eq!(art(&d).iter().filter(|n| n.children().is_none()).count(), 1024);
// 5,000 rectangles of a class with short rules, beside a long rule that matches none of them.
let rules = format!(".a{{fill:#123456;stroke:#654321;stroke-width:2;opacity:.5}} .b{{{}}}", long_style());
let classed = svg(&format!("<style>{rules}</style>{}", r#"<rect class="a" width="1" height="1"/>"#.repeat(5000)));
let (d, _) = import_with(&classed, &ImportOptions::default()).unwrap();
assert_eq!(art(&d).len(), 5000);
}
/// A chain of `<use>`s that makes more elements than usvg reads is refused before usvg makes them.
#[test]
fn a_use_chain_past_the_elements_usvg_reads_is_refused() {
let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}");
}
/// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images
/// share the limit with the SVG showing them.
#[test]
fn svg_images_whose_styles_expand_past_the_limit_refuse_the_svg() {
let err = import_with(&svg(&image_of("image/svg+xml", &use_chain(10, &long_style()))), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}");
// Each image copies its long style 383 times (about 38 MB): one imports, two together don't.
let image = image_of("image/svg+xml", &use_chain(7, &long_style()));
let (d, _) = import_with(&svg(&image), &ImportOptions::default()).unwrap();
assert!(!art(&d).is_empty());
let err = import_with(&svg(&image.repeat(2)), &ImportOptions::default()).unwrap_err();
assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}");
// An image that doesn't decode (no size) is left out, and what it would copy doesn't count.
let sizeless = use_chain(7, &long_style()).replacen(r#"width="200" height="120""#, r#"width="0" height="0""#, 1);
let (d, _) = import_with(&svg(&format!("{}{image}", image_of("image/svg+xml", &sizeless).repeat(2))), &ImportOptions::default()).unwrap();
assert!(!art(&d).is_empty());
}
/// Nested SVG images exceeding `MAX_NESTED_SVG_IMAGES` are left out with a warning note (#3564).
#[test]
fn nested_svg_images_past_count_cap_are_left_out() {
+93 -41
View File
@@ -2,7 +2,7 @@
use proptest::prelude::*;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::{Location, key_location, location_in, location_keys};
use vectorcraft_engine::cmd::{Location, ParamsPlace, key_location, location_keys};
use vectorcraft_engine::{CommandSpec, Session, command_specs};
use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath};
@@ -518,20 +518,8 @@ pub fn command_param_keys(spec: &CommandSpec) -> Vec<String> {
keys
}
/// Parameter-name keys that name a file or folder in some command ([`key_location`]): fuzzing these
/// with arbitrary strings could write files anywhere, so callers substitute a temp path.
pub fn is_path_key(k: &str) -> bool {
key_location(k).is_some()
}
/// Path keys that name a folder a command reads, creates or writes files into ([`key_location`]):
/// `folder`, `folders`, `dir`, `directory`, `destinationFolder` and `sourceFolder`.
pub fn is_folder_key(k: &str) -> bool {
key_location(k) == Some(Location::Folder)
}
/// The location to send under the path key `k`: `safe_path` for a file, a folder next to it (in
/// the same temp folder) for a folder key.
/// The location to send under the path key `k` ([`key_location`]): `safe_path` for a file, a folder
/// next to it (in the same temp folder) for a folder key.
pub fn safe_location(k: &str, safe_path: &str) -> String {
location(key_location(k).unwrap_or(Location::File), safe_path)
}
@@ -542,55 +530,74 @@ fn location(l: Location, safe_path: &str) -> String {
if l == Location::Folder { format!("{safe_path}-folder") } else { safe_path.to_string() }
}
/// `v` with every string in it that can name a place on disk sent to the temp location: `v`
/// itself and the members of arrays in it, at any depth, when `kind` is `Some`, and in an object
/// at any depth, the strings under a path key ([`is_path_key`]). Other values keep their junk
/// shape.
fn redirect(kind: Option<Location>, v: &Value, safe_path: &str) -> Value {
/// `v`, found at `place` in a command's params, with every string in it that can name a place on
/// disk sent to the temp location: `v` itself and the members of arrays in it, at any depth, when
/// `kind` is `Some`, and in an object at any depth, the strings under a key that names a file or a
/// folder there ([`ParamsPlace::member`]: a call or a recorded step inside `v` keeps its command's
/// meaning). Other values keep their junk shape.
fn redirect(place: ParamsPlace, kind: Option<Location>, v: &Value, safe_path: &str) -> Value {
match v {
Value::String(_) => kind.map_or_else(|| v.clone(), |l| json!(location(l, safe_path))),
Value::Array(a) => Value::Array(a.iter().map(|x| redirect(kind, x, safe_path)).collect()),
Value::Object(o) => Value::Object(o.iter().map(|(k, x)| (k.clone(), redirect(key_location(k), x, safe_path))).collect()),
Value::Array(a) => {
let step = ParamsPlace::step(a);
Value::Array(a.iter().enumerate().map(|(i, x)| redirect(place.item(i, step), kind, x, safe_path)).collect())
}
Value::Object(o) => {
let carried = ParamsPlace::carried(o);
let member = |k: &String, x: &Value| {
let (below, l) = place.member(k, carried);
(k.clone(), redirect(below, l, x, safe_path))
};
Value::Object(o.iter().map(|(k, x)| member(k, x)).collect())
}
_ => v.clone(),
}
}
/// `v`, with its strings sent to the temp location when `k` is a path key in any command
/// ([`is_path_key`]), and the strings under path keys in objects inside it too.
pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value {
redirect(key_location(k), v, safe_path)
/// `v`, sent under key `k` at `place`, as [`redirect`] makes it.
fn redirect_under(place: ParamsPlace, k: &str, v: &Value, safe_path: &str) -> Value {
let (below, kind) = place.member(k, None);
redirect(below, kind, v, safe_path)
}
/// `v` as [`safe_value`] makes it for command `spec` ([`location_in`]): a key that names part of
/// the document in it keeps its strings.
/// `v`, with its strings sent to the temp location when `k` is a path key in a command that gives it
/// no other meaning ([`key_location`]), and the strings under path keys in objects inside it too.
pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value {
redirect_under(ParamsPlace::top(None), k, v, safe_path)
}
/// `v` as [`safe_value`] makes it for command `spec` ([`vectorcraft_engine::cmd::location_in`]): a key that names part of
/// the document in it keeps its strings, at the top level and below.
pub fn safe_value_for_command(spec: &CommandSpec, k: &str, v: &Value, safe_path: &str) -> Value {
redirect(location_in(spec, k), v, safe_path)
redirect_under(ParamsPlace::top(Some(spec)), k, v, safe_path)
}
/// A deterministic list of junk param objects for `doc` (the command's params doc): each
/// documented key set to each junk value, all keys junk at once, wrong top-level types. A string
/// under a key that names a file or folder in any command ([`is_path_key`]) is a temp location.
/// under a key that names a file or folder in a command that gives it no other meaning
/// ([`key_location`]) is a temp location.
pub fn junk_params(doc: &str, safe_path: &str) -> Vec<Value> {
junk_params_with(&param_keys(doc), |k, v| safe_value(k, v, safe_path), key_location, safe_path)
junk_params_with(&param_keys(doc), ParamsPlace::top(None), safe_path)
}
/// [`junk_params`] for command `spec`, with the keys of its schema and its file and folder keys too
/// ([`command_param_keys`]), and a string under each key that names a file or folder in it
/// ([`location_in`]) a temp location, as are the strings in an array of them and under the path
/// ([`vectorcraft_engine::cmd::location_in`]) a temp location, as are the strings in an array of them and under the path
/// keys of objects in one (`paths: [{ids, path}]`), which it also sends.
pub fn junk_params_for_command(spec: &CommandSpec, safe_path: &str) -> Vec<Value> {
junk_params_with(&command_param_keys(spec), |k, v| safe_value_for_command(spec, k, v, safe_path), |k| location_in(spec, k), safe_path)
junk_params_with(&command_param_keys(spec), ParamsPlace::top(Some(spec)), safe_path)
}
/// The junk cases for `keys`: `safe(k, v)` is what is sent for junk value `v` under `k`, and
/// `kind(k)` what `k` names on disk, if anything, whose keys also get a list of locations and a
/// list of objects with a `path`.
fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind: impl Fn(&str) -> Option<Location>, safe_path: &str) -> Vec<Value> {
/// The junk cases for `keys` at `place`, the top of a command's params: what is sent for a junk value
/// under a key is [`redirect_under`] it, and a key that names a file or a folder there also gets a
/// list of locations and a list of objects with a `path`.
fn junk_params_with(keys: &[String], place: ParamsPlace, safe_path: &str) -> Vec<Value> {
let junk = junk_values();
let mut out = vec![Value::Null, json!([]), json!("str"), json!(42), json!({"unknownKey": 1})];
for k in keys {
let (below, kind) = place.member(k, None);
for (i, v) in junk.iter().enumerate() {
let v = safe(k, v);
let v = redirect(below, kind, v, safe_path);
// Sparse: one key at a time with every junk value, plus a few combos.
let mut o = serde_json::Map::new();
o.insert(k.clone(), v.clone());
@@ -598,17 +605,62 @@ fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind:
if i % 5 == 0 {
let mut all = serde_json::Map::new();
for k2 in keys {
let v2 = kind(k2).map_or_else(|| v.clone(), |l| json!(location(l, safe_path)));
let v2 = place.member(k2, None).1.map_or_else(|| v.clone(), |l| json!(location(l, safe_path)));
all.insert(k2.clone(), v2);
}
out.push(Value::Object(all));
}
}
if let Some(l) = kind(k) {
if let Some(l) = kind {
for v in [json!(["junk", "", 1]), json!([{"ids": [1], "path": "junk"}, {"path": null}])] {
out.push(json!({ k.as_str(): redirect(Some(l), &v, safe_path) }));
out.push(json!({ k.as_str(): redirect(below, Some(l), &v, safe_path) }));
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// The strings the sweeps send keep the meaning the command gives their key, at every depth: an
/// export's folder grouping and a web link stay as sent, also inside a `command.batch` step and
/// a recorded step, and a real file or folder key there goes to the temp location. A key that names
/// part of the document in a recorded step's command stays, and the same key in a command that
/// doesn't take it as a param names a file.
#[test]
fn nested_locations_keep_command_meaning() {
let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap_or_else(|| panic!("no command {id}"));
let safe = "/tmp/sweep/out.bin";
let settings = json!({"folders": "rows", "formats": [{"format": "png", "folder": "junk"}]});
assert_eq!(
safe_value_for_command(spec("document.exportPresets.save"), "settings", &settings, safe),
json!({"folders": "rows", "formats": [{"format": "png", "folder": "/tmp/sweep/out.bin-folder"}]})
);
let steps = json!([
{"command": "attributes.set", "params": {"url": "https://example.com/a"}},
{"command": "document.save", "params": {"path": "junk"}},
{"command": "object.path.simplify", "params": {"wholePaths": "junk"}},
]);
assert_eq!(
safe_value_for_command(spec("command.batch"), "commands", &steps, safe),
json!([
{"command": "attributes.set", "params": {"url": "https://example.com/a"}},
{"command": "document.save", "params": {"path": safe}},
{"command": "object.path.simplify", "params": {"wholePaths": "junk"}},
])
);
let recorded = json!([
["text.createInPath", {"path": "junk"}],
["object.setLiveShape", {"path": "junk"}],
["document.compare", {"diffPath": "junk"}],
]);
assert_eq!(
safe_value("steps", &recorded, safe),
json!([["text.createInPath", {"path": "junk"}], ["object.setLiveShape", {"path": safe}], ["document.compare", {"diffPath": safe}]])
);
assert_eq!(safe_value("url", &json!("https://example.com/a"), safe), json!("https://example.com/a"));
assert_eq!(safe_value("destinationFolder", &json!("junk"), safe), json!("/tmp/sweep/out.bin-folder"));
}
}
+89 -26
View File
@@ -53,6 +53,15 @@ impl Metrics {
}
}
/// What a line band was placed below: the baseline of the line above it and the em box top that
/// line left for the next one (both `None` for a cell's first band), and the space pending between.
#[derive(Clone, Copy, Default)]
pub(super) struct Above {
pub(super) prev: Option<f64>,
pub(super) next_top: Option<f64>,
pub(super) pending: f64,
}
/// Where the next line goes: the region being filled and the previous baseline in it.
#[derive(Clone)]
pub(super) struct Pen<'r> {
@@ -64,6 +73,8 @@ pub(super) struct Pen<'r> {
pub(super) fb_min: f64,
/// Further spans at the current baseline (text wrapping on both sides of an object).
pub(super) queued: Vec<(f64, f64, f64)>,
/// What the line band at the current baseline was placed below (see [`Above`]).
pub(super) above: Above,
/// Leading measured from em box top to em box top: where the next line's em box top goes.
pub(super) model: LeadingModel,
pub(super) next_top: Option<f64>,
@@ -108,16 +119,21 @@ impl Pen<'_> {
/// [`Pen::place`], skipping lines of a non-rectangular frame narrower than `min`.
fn place_at_least(&mut self, est: Metrics, ind_l: f64, ind_r: f64, min: f64) -> Option<(f64, f64, f64, bool)> {
let Some(regions) = self.regions else {
let b = self.prev.map_or(0.0, |b| self.next_baseline(b, est));
let b = self.prev.map_or(0.0, |b| self.next_baseline(b, self.next_top, self.pending, est));
return Some((b, f64::NEG_INFINITY, f64::INFINITY, false));
};
// A further span was measured across the height of the line set before it on its baseline.
// This line gets the part of it that is free across its own height: a taller line can
// reach a wrap object the line before it stayed clear of. A span with no such part is
// left empty, and so is a part the line's height made narrower than `min`.
// left empty, and so is a part the line's height made narrower than `min`. A span on a
// baseline nearer the line above the band than this line's own leading sets it is left
// empty too: a taller line would reach into that line.
while !self.queued.is_empty() {
let (b, x0, x1) = self.queued.remove(0);
let Some(r) = regions.get(self.ri) else { return Some((b, x0, x1, true)) };
if b + EPS < self.band_baseline(r, est) {
continue;
}
let mut free = r.spans(b - est.asc, b + est.desc).into_iter().filter_map(|(s, e)| {
let (s, e) = (s.max(x0), e.min(x1));
let room = e - s - ind_l - ind_r;
@@ -132,11 +148,8 @@ impl Pen<'_> {
}
loop {
let r = regions.get(self.ri)?;
let mut baseline = match self.prev {
None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min),
None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min),
Some(b) => self.next_baseline(b, est) + r.gap,
};
self.above = Above { prev: self.prev, next_top: self.next_top, pending: self.pending };
let mut baseline = self.band_baseline(r, est);
// The baseline moves down the cell a lead at a time, or a `MAX_STEPS`th of the cell's
// height when that is more, in at most `MAX_STEPS` steps.
let step = est.lead.max(1.0).max(r.cell.height() / MAX_STEPS as f64);
@@ -188,13 +201,30 @@ impl Pen<'_> {
pub(super) fn bottom(&self) -> f64 {
self.regions.and_then(|r| r.get(self.ri)).map_or(f64::INFINITY, |r| r.bottom())
}
/// The baseline of the line after the one at `prev`, for a line of metrics `est`.
fn next_baseline(&self, prev: f64, est: Metrics) -> f64 {
match (self.model, self.next_top) {
(LeadingModel::EmBoxTop, Some(top)) => top + est.top + self.pending,
_ => prev + est.lead + self.pending,
/// The baseline of the line after the one at `prev`, which left the next em box top at
/// `next_top`, for a line of metrics `est` with `pending` space between them.
fn next_baseline(&self, prev: f64, next_top: Option<f64>, pending: f64, est: Metrics) -> f64 {
match (self.model, next_top) {
(LeadingModel::EmBoxTop, Some(top)) => top + est.top + pending,
_ => prev + est.lead + pending,
}
}
/// The highest baseline in cell `r` for a line of metrics `est` in the current line band: as
/// far below the line above the band ([`Pen::above`]) as its own leading sets it, or at the
/// cell's first baseline.
fn band_baseline(&self, r: &Region, est: Metrics) -> f64 {
let Above { prev, next_top, pending } = self.above;
match prev {
None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min),
None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min),
Some(b) => self.next_baseline(b, next_top, pending, est) + r.gap,
}
}
/// A line of metrics `m` set in a further span at baseline `b` is no nearer the line above
/// the band than its own leading sets it.
pub(super) fn clears_above(&self, b: f64, m: Metrics) -> bool {
self.regions.and_then(|r| r.get(self.ri)).is_none_or(|r| b + EPS >= self.band_baseline(r, m))
}
/// A line was set at `baseline` with metrics `m`: where the next one goes from.
pub(super) fn settled(&mut self, baseline: f64, m: Metrics) {
self.prev = Some(baseline);
@@ -214,18 +244,30 @@ pub(super) fn tab_advance<'t, 'g>(
) -> (f64, &'t str) {
use vectorcraft_doc::TabAlign;
let rel = x - origin;
let seg: Vec<&SGlyph> = rest.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect();
let width: f64 = seg.iter().map(|g| g.adv).sum();
let target = |pos: f64, align: TabAlign, on: char| match align {
TabAlign::Left => pos,
TabAlign::Right => pos - width,
TabAlign::Center => pos - width / 2.0,
TabAlign::Decimal => pos - seg.iter().take_while(|g| g.ch != on).map(|g| g.adv).sum::<f64>(),
};
let explicit = tabs.iter().find_map(|t| {
let at = target(t.position, t.align, t.align_on);
(at > rel + 1e-6).then_some((at, t.leader.as_str()))
});
// The text after the tab is read only when a right, center or decimal stop is reached, since
// only those align it. A tab to a default or left stop reads none of it.
let mut rest = Some(rest);
let mut seg: Vec<&SGlyph> = Vec::new();
let mut width = 0.0;
let mut explicit = None;
for t in tabs {
if t.align != TabAlign::Left
&& let Some(r) = rest.take()
{
seg = r.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect();
width = seg.iter().map(|g| g.adv).sum();
}
let at = match t.align {
TabAlign::Left => t.position,
TabAlign::Right => t.position - width,
TabAlign::Center => t.position - width / 2.0,
TabAlign::Decimal => t.position - seg.iter().take_while(|g| g.ch != t.align_on).map(|g| g.adv).sum::<f64>(),
};
if at > rel + 1e-6 {
explicit = Some((at, t.leader.as_str()));
break;
}
}
let (at, leader) = explicit.unwrap_or_else(|| {
let last = tabs.iter().map(|t| t.position).fold(0.0, f64::max).max(0.0);
let base = rel.max(last);
@@ -263,7 +305,8 @@ const MAX_DRAWN_CHECKS: usize = 256;
/// Most breaks, or hyphenation points, [`break_line`] measures as drawn one by one when a glyph of
/// the line has a negative advance: a later break can then be drawn narrower than an earlier one,
/// and bisecting can miss the latest break that fits.
/// and bisecting can miss the latest break that fits. It is also the most legal breaks such a line
/// reads past where it first overflows in the order of its text.
const MAX_DRAWN_CHECKS_STEPPING_BACK: usize = 1024;
/// Most copies of a leader drawn in one tab: a tiny type size and a far stop must not make
@@ -369,7 +412,11 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
/// while the least it can be drawn at fits `width`, then ends at the latest legal break where it
/// fits as drawn (past [`MAX_DRAWN_CHECKS`] breaks back from the latest, or
/// [`MAX_DRAWN_CHECKS_STEPPING_BACK`] when a glyph of the line has a negative advance, the earlier
/// ones without a hyphen are bisected); hyphenation points are measured the same way.
/// ones without a hyphen are bisected); hyphenation points are measured the same way. Once such a
/// line holds a glyph with a negative advance and has been wider than `width` in the order of its
/// text, it reads at most [`MAX_DRAWN_CHECKS_STEPPING_BACK`] legal breaks further, and a forced
/// line break right after the last of them, and ends at the latest of the breaks read that fits as
/// drawn.
#[allow(clippy::too_many_arguments)]
pub(super) fn break_line(
text: &str,
@@ -439,6 +486,11 @@ pub(super) fn break_line(
}
};
let mut last_break: Option<(usize, bool)> = None;
// Whether the line, once it holds a tab and is measured as drawn, has been wider in the order of
// its text than `width`, and how many legal breaks it has read since then with a glyph stepping
// back: past MAX_DRAWN_CHECKS_STEPPING_BACK of them the line stops reading.
let mut overflowed = false;
let mut breaks_past_overflow = 0usize;
// A list marker (length 0) is a cluster of its own; the line holds it and at least the first
// cluster after it.
let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count();
@@ -489,6 +541,7 @@ pub(super) fn break_line(
// there are tabs.
let stops_reached = if back + cluster_back > 0.0 { f64::NEG_INFINITY } else { nth_stop(tabs_read) - x_start };
let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width };
overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS;
if j > first && !gl.is_space() && measured - end_credit > width + EPS {
// It ends the line with the spaces after it.
if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1, kinsoku) {
@@ -517,6 +570,15 @@ pub(super) fn break_line(
if fits.is_some() {
breaks.push((cluster_end, hyphenated));
}
// A line with a glyph stepping back stops reading MAX_DRAWN_CHECKS_STEPPING_BACK
// breaks past where it first overflowed in the order of its text, and ends at the
// latest break read that fits as drawn: each of those breaks is measured one by one.
// A soft hyphen ending the text draws no hyphen there, as at the end of the text below.
// A break right before a forced line break reads on to it: the line ends there.
breaks_past_overflow += usize::from(overflowed && back > 0.0);
if breaks_past_overflow >= MAX_DRAWN_CHECKS_STEPPING_BACK && g.get(cluster_end).is_none_or(|n| n.ch != '\u{2028}') {
return settle(tabbed, checks(back), (cluster_end, hyphenated && cluster_end < g.len()), &breaks);
}
}
}
j = cluster_end;
@@ -967,6 +1029,7 @@ fn a_pen_out_of_baseline_steps_finds_no_room() {
fb: FirstBaseline::Ascent,
fb_min: 0.0,
queued: vec![],
above: Default::default(),
model: LeadingModel::default(),
next_top: None,
no_room_for: f64::INFINITY,
+6
View File
@@ -177,6 +177,7 @@ pub(super) fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, reg
fb: cx.opts.first_baseline,
fb_min: cx.opts.first_baseline_min,
queued: vec![],
above: Default::default(),
model: t.para_at(0).leading_model,
next_top: None,
no_room_for: f64::INFINITY,
@@ -538,6 +539,11 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
}
}
let m = metrics(end);
if same_baseline && !pen.clears_above(baseline, m) {
// A glyph taller than the first one sets the line lower than the span's baseline: the
// span is left empty, and the line goes in the next span or on the next baseline.
continue;
}
baseline += if !settle || same_baseline || (pen.regions.is_none() && first_in_region) {
0.0
} else if pen.model == LeadingModel::EmBoxTop {
+4 -2
View File
@@ -91,8 +91,9 @@ struct Placed<'r> {
/// What a line's placement depends on: its first glyph, whether it is the paragraph's first line,
/// the pen's cell, baselines, pending space, narrowest word without room and further spans, the
/// span of the line above and whether the line is past the frame's end.
type Key = (usize, bool, usize, Option<u64>, Option<u64>, u64, u64, Vec<[u64; 3]>, Option<u64>, bool);
/// span of the line above, whether the line is past the frame's end, and what the further spans'
/// band was placed below.
type Key = (usize, bool, usize, Option<u64>, Option<u64>, u64, u64, Vec<[u64; 3]>, Option<u64>, bool, (Option<u64>, Option<u64>, u64));
fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option<f64>, past: bool) -> Key {
(
@@ -106,6 +107,7 @@ fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option<f64>, past: bool) ->
pen.queued.iter().map(|&(b, x0, x1)| [b.to_bits(), x0.to_bits(), x1.to_bits()]).collect(),
span.map(f64::to_bits),
past,
(pen.above.prev.map(f64::to_bits), pen.above.next_top.map(f64::to_bits), pen.above.pending.to_bits()),
)
}
+204 -3
View File
@@ -646,6 +646,149 @@ fn a_negative_advance_after_a_tab_keeps_a_fitting_line_whole() {
assert_eq!(ended, (5, false));
}
/// A tabbed line of glyphs with negative advances, past the frame in the order of its text: `a`,
/// a tab to the default stop at 36 pt, `y` stepping back 1 pt, then `n` times `b` (1 pt), `z`
/// (−1 pt) and a space, so its glyphs other than the tab never fill the frame. Its breaks end the
/// line before glyph 2 and before 6 + 3u for each u.
fn stepping_back_tabbed_line(n: usize) -> (String, Vec<SGlyph>) {
let text = format!("a\ty{}", "bz ".repeat(n));
let specs: Vec<_> = text
.char_indices()
.map(|(byte, ch)| {
let adv = match ch {
'y' | 'z' => -1.0,
' ' => 0.0,
_ => 1.0,
};
(byte, ch.len_utf8(), adv, ch)
})
.collect();
let glyphs = synthetic_glyphs(&specs);
(text, glyphs)
}
/// A tabbed line with glyphs stepping back stops reading a bounded number of breaks past where it
/// overflows in the order of its text: a long paragraph is not read to its end to set one line.
#[test]
fn a_tabbed_line_stepping_back_stops_reading_past_its_overflow() {
let (text, glyphs) = stepping_back_tabbed_line(2000);
// The latest break the line reads is the first it measures as drawn.
let furthest = std::cell::Cell::new(0);
let measured = std::cell::Cell::new(0usize);
let drawn_fits = |end: usize, _hyphenated: bool| {
furthest.set(furthest.get().max(end));
measured.set(measured.get() + 1);
end <= 10
};
let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits);
let ended =
break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits);
assert_eq!(ended, (9, false));
// 1,024 breaks past the overflow at `y`: the break before glyph 6 + 3 × 1,023.
assert_eq!(furthest.get(), 3075, "read up to glyph {} of {}", furthest.get(), glyphs.len());
assert!(measured.get() <= 1100, "measured {} breaks as drawn", measured.get());
}
/// Where a tabbed line with glyphs stepping back stops reading, it ends at the latest break read
/// that fits as drawn, even when a break past those fits too.
#[test]
fn a_tabbed_line_stepping_back_ends_at_the_latest_break_read_that_fits() {
let (text, glyphs) = stepping_back_tabbed_line(1500);
let end = |drawn_fits: &dyn Fn(usize, bool) -> bool| {
break_line(
&text,
&glyphs,
0,
30.0,
&[],
0.0,
None,
Burasagari::None,
Kinsoku::None,
KinsokuShoriType::PushOutOnly,
false,
false,
&[],
Some(drawn_fits),
)
};
// The break before glyph 4002 is past the 1,024 breaks read after the overflow (up to 3075).
assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 4002), (9, false));
// A break among those read keeps its place.
assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 600), (600, false));
assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 3075), (3075, false));
}
/// A tabbed line with glyphs stepping back that stops reading at a soft hyphen ending the text ends
/// there without a hyphen, as a line that reads to the end of the text does.
#[test]
fn a_tabbed_line_stepping_back_ends_at_a_final_soft_hyphen_without_a_hyphen() {
// The 1,023 spaces and the soft hyphen are the 1,024 breaks the line reads past its overflow.
let text = format!("a\ty{}b\u{00AD}", "bz ".repeat(1023));
let specs: Vec<_> = text
.char_indices()
.map(|(byte, ch)| {
let adv = match ch {
'y' | 'z' => -1.0,
' ' | '\u{00AD}' => 0.0,
_ => 1.0,
};
(byte, ch.len_utf8(), adv, ch)
})
.collect();
let glyphs = synthetic_glyphs(&specs);
let len = glyphs.len();
let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end == len;
let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits);
let ended =
break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits);
assert_eq!(ended, (len, false));
}
/// A tabbed line with glyphs stepping back whose last break read comes right before a forced line
/// break ends after the forced break, so the next line does not start with it and draw empty.
#[test]
fn a_tabbed_line_stepping_back_keeps_a_forced_break_after_its_last_break_read() {
// The 1,024th space is the 1,024th break past the overflow, and glyph 3075 after it is U+2028.
let text = format!("a\ty{}\u{2028}bbb", "bz ".repeat(1024));
let specs: Vec<_> = text
.char_indices()
.map(|(byte, ch)| {
let adv = match ch {
'y' | 'z' => -1.0,
' ' | '\u{2028}' => 0.0,
_ => 1.0,
};
(byte, ch.len_utf8(), adv, ch)
})
.collect();
let glyphs = synthetic_glyphs(&specs);
assert_eq!(glyphs[3075].ch, '\u{2028}');
let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end >= 3075;
let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits);
let ended =
break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits);
assert_eq!(ended, (3076, false));
}
/// A tab to a default or left stop does not read the text after it, which only right, center and
/// decimal stops align: the first tab of a long paragraph does not read the paragraph to its end.
#[test]
fn a_tab_to_a_default_or_left_stop_reads_no_text_after_it() {
use vectorcraft_doc::{TabAlign, TabStop};
let (_, glyphs) = stepping_back_tabbed_line(2000);
let read = std::cell::Cell::new(0usize);
let rest = || glyphs[2..].iter().inspect(|_| read.set(read.get() + 1));
let left = [TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }];
assert_eq!(tab_advance(&[], 0.0, 1.0, rest()).0, 35.0);
assert_eq!(tab_advance(&left, 0.0, 1.0, rest()).0, 99.0);
assert_eq!(read.get(), 0, "read {} glyphs after the tab", read.get());
// A right stop reads up to the next tab and aligns that text on the stop.
let right = [TabStop { position: 100.0, align: TabAlign::Right, leader: String::new(), align_on: '.' }];
let short = synthetic_glyphs(&[(0, 1, 2.0, 'b'), (1, 1, 3.0, 'b'), (2, 1, 0.0, '\t'), (3, 1, 7.0, 'b')]);
assert_eq!(tab_advance(&right, 0.0, 1.0, short.iter()).0, 94.0);
}
/// A long tabbed line with a glyph that steps back ends at the latest break that fits as drawn, even
/// where a later break than one that does not fit fits again.
#[test]
@@ -911,7 +1054,8 @@ fn a_further_span_is_measured_across_the_height_of_its_line() {
wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false },
};
let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 };
let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 };
// The tall line is set at the small line's leading, so it may share the small line's baseline.
let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 14.0, cap: 21.0, xh: 15.0, top: 30.0 };
// An object down the middle of the frame splits every line in two, and `above` lies right of
// it over y 20 to 40. A small line after a baseline of 50 is set at 64, over y 54 to 67, clear
// of `above`; a tall line in the span right of it on that baseline covers y 34 to 73.
@@ -926,6 +1070,7 @@ fn a_further_span_is_measured_across_the_height_of_its_line() {
fb: FirstBaseline::Ascent,
fb_min: 0.0,
queued: vec![],
above: Default::default(),
model: LeadingModel::RomanBaseline,
next_top: None,
no_room_for: f64::INFINITY,
@@ -946,17 +1091,72 @@ fn a_further_span_is_measured_across_the_height_of_its_line() {
assert!(near(right, (64.0, 220.0, 300.0, true)), "{right:?}");
// That part is 80 wide: a tall line that starts with a wider word goes on the next baseline.
let (_, right) = set(Rect::new(300.0, 20.0, 400.0, 40.0), 100.0);
assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}");
assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}");
// `above` covers the whole span: the tall line goes on the next baseline, left of the object.
let (left, right) = set(Rect::new(220.0, 20.0, 400.0, 40.0), 0.0);
assert!(near(left, (64.0, 0.0, 180.0, false)), "{left:?}");
assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}");
assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}");
// `above` lies below the tall line: the span is as wide for it as for the small line, and it
// takes the span whatever its first word, as a further span always did.
let (_, right) = set(Rect::new(300.0, 300.0, 400.0, 320.0), 200.0);
assert!(near(right, (64.0, 220.0, 400.0, true)), "{right:?}");
}
/// A further span goes only to a line whose own leading sets it no higher than the span's
/// baseline: a taller line leaves the span empty and goes on the next baseline, so its ascent does
/// not reach into the line above the band. In a cell's first band, a taller line leaves a span
/// whose baseline is above its own first baseline in the cell.
#[test]
fn a_further_span_is_left_to_a_line_its_leading_sets_there() {
use std::cell::Cell;
use std::rc::Rc;
let frame = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1);
let wraps = [vectorcraft_doc::WrapShape {
path: PathData::from_bezpath(&Rect::new(180.0, 0.0, 220.0, 400.0).to_path(0.1)),
wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false },
}];
let regions = region::Region::cells(&frame, &LayoutOptions::default(), &wraps);
let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 };
let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 };
let set = |prev: Option<f64>, model: LeadingModel, next: breaking::Metrics| {
let mut pen = breaking::Pen {
regions: Some(&regions),
ri: 0,
prev,
pending: 0.0,
fb: FirstBaseline::Ascent,
fb_min: 0.0,
queued: vec![],
above: Default::default(),
model,
next_top: prev.map(|b| b - small.top + small.lead),
no_room_for: f64::INFINITY,
steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)),
search: Default::default(),
};
let left = pen.place(small, 0.0, 0.0, 0.0);
let at = left.map_or(f64::NAN, |l| l.0);
pen.settled(at, small);
let ok = pen.clears_above(at, next);
(left, pen.place(next, 0.0, 0.0, 0.0), ok)
};
let near = |got: Option<(f64, f64, f64, bool)>, want: (f64, f64, f64, bool)| {
got.is_some_and(|g| (g.0 - want.0).abs() < 0.01 && (g.1 - want.1).abs() < 0.01 && (g.2 - want.2).abs() < 0.01 && g.3 == want.3)
};
// The next baseline for the tall line after the small one at 64, and after the small one at 10.
for (model, after_64, after_10) in [(LeadingModel::RomanBaseline, 106.0, 52.0), (LeadingModel::EmBoxTop, 98.0, 44.0)] {
// After a line at 50, the small line is set at 64. A small line takes the span right of the
// object on that baseline; a tall line, which its leading sets lower, goes on the next one.
let (left, right, ok) = set(Some(50.0), model, small);
assert!(near(left, (64.0, 0.0, 180.0, false)) && near(right, (64.0, 220.0, 400.0, true)) && ok, "{model:?}: {left:?} {right:?}");
let (_, right, ok) = set(Some(50.0), model, tall);
assert!(near(right, (after_64, 0.0, 180.0, false)) && !ok, "{model:?}: {right:?}");
// The cell's first band: the small line at 10, the tall line on the next baseline.
let (left, right, ok) = set(None, model, tall);
assert!(near(left, (10.0, 0.0, 180.0, false)) && near(right, (after_10, 0.0, 180.0, false)) && !ok, "{model:?}: {left:?} {right:?}");
}
}
/// The every-line composer's searches for the paragraphs of one frame share one budget: each takes
/// the lines it tried and the baseline steps it spent from it, the layout's own steps stay as they
/// were, and once the budget runs out the next paragraph's search stops (it is broken line by line).
@@ -990,6 +1190,7 @@ fn shaped_composition_searches_share_the_frame_budget() {
fb: FirstBaseline::Ascent,
fb_min: 0.0,
queued: vec![],
above: Default::default(),
model: LeadingModel::default(),
next_top: None,
no_room_for: f64::INFINITY,
+30
View File
@@ -443,6 +443,36 @@ fn composer_x_mixed_sizes_around_text_wrap() {
assert_eq!(every, greedy);
}
#[test]
fn composer_x_taller_line_in_a_further_span() {
// A wrap object down the middle of the frame splits every line in two. The 36 pt word falls in
// the span right of it on the second baseline, after a 12 pt line left of it: the line that
// holds it is set as far below the line above it as its own leading sets it, and its ascent
// stays clear of that line, with either composer.
let w = x_width();
let object = Rect::new(w, -10.0, w + 40.0, 310.0);
for composer in [Composer::SingleLine, Composer::EveryLine] {
let mut runs = vec![run(&format!("{RAG} Then draw a card for each creature destroyed this way. "), sans(12.0))];
runs.extend(with_x(sans(36.0)));
let mut t = area(runs, Rect::new(0.0, 0.0, 2.0 * w + 40.0, 300.0));
t.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&object.to_path(0.1)), wrap: Default::default() }];
t.para.composer = composer;
let l = layout(db(), &t);
assert!(!l.overflow, "{composer:?}: {:?}", l.lines);
let tall: Vec<_> = l.lines.iter().filter(|line| line.ascent > 30.0).collect();
assert_eq!(tall.len(), 1, "{composer:?}: {:?}", l.lines);
for line in tall {
for above in l.lines.iter().filter(|a| a.baseline < line.baseline - 0.01) {
let beside = above.avail.0 < line.avail.1 && line.avail.0 < above.avail.1;
assert!(
!beside || line.baseline - line.ascent >= above.baseline + above.descent - 0.01,
"{composer:?}: {line:?} reaches into {above:?}"
);
}
}
}
}
#[test]
fn composer_x_mixed_sizes_in_a_frame_that_widens() {
// A frame as wide as "Destroy all" down to 20 pt and as wide as the first line of
+210 -80
View File
@@ -21,7 +21,10 @@ mod caps;
mod mesh;
pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh};
mod shadow;
pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW};
pub use shadow::{
MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed,
plane_shadowed, revolve_facets_shadowed, revolve_shadowed,
};
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2};
@@ -961,21 +964,136 @@ fn revolve_face_limit(o: Revolve) -> usize {
/// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn,
/// each turned out of the region `rule` fills.
fn revolve_faces(
fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec<solid::Face3>>) -> Result<Vec<Face>, String> {
let draw = mesh.is_none();
revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces)
}
#[cfg(test)]
thread_local! {
/// How many Revolve surfaces this thread has swept, for the tests.
pub(crate) static REVOLVED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// One contour's profile as a sweep takes it: its points, the tangents at the ends of each edge,
/// and whether each edge walls a hole.
#[derive(Default)]
struct Swept {
points: Vec<Point>,
tangents: Vec<[Vec2; 2]>,
holes: Vec<bool>,
}
/// Where a sweep places a profile: about the axis at `axis` and the middle height `center_y`,
/// turned through `sweep` radians in `steps` steps, with the sanitized options `o`.
struct Sweeping {
o: Revolve,
axis: f64,
center_y: f64,
sweep: f64,
steps: usize,
}
impl Sweeping {
/// Profile point `p` turned to the end of step `step`, in view space.
fn vertex(&self, p: Point, step: usize) -> V3 {
let (s, c) = (self.sweep * step as f64 / self.steps as f64).sin_cos();
self.o.rotate(V3((p.x - self.axis) * c, p.y - self.center_y, (p.x - self.axis) * s))
}
}
/// The end `index` (0 the first, 1 the last) of `profile` and the way its cap faces along the axis:
/// the sign of the end's y less its neighbor's, or with the two level, -1 for an end above the
/// middle height `center_y` and 1 otherwise.
fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, f64)> {
let neighbours = if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) };
neighbours.map(|(end, neighbour)| {
let dy = end.y - neighbour.y;
let outward = if dy.abs() > 1e-10 {
dy.signum()
} else if end.y < center_y {
-1.0
} else {
1.0
};
(*end, outward)
})
}
/// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as
/// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for
/// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn
/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its
/// error, or an edge with invalid coordinates, stops the faces.
fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec<V3>, V3) -> Result<(), String>) -> Result<(), String> {
let (o, steps) = (at.o, at.steps);
for (pair, hole) in s.points.windows(2).zip(&s.holes) {
let [a, b] = pair else { continue };
let turn = if *hole { -turn } else { turn };
if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) {
return Err("Revolve profile contains invalid coordinates".into());
}
for j in 0..steps {
let [v0, v1, v2, v3] = [at.vertex(*a, j), at.vertex(*b, j), at.vertex(*b, j + 1), at.vertex(*a, j + 1)];
// The edge's outward normal in the profile's plane (distance from the axis, height),
// swept to the middle of the step.
let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn);
let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos();
keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?;
}
}
for &index in caps {
let Some((end, outward)) = cap_outward(&s.points, index, at.center_y) else { continue };
let mut cap: Vec<V3> = (0..=steps).map(|j| at.vertex(end, j)).collect();
if o.angle >= 360.0 {
cap.pop();
} else {
cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0)));
}
keep(cap, o.rotate(V3(0.0, outward, 0.0)))?;
}
Ok(())
}
/// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn.
fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec<solid::Face3>>, lost: &mut Option<String>, e: String) -> Result<(), String> {
if !draw {
return Err(e);
}
*mesh = None;
lost.get_or_insert(e);
Ok(())
}
/// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept
/// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an
/// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces
/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result.
fn revolve_sweep(
path: &PathData,
rule: FillRule,
bounds: Rect,
options: Revolve,
draw: bool,
mut mesh: Option<&mut Vec<solid::Face3>>,
) -> Result<Vec<Face>, String> {
) -> Result<(Vec<Face>, Option<String>), String> {
#[cfg(test)]
REVOLVED.with(|n| n.set(n.get() + 1));
let o = options.sanitized();
let curve_samples = match o.curve_samples {
Some(samples) => samples.clamp(1, CURVE_SAMPLES),
None => revolve_curve_samples([path], o)?,
};
let mut lost = None;
// For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so
// each part's normal turns toward a hole only where it walls one.
let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None };
let mut search = None;
if mesh.is_some() {
match HoleSearch::new(path, rule) {
Ok(s) => search = Some(s),
Err(e) => lose_mesh(draw, &mut mesh, &mut lost, e)?,
}
}
let face_limit = revolve_face_limit(o);
// A face kept for a mesh: its normal follows from its corners.
let keep = |mesh: &mut Vec<solid::Face3>, face: Vec<V3>, normal: V3| {
@@ -1013,10 +1131,8 @@ fn revolve_faces(
// Only the longest contour of a compound profile carries the graphics.
let surface_contour = o.map_surface.then(|| longest_contour(path, axis)).flatten();
let mut faces = Vec::new();
let vertex = |p: Point, step: usize| {
let (s, c) = (sweep * step as f64 / steps as f64).sin_cos();
o.rotate(V3((p.x - axis) * c, p.y - center_y, (p.x - axis) * s))
};
let at = Sweeping { o, axis, center_y, sweep, steps };
let vertex = |p: Point, step: usize| at.vertex(p, step);
let normal = |tangent: Vec2, step: usize| {
let (s, c) = (sweep * step as f64 / steps as f64).sin_cos();
o.rotate(V3(tangent.y * c, -tangent.x, tangent.y * s).unit())
@@ -1032,17 +1148,26 @@ fn revolve_faces(
}
Ok(())
};
let mut count = 0;
// The points of the profile drawn, and of the profile kept for the mesh, which takes the parts
// its edges are cut into.
let (mut count, mut kept_count) = (0, 0);
let mut curve_budget = 0;
for (contour, sp) in path.subpaths.iter().enumerate() {
let mut profile = Vec::new();
let mut tangents = Vec::new();
let mut hole_edges = Vec::new();
let (mut drawn, mut kept) = (Swept::default(), Swept::default());
if let Some(first) = sp.anchors.first() {
profile.push(first.p);
count += 1;
if count > MAX_PROFILE_POINTS {
return Err(TOO_COMPLEX_PROFILE.into());
if draw {
drawn.points.push(first.p);
count += 1;
if count > MAX_PROFILE_POINTS {
return Err(TOO_COMPLEX_PROFILE.into());
}
}
if mesh.is_some() {
kept.points.push(first.p);
kept_count += 1;
if kept_count > MAX_PROFILE_POINTS {
lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?;
}
}
}
let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) };
@@ -1074,22 +1199,40 @@ fn revolve_faces(
let v = d.eval(t.clamp(1e-7, 1.0 - 1e-7)).to_vec2();
if v.hypot2() > 1e-20 { v } else { b - a }
};
let a = profile.last().copied().unwrap_or(b);
let parts = match search.as_mut() {
Some(search) => search.parts(contour, a, b)?,
None => vec![(b, false)],
};
for (end, hole) in parts {
tangents.push([tangent(t0), tangent(t1)]);
hole_edges.push(hole);
profile.push(end);
let ends = [tangent(t0), tangent(t1)];
if draw {
drawn.tangents.push(ends);
drawn.holes.push(false);
drawn.points.push(b);
count += 1;
if count > MAX_PROFILE_POINTS {
return Err(TOO_COMPLEX_PROFILE.into());
}
}
let Some(search) = search.as_mut().filter(|_| mesh.is_some()) else { continue };
let a = kept.points.last().copied().unwrap_or(b);
let parts = match search.parts(contour, a, b) {
Ok(parts) => parts,
Err(e) => {
lose_mesh(draw, &mut mesh, &mut lost, e)?;
continue;
}
};
for (end, hole) in parts {
kept.tangents.push(ends);
kept.holes.push(hole);
kept.points.push(end);
kept_count += 1;
if kept_count > MAX_PROFILE_POINTS {
lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?;
break;
}
}
}
}
// The two profiles start and end at the same points: the parts of the last edge end where
// it does.
let profile = if draw { &drawn.points } else { &kept.points };
let ends = o.cap_ends && !sp.closed && profile.len() >= 2 && profile.first().zip(profile.last()).is_some_and(|(a, b)| a.distance(*b) > 1e-10);
let mut rings = [None, None];
if ends {
@@ -1101,33 +1244,49 @@ fn revolve_faces(
}
}
}
// For a mesh: which way the profile runs round the region it sweeps (closed against the
// axis at its ends when it is open), so the faces' normals point out of the solid.
let turn = {
let mut ring: Vec<(f64, f64)> = profile.iter().map(|p| (p.x - axis, p.y)).collect();
if let (false, Some(first), Some(last)) = (sp.closed, profile.first(), profile.last()) {
ring.extend([(0.0, last.y), (0.0, first.y)]);
// Which way a profile runs round the region it sweeps (closed against the axis at its ends
// when it is open), so the faces' normals point out of the solid. A closed contour that does
// not touch the axis has its side cut opposite the middle of its outer side; an anchor goes
// there, so no face runs across the cut. That one anchor is not counted against the limit
// on the profile's points.
let prepare = |s: &mut Swept| {
let turn = {
let mut ring: Vec<(f64, f64)> = s.points.iter().map(|p| (p.x - axis, p.y)).collect();
if let (false, Some(first), Some(last)) = (sp.closed, s.points.first(), s.points.last()) {
ring.extend([(0.0, last.y), (0.0, first.y)]);
}
let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum();
if area < 0.0 { -1.0 } else { 1.0 }
};
if sp.closed
&& surface_contour == Some(contour)
&& let Some((k, t)) = ring_cut(&s.points, axis)
&& let (Some(a), Some(b), Some([ta, tb]), Some(hole)) =
(s.points.get(k), s.points.get(k + 1), s.tangents.get(k).copied(), s.holes.get(k).copied())
{
let point = *a + (*b - *a) * t;
let middle = ta + (tb - ta) * t;
s.points.insert(k + 1, point);
s.tangents.splice(k..=k, [[ta, middle], [middle, tb]]);
s.holes.insert(k + 1, hole);
}
let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum();
if area < 0.0 { -1.0 } else { 1.0 }
turn
};
// A closed contour that does not touch the axis has its side cut opposite the middle of its
// outer side; an anchor goes there, so no face runs across the cut. That one anchor is not
// counted against the limit on the profile's points.
if sp.closed
&& surface_contour == Some(contour)
&& let Some((k, t)) = ring_cut(&profile, axis)
&& let (Some(a), Some(b), Some([ta, tb]), Some(hole)) =
(profile.get(k), profile.get(k + 1), tangents.get(k).copied(), hole_edges.get(k).copied())
{
let point = *a + (*b - *a) * t;
let middle = ta + (tb - ta) * t;
profile.insert(k + 1, point);
tangents.splice(k..=k, [[ta, middle], [middle, tb]]);
hole_edges.insert(k + 1, hole);
if let Some(m) = mesh.as_deref_mut() {
let turn = prepare(&mut kept);
let caps: Vec<usize> = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect();
let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal));
if let Err(e) = kept {
lose_mesh(draw, &mut mesh, &mut lost, e)?;
}
}
let along = along_profile(&profile, axis, sp.closed);
for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() {
if !draw {
continue;
}
let turn = prepare(&mut drawn);
let profile = &drawn.points;
let along = along_profile(profile, axis, sp.closed);
for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() {
let [a, b] = pair else { continue };
let turn = if hole { -turn } else { turn };
let [va, vb] = along.get(i).copied().unwrap_or_default();
@@ -1136,14 +1295,6 @@ fn revolve_faces(
}
for j in 0..steps {
let [v0, v1, v2, v3] = [vertex(*a, j), vertex(*b, j), vertex(*b, j + 1), vertex(*a, j + 1)];
if let Some(mesh) = mesh.as_deref_mut() {
// The edge's outward normal in the profile's plane (distance from the axis,
// height), swept to the middle of the step.
let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn);
let (s, c) = (sweep * (j as f64 + 0.5) / steps as f64).sin_cos();
keep(mesh, vec![v0, v1, v2, v3], o.rotate(V3(dy * c, -dr, dy * s)))?;
continue;
}
let first = (i == 0).then(|| rings.first().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten();
let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten();
// Where the corners lie on the unrolled side surface, and whether the face shows
@@ -1186,28 +1337,7 @@ fn revolve_faces(
}
}
for (index, ring) in rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|r| (i, r))) {
let neighbours =
if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) };
if let Some((end, neighbour)) = neighbours {
let dy = end.y - neighbour.y;
let outward = if dy.abs() > 1e-10 {
dy.signum()
} else if end.y < center_y {
-1.0
} else {
1.0
};
if let Some(mesh) = mesh.as_deref_mut() {
// The disk, or for a partial sweep the sector with its centre on the axis.
let mut cap: Vec<V3> = (0..=steps).map(|j| vertex(*end, j)).collect();
if o.angle >= 360.0 {
cap.pop();
} else {
cap.insert(0, o.rotate(V3(0.0, end.y - center_y, 0.0)));
}
keep(mesh, cap, o.rotate(V3(0.0, outward, 0.0)))?;
continue;
}
if let Some((_, outward)) = cap_outward(profile, index, center_y) {
// Keep the original tessellation work budget, even though each cap
// now produces only one curved vector face.
emit(ring.face(bounds, o, light, outward)?, steps)?;
@@ -1215,7 +1345,7 @@ fn revolve_faces(
}
}
faces.sort_by(|a, b| a.depth.total_cmp(&b.depth));
Ok(faces)
Ok((faces, lost))
}
#[cfg(test)]
+59 -1
View File
@@ -12,7 +12,7 @@ use std::ops::Range;
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect};
use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces};
use crate::{Extrude, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale};
use crate::{Extrude, Face, Facet, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale};
/// Where the shadow falls.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -203,6 +203,14 @@ impl ShadowCaster {
self.add(faces, Some(crate::revolve_projection(bounds, o)))
}
/// Add the faces of a solid kept by the build that drew it ([`extrude_shadowed`],
/// [`plane_shadowed`], [`inflate_shadowed`], [`revolve_shadowed`]): the faces
/// [`ShadowCaster::extrude`], [`ShadowCaster::plane`], [`ShadowCaster::inflate`] or
/// [`ShadowCaster::revolve`] adds for that solid, or the error it gives.
pub fn add_solid(&mut self, solid: SolidFaces) -> Result<Range<usize>, String> {
self.add(solid.faces?, solid.projection)
}
/// The shadow of the faces gathered, on the page, filled with the nonzero rule: `None` when
/// there are none, when the first light lights nothing (Shading is off or its intensity is 0)
/// or does not reach the plane (it is behind the object for a shadow behind it, or below the
@@ -291,6 +299,56 @@ impl ShadowCaster {
}
}
/// A solid's faces before projection, kept by the build that drew it, for its shadow
/// ([`ShadowCaster::add_solid`]): the faces, or the error keeping them gave, and the projection the
/// solid was drawn with.
#[derive(Clone, Debug)]
pub struct SolidFaces {
faces: Result<Vec<Face3>, String>,
projection: Option<Projection>,
}
/// Extrude & Bevel's solid ([`crate::extrude`]) and, from the same build, the faces
/// [`ShadowCaster::extrude`] adds for it. An error where [`crate::extrude`] gives one.
pub fn extrude_shadowed(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result<(Vec<Facet>, SolidFaces), String> {
let (facets, faces, projection) = extrude_faces(path, rule, bounds, options, view, Keep::Both)?;
Ok((facets, SolidFaces { faces, projection }))
}
/// Rotate's plane ([`crate::plane`]) and, from the same build, the face [`ShadowCaster::plane`]
/// adds for it. An error where [`crate::plane`] gives one.
pub fn plane_shadowed(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<(Vec<Facet>, SolidFaces), String> {
let (facets, faces, projection) = plane_faces(path, rule, bounds, view, Keep::Both)?;
Ok((facets, SolidFaces { faces, projection }))
}
/// Inflate's solids for several shapes of one object ([`crate::inflate_each`]) and, from the same
/// builds, the faces [`ShadowCaster::inflate`] adds for each, each solid built as the iterator
/// reaches it. An error where [`crate::inflate_each`] gives one.
pub fn inflate_shadowed(
shapes: &[(&PathData, FillRule)],
bounds: Rect,
options: Inflate,
view: View,
) -> impl Iterator<Item = Result<(Vec<Facet>, SolidFaces), String>> + use<> {
inflate_faces(shapes, bounds, options, view, Keep::Both).map(|r| r.map(|(facets, faces, projection)| (facets, SolidFaces { faces, projection })))
}
/// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces
/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where
/// [`crate::revolve`] gives one.
pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec<Face>, SolidFaces), String> {
let mut kept = vec![];
let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?;
let projection = Some(crate::revolve_projection(bounds, options.sanitized()));
Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection }))
}
/// [`revolve_shadowed`] with the faces as facets, as [`crate::revolve_facets`] gives them.
pub fn revolve_facets_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec<Facet>, SolidFaces), String> {
revolve_shadowed(path, bounds, options).map(|(faces, kept)| (faces.into_iter().map(Facet::of_face).collect(), kept))
}
/// Whether `area`, the signed area of a polygon with corners `points`, is within rounding of
/// nothing for its size (the square of its bounds' diagonal), or not a number, so the polygon draws
/// nothing. A long, narrow polygon keeps an area well above that.
+241
View File
@@ -186,6 +186,247 @@ fn every_effect_casts_a_shadow() {
assert!(b.x1 > 100.0 && b.x0 < 100.0 + 1e-6, "{b:?}");
}
/// The faces `caster` gathered and the projection it keeps, every number to the bit.
fn gathered(caster: &ShadowCaster) -> String {
format!("{:?} {:?}", caster.faces, caster.projection)
}
/// What a solid kept for its shadow casts ([`casts`]).
fn cast_from(solid: SolidFaces) -> Result<(String, Option<PathData>, Option<PathData>), String> {
let mut caster = ShadowCaster::new();
caster.add_solid(solid)?;
Ok(casts(&caster))
}
/// The faces `caster` gathered, and the shadows they cast behind and below.
fn casts(caster: &ShadowCaster) -> (String, Option<PathData>, Option<PathData>) {
let below = Shadow { position: ShadowPosition::Below, distance: 0.3, ..Shadow::default() };
(gathered(caster), caster.path(Shadow::default()), caster.path(below))
}
/// A star of `points` points about (100, 100), its edges curved, with a square hole.
fn star(points: usize) -> PathData {
let mut b = BezPath::new();
for k in 0..2 * points {
let (s, c) = (k as f64 * std::f64::consts::PI / points as f64).sin_cos();
let r = if k % 2 == 0 { 90.0 } else { 45.0 };
let p = (100.0 + r * c, 100.0 + r * s);
if k == 0 { b.move_to(p) } else { b.curve_to((p.0 + 3.0, p.1), (p.0, p.1 + 3.0), p) }
}
b.close_path();
rect(&mut b, 90.0, 90.0, 20.0, 20.0);
PathData::from_bezpath(&b)
}
/// A closed rectangle from (`x`, `y`), `w` wide and `h` high.
fn rect(b: &mut BezPath, x: f64, y: f64, w: f64, h: f64) {
b.move_to((x, y));
b.line_to((x + w, y));
b.line_to((x + w, y + h));
b.line_to((x, y + h));
b.close_path();
}
/// The views the solids are compared in: straight on, turned, with perspective, and with colored
/// lights.
fn views() -> Vec<View> {
let turned = View { rotation_x: -25.0, rotation_y: 35.0, rotation_z: 10.0, ..View::default() };
vec![front(), turned, View { perspective: 60.0, ..turned }, View { light_color: [1.0, 0.5, 0.25], ..turned }]
}
/// Extrude & Bevel built once for its facets and its shadow gives the facets [`crate::extrude`]
/// gives and casts what [`ShadowCaster::extrude`] casts, to the bit, errors included.
#[test]
fn an_extruded_solid_and_its_shadow_match_the_two_built_apart() {
use crate::{Bevel, BevelShape};
let bevel = Bevel { shape: BevelShape::Rounded, width: 6.0, height: 5.0, ..Bevel::default() };
let options = [
Extrude::default(),
Extrude { depth: 0.0, ..Extrude::default() },
Extrude { cap: false, ..Extrude::default() },
Extrude { hidden: true, ..Extrude::default() },
Extrude { twist: 90.0, taper: 0.6, ..Extrude::default() },
Extrude { bevel: Some(bevel), ..Extrude::default() },
Extrude { bevel: Some(Bevel { both_sides: true, inside: true, ..bevel }), twist: 45.0, ..Extrude::default() },
];
let path = star(7);
let r = path.bounds().unwrap();
for view in views() {
for o in options {
let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, o, view).unwrap();
let apart = crate::extrude(&path, FillRule::NonZero, r, o, view).unwrap();
assert_eq!(format!("{facets:?}"), format!("{apart:?}"), "{o:?} {view:?}");
let mut caster = ShadowCaster::new();
caster.extrude(&path, FillRule::NonZero, r, o, view).unwrap();
assert!(!caster.is_empty());
assert_eq!(cast_from(faces), Ok(casts(&caster)), "{o:?} {view:?}");
}
}
let flat = Rect::new(0.0, 0.0, f64::INFINITY, 10.0);
let error = crate::extrude(&path, FillRule::NonZero, flat, Extrude::default(), front()).err();
assert!(error.is_some());
assert_eq!(extrude_shadowed(&path, FillRule::NonZero, flat, Extrude::default(), front()).err(), error);
}
/// Rotate's plane built once for its facet and its shadow matches the two built apart.
#[test]
fn a_rotated_plane_and_its_shadow_match_the_two_built_apart() {
let path = star(5);
let r = path.bounds().unwrap();
for view in views() {
for rule in [FillRule::NonZero, FillRule::EvenOdd] {
let (facets, faces) = plane_shadowed(&path, rule, r, view).unwrap();
assert_eq!(format!("{facets:?}"), format!("{:?}", crate::plane(&path, rule, r, view).unwrap()), "{view:?}");
let mut caster = ShadowCaster::new();
caster.plane(&path, rule, r, view).unwrap();
assert_eq!(cast_from(faces), Ok(casts(&caster)), "{view:?}");
}
}
}
/// Inflate's solids built once for their facets and shadows match the two built apart: several
/// puffs under one eye, both sides, open backs, and twisted sides cut finer than room is left for.
#[test]
fn inflated_solids_and_their_shadows_match_the_two_built_apart() {
let star = star(5);
let box_ = square(200.0, 20.0, 60.0);
let ring: Vec<Point> = (0..600)
.map(|k| {
let (s, c) = (k as f64 * std::f64::consts::TAU / 600.0).sin_cos();
Point::new(100.0 + 90.0 * c, 100.0 + 90.0 * s)
})
.collect();
let ring = PathData::single(vectorcraft_geom::SubPath::polyline(&ring, true));
let sets = [vec![(&star, FillRule::NonZero), (&box_, FillRule::NonZero), (&star, FillRule::EvenOdd)], vec![(&ring, FillRule::NonZero)]];
let bounds = Rect::new(0.0, 0.0, 280.0, 200.0);
let options = [
Inflate::default(),
Inflate { depth: 30.0, both_sides: true, ..Inflate::default() },
Inflate { depth: 20.0, cap: false, volume: 80.0, ..Inflate::default() },
Inflate { depth: 40.0, twist: 360.0, taper: 0.7, both_sides: true, ..Inflate::default() },
// Thin and barely twisted: the star's sides want more pieces than room is left after its
// front and back, and the shadow, which keeps the faces turned away, has less room left.
Inflate { depth: 0.1, twist: 0.1, both_sides: true, ..Inflate::default() },
];
for shapes in &sets {
for view in views() {
for o in options {
let built: Vec<_> = inflate_shadowed(shapes, bounds, o, view).collect();
let facets: Vec<_> = crate::inflate_each(shapes, bounds, o, view).collect();
let mut caster = ShadowCaster::new();
let added = caster.inflate(shapes, &vec![true; shapes.len()], bounds, o, view);
assert!(added.iter().all(Result::is_ok));
assert_eq!(built.len(), shapes.len());
let mut one = ShadowCaster::new();
for (b, f) in built.into_iter().zip(&facets) {
let ((facets, faces), f) = (b.unwrap(), f.as_ref().unwrap());
assert_eq!(format!("{facets:?}"), format!("{f:?}"), "{o:?} {view:?}");
one.add_solid(faces).unwrap();
}
assert_eq!(casts(&one), casts(&caster), "{o:?} {view:?}");
}
}
}
}
/// Revolve's surface swept once for its faces and its shadow gives the faces [`crate::revolve`]
/// gives and casts what [`ShadowCaster::revolve`] casts, to the bit: an open profile with caps,
/// closed contours that cross (their walls cut where they do), a hole, partial sweeps, smooth and
/// flat shading, and the cut side that graphics take.
#[test]
fn a_revolved_surface_and_its_shadow_match_the_two_swept_apart() {
let mut open = BezPath::new();
open.move_to((120.0, 0.0));
open.curve_to((160.0, 20.0), (100.0, 60.0), (140.0, 90.0));
open.line_to((125.0, 120.0));
let mut crossing = BezPath::new();
rect(&mut crossing, 110.0, 0.0, 60.0, 80.0);
rect(&mut crossing, 150.0, 40.0, 40.0, 80.0);
let mut holed = BezPath::new();
holed.move_to((110.0, 0.0));
holed.curve_to((200.0, 0.0), (200.0, 120.0), (110.0, 120.0));
holed.close_path();
rect(&mut holed, 130.0, 40.0, 20.0, 30.0);
let paths = [open, crossing, holed].map(|b| PathData::from_bezpath(&b));
let turned = Revolve { rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() };
let options = [
Revolve::default(),
turned,
Revolve { angle: 200.0, perspective: 40.0, ..turned },
Revolve { smooth_shading: false, segments: 12, ..turned },
Revolve { cap_ends: false, offset: 15.0, ..turned },
Revolve { map_surface: true, edge: crate::Edge::Right, ..turned },
Revolve { map_surface: true, angle: 300.0, curve_samples: Some(5), ..turned },
];
for path in &paths {
let bounds = path.bounds().unwrap();
for o in options {
let (faces, kept) = revolve_shadowed(path, bounds, o).unwrap();
assert_eq!(format!("{faces:?}"), format!("{:?}", crate::revolve(path, bounds, o).unwrap()), "{o:?}");
let (facets, also) = revolve_facets_shadowed(path, bounds, o).unwrap();
assert_eq!(format!("{facets:?}"), format!("{:?}", crate::revolve_facets(path, bounds, o).unwrap()), "{o:?}");
assert_eq!(cast_from(also), cast_from(kept.clone()), "{o:?}");
let mut caster = ShadowCaster::new();
caster.revolve(path, FillRule::NonZero, bounds, o).unwrap();
assert!(!caster.is_empty());
assert_eq!(cast_from(kept), Ok(casts(&caster)), "{o:?}");
}
}
}
/// A surface whose shadow is past the limit on the profile's points (its walls cut where they
/// cross another contour) still draws every face, and its shadow gives the error the shadow swept
/// alone gives.
#[test]
fn a_surface_whose_shadow_is_too_complex_still_draws() {
let mut b = BezPath::new();
b.move_to((110.0, 0.0));
for i in 1..6000 {
b.line_to((110.0 + f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 10.0 }));
}
b.line_to((110.0, 20.0));
b.close_path();
rect(&mut b, 100.0, 4.0, 140.0, 2.0);
let path = PathData::from_bezpath(&b);
let bounds = path.bounds().unwrap();
let o = Revolve { segments: 4, smooth_shading: false, ..Revolve::default() };
let (faces, kept) = revolve_shadowed(&path, bounds, o).unwrap();
let drawn = crate::revolve(&path, bounds, o).unwrap();
assert!(!drawn.is_empty());
assert!(faces == drawn);
let alone = ShadowCaster::new().revolve(&path, FillRule::NonZero, bounds, o).unwrap_err();
assert!(alone.contains("too complex"), "{alone}");
assert_eq!(cast_from(kept).unwrap_err(), alone);
}
/// One build gives the facets and the faces of the shadow: each solid is built once.
#[test]
fn a_solid_and_its_shadow_are_built_once() {
let path = star(5);
let r = path.bounds().unwrap();
let count = |n: &'static std::thread::LocalKey<std::cell::Cell<usize>>| n.with(std::cell::Cell::get);
let start = count(&crate::solid::EXTRUDED);
let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, Extrude::default(), front()).unwrap();
assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some()));
assert_eq!(count(&crate::solid::EXTRUDED), start + 1);
let start = count(&crate::solid::PLANES);
let (facets, faces) = plane_shadowed(&path, FillRule::NonZero, r, front()).unwrap();
assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some()));
assert_eq!(count(&crate::solid::PLANES), start + 1);
let start = count(&crate::solid::INFLATED);
let box_ = square(200.0, 20.0, 60.0);
let shapes = [(&path, FillRule::NonZero), (&box_, FillRule::NonZero)];
for solid in inflate_shadowed(&shapes, Rect::new(0.0, 0.0, 280.0, 200.0), Inflate::default(), front()) {
let (facets, faces) = solid.unwrap();
assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some()));
}
assert_eq!(count(&crate::solid::INFLATED), start + 2);
let start = count(&crate::REVOLVED);
let (drawn, faces) = revolve_shadowed(&path, r, Revolve::default()).unwrap();
assert!(!drawn.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some()));
assert_eq!(count(&crate::REVOLVED), start + 1);
}
/// An Inflate shape that casts nothing still places the eye with its puff, but its solid is not
/// built (nor, with no volume, its puff solved); the shapes that cast keep the very faces and
/// projection they have when every shape casts.
+2
View File
@@ -23,6 +23,8 @@ mod rings;
#[cfg(test)]
pub(crate) use build::EXTRUDED;
#[cfg(test)]
pub(crate) use build::PLANES;
#[cfg(test)]
use build::{Camera, cuts, edge_distance, newell, section};
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
pub use build::{extrude, plane};
+9
View File
@@ -705,6 +705,13 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio
Ok(b.finish())
}
#[cfg(test)]
thread_local! {
/// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for
/// the tests.
pub(crate) static PLANES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Rotate: the flat art turned in 3D about the centre of `bounds` (which may be larger than the
/// shape's own, so that every part of one object turns about the same point).
pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<Vec<Facet>, String> {
@@ -713,6 +720,8 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul
/// [`plane`], keeping its facet, its face before projection, or both, as `keep` asks.
pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: View, keep: Keep) -> Result<Built, String> {
#[cfg(test)]
PLANES.with(|n| n.set(n.get() + 1));
check_bounds(bounds)?;
let rings = solid_rings_traced(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS, CURVE_PIECES)?;
let camera = Camera::new(view, bounds, 0.0);
+9 -6
View File
@@ -505,8 +505,8 @@ fn collect_members<'a>(n: &'a Node, builder: bool, out: &mut Vec<&'a Node>) {
NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => {}
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push(n),
NodeKind::Group { .. } if builder && is_live_paint(n) => {
out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || !f.appearance.fill_paint().is_none()).map(|f| &**f));
out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || !e.appearance.stroke_paint().is_none()).map(|e| &**e));
out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || (f.opacity > 0.0 && f.appearance.has_drawn_fill())).map(|f| &**f));
out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || (e.opacity > 0.0 && e.appearance.has_drawn_stroke())).map(|e| &**e));
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
for c in children {
@@ -587,9 +587,12 @@ fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], builder: bool) -> (Vec<po:
/// Shape Builder inputs: [`shapes_for`], with the open subpaths of filled paths closed where that
/// encloses an area (the fill bounds a region, as if an invisible edge closed it) when
/// `open_filled_as_closed`. Unfilled open paths and straight lines stay open and cut the regions
/// they cross, and so do filled open paths without `open_filled_as_closed`. A Live Paint group
/// contributes its filled faces as shapes and its stroked edges as open lines; its unfilled faces
/// and its edges without a stroke are left out. Locked objects, and objects in a locked group or
/// they cross, and so do filled open paths without `open_filled_as_closed`. A path, face or edge
/// counts as filled or stroked when any of its fill or stroke rows draws
/// ([`vectorcraft_doc::Appearance::has_drawn_fill`], [`vectorcraft_doc::Appearance::has_drawn_stroke`]),
/// whichever row is on top. A Live Paint group contributes its filled faces as shapes and its
/// stroked edges as open lines; its unfilled faces, its edges without a stroke, and its faces and
/// edges whose own opacity is 0 are left out. Locked objects, and objects in a locked group or
/// layer, give nothing.
pub fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId], open_filled_as_closed: bool) -> (Vec<po::Shape>, Vec<&'a Node>) {
let (mut shapes, leaves) = shapes_of(doc, roots, true);
@@ -600,7 +603,7 @@ pub fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId], open_filled
s.path.subpaths = s.path.subpaths.iter().flat_map(|sp| sp.cut_at(&start)).collect();
continue;
}
if !open_filled_as_closed || l.appearance.fill_paint().is_none() {
if !open_filled_as_closed || !l.appearance.has_drawn_fill() {
continue;
}
for sp in s.path.subpaths.iter_mut().filter(|sp| !sp.closed) {

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