Merge main into fix/hi-missing-message-rows

This commit is contained in:
dotCooCoo
2026-11-14 15:03:53 -08:00
142 changed files with 6964 additions and 706 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"
+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();
+16
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")]
+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)]
+167 -21
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>>);
@@ -1582,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;
@@ -1598,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;
}
@@ -1619,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.
@@ -1760,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
+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);
+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 }))
+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`.
+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
+1 -1
View File
@@ -48,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,
};
+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();
+183 -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() {
+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.
@@ -474,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();
+21 -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| {
@@ -660,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());
}
@@ -676,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)));
@@ -707,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
+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;
+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;
+121 -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
+113
View File
@@ -10194,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() {
+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, .. } => {
+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:?}");
}
}
}
+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()
}
+43 -2
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))
}
+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`]).
+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"));
}
}
+46 -14
View File
@@ -244,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);
@@ -293,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
@@ -399,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,
@@ -469,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();
@@ -519,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) {
@@ -547,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;
+143
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]
+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) {
+3 -2
View File
@@ -364,7 +364,8 @@ impl BuilderMap {
}
/// What a merge needs of each input besides the map: its outline as drawn ([`node_outline`]) and
/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill).
/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill row
/// that draws).
#[derive(Clone, Debug, PartialEq)]
pub struct MergeInput {
pub outline: Option<PathData>,
@@ -375,7 +376,7 @@ pub struct MergeInput {
pub fn merge_inputs(leaves: &[&Node], open_filled_as_closed: bool) -> Vec<MergeInput> {
leaves
.iter()
.map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && !l.appearance.fill_paint().is_none() })
.map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && l.appearance.has_drawn_fill() })
.collect()
}
+2
View File
@@ -329,6 +329,8 @@ pub struct ToolContext<'a> {
pub screen: Option<ScreenFrame>,
/// Where the Plane Switching Widget sits (Perspective Grid Options); None while it's hidden.
pub plane_widget: Option<distort::perspective::widget::WidgetCorner>,
/// What Automatic Plane Positioning takes a point from (Perspective Grid Options).
pub plane_targets: distort::perspective::widget::PlaneTargets,
/// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are
/// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline.
pub precise_cursors: bool,
+44 -20
View File
@@ -26,6 +26,7 @@ use crate::bbox::{Handle as BoxHandle, scale_for_drag};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
pub mod define;
pub mod infer;
pub mod view;
pub mod widget;
pub use define::{GridDefinition, Rgb, Station};
@@ -183,6 +184,11 @@ pub struct PerspectiveGrid {
/// Horizontal extent of the right plane (points, plane units); None: `extent`, as the left.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extent_right: Option<f64>,
/// Automatic Plane Positioning: the point (x, y and z in the grid's frame, points, as
/// [`Axis`] names them) the active plane passes through for now, while the other planes hide
/// ([`infer`]). View state.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inferred: Option<[f64; 3]>,
}
impl PerspectiveGrid {
@@ -224,11 +230,18 @@ impl PerspectiveGrid {
snap: true,
rulers: false,
extent_right: None,
inferred: None,
}
}
/// Where `plane` is along its normal (points; 0: its place in the grid's definition).
/// Where `plane` is along its normal (points; 0: its place in the grid's definition): for the
/// active plane held by Automatic Plane Positioning, where that holds it.
pub fn offset(&self, plane: Plane) -> f64 {
self.inferred_offset(plane).unwrap_or_else(|| self.placed_offset(plane))
}
/// Where `plane` was moved along its normal, Automatic Plane Positioning aside.
pub fn placed_offset(&self, plane: Plane) -> f64 {
match plane {
Plane::Left => self.left_offset,
Plane::Right => self.right_offset,
@@ -325,7 +338,8 @@ impl PerspectiveGrid {
let mut v = serde_json::to_value(self).map_err(|e| e.to_string())?;
if let (Some(o), Some(p)) = (v.as_object_mut(), patch.as_object()) {
for (k, val) in p {
if k == "ids" || k == "attached" {
// Automatic Plane Positioning's point is `perspective.plane.infer`'s to set.
if k == "ids" || k == "attached" || k == "inferred" {
continue;
}
o.insert(k.clone(), val.clone());
@@ -333,6 +347,7 @@ impl PerspectiveGrid {
}
let mut g: Self = serde_json::from_value(v).map_err(|e| e.to_string())?;
g.reconcile(self, patch);
g.keep_positioning_valid();
g.validate()?;
Ok(g)
}
@@ -354,7 +369,7 @@ impl PerspectiveGrid {
self.extent,
self.height,
];
if nums.iter().any(|v| !v.is_finite() || v.abs() > 4.0e6) {
if nums.iter().chain(self.inferred.iter().flatten()).any(|v| !v.is_finite() || v.abs() > 4.0e6) {
return Err("grid values must be finite".into());
}
if self.distance <= 0.0 || self.cell <= 0.0 || self.extent <= 0.0 || self.height <= 0.0 {
@@ -563,10 +578,31 @@ impl PerspectiveGrid {
let Some(h) = self.homography(plane) else { return vec![] };
let d = self.domain(plane);
let mut out = vec![];
let (w, h_len) = (d.width(), d.height());
let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { return out };
for i in 0..=nu {
let u = i as f64 * su;
if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) {
out.push((a, b));
}
}
for i in 0..=nv {
let v = i as f64 * sv;
if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) {
out.push((a, b));
}
}
out
}
/// How the gridlines of `plane` are spaced as drawn: (step, the number of the last line) along
/// its u and its v axis. `None` for a grid without lines.
pub(crate) fn line_steps(&self, plane: Plane) -> Option<((f64, usize), (f64, usize))> {
let d = self.domain(plane);
// A stored grid is not checked: no spacing, or an extent that isn't a number, has no lines.
let (w, h_len) = (d.width(), d.height());
if !(self.cell.is_finite() && self.cell > 0.0 && w.is_finite() && h_len.is_finite()) {
return out;
return None;
}
let step = |len: f64| {
let mut s = self.cell;
@@ -580,19 +616,7 @@ impl PerspectiveGrid {
// tolerance can inflate the count when the whole domain is far smaller than it, so the
// bound is capped on its own, before any loop runs.
let count = |len: f64, s: f64| ((len + 1e-9) / s).floor().clamp(0.0, 120.0) as usize;
for i in 0..=count(w, su) {
let u = i as f64 * su;
if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) {
out.push((a, b));
}
}
for i in 0..=count(h_len, sv) {
let v = i as f64 * sv;
if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) {
out.push((a, b));
}
}
out
Some(((su, count(w, su)), (sv, count(h_len, sv))))
}
/// Plane Switching widget geometry in the first artboard's top-left corner (headless): (plane,
@@ -611,10 +635,10 @@ impl PerspectiveGrid {
}
/// The left, right and horizontal plane widgets: where each sits (on its plane: the middle of a
/// wall's ground edge, the middle of the horizontal plane).
/// wall's ground edge, the middle of the horizontal plane). A hidden plane has none.
pub fn plane_widgets(&self) -> Vec<(Plane, Point)> {
let e = self.extent / 2.0;
Plane::ALL
self.shown_planes()
.into_iter()
.filter_map(|pl| {
let q = if pl == Plane::Ground { Point::new(e, e) } else { Point::new(e, 0.0) };
@@ -793,7 +817,7 @@ pub fn grid_overlays_in(doc: &Document, tol: f64, place: Option<widget::WidgetPl
return vec![];
}
let mut out = vec![];
for pl in g.planes() {
for pl in g.shown_planes() {
let (line, color) = (g.line_color(pl), g.plane_color(pl));
for (a, b) in g.lines(pl) {
out.push(Overlay::GridLine { a, b, color: line });
@@ -385,6 +385,7 @@ impl PerspectiveGrid {
let x = g.station().x;
g.vp_vertical = [x + def.third_vp[0] * r, g.horizon - def.third_vp[1] * r];
}
g.keep_positioning_valid();
g.validate()?;
Ok(g)
}
@@ -0,0 +1,351 @@
//! Automatic Plane Positioning (Perspective Grid Options): the active plane takes its height or
//! depth from an anchor point of art in perspective, or from a gridline intersection. With the
//! Perspective Selection tool, Shift held over one, with no button down, moves the active plane
//! through that point for now and hides the other planes ([`PerspectiveGrid::inferred`]). Making
//! another plane the active one brings that plane through the same point. The plane goes back to
//! its place once an object is drawn on it or attached to it.
//!
//! The point is kept in the grid's frame: x, y and z in points along [`Axis::X`], [`Axis::Y`] and
//! [`Axis::Z`] from the origin, so a plane through it lies at the point's coordinate along the
//! plane's normal.
use serde_json::json;
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_geom::Point;
use super::widget::PlaneTargets;
use super::{Axis, DOC_KEY, PerspectiveGrid, Plane, attachment};
use crate::{Action, ToolContext};
/// The pointer is over an anchor point or a gridline intersection within this many screen pixels.
pub const HIT_PX: f64 = 6.0;
/// What Automatic Plane Positioning took its point from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InferSource {
Anchor,
Gridline,
}
impl InferSource {
pub fn id(self) -> &'static str {
match self {
Self::Anchor => "anchor",
Self::Gridline => "gridline",
}
}
}
impl Axis {
/// Where the axis' coordinate is in a point of the grid's frame.
fn index(self) -> usize {
match self {
Self::X => 0,
Self::Y => 1,
Self::Z => 2,
}
}
}
/// Call `f` with each shown object in perspective that isn't inside another one, its plane and
/// its depth: its own record, else the one grid `g` stored before attachments were kept on the
/// objects ([`PerspectiveGrid::attachment_of`]).
fn each_attached<'a>(g: &PerspectiveGrid, n: &'a Node, f: &mut dyn FnMut(&'a Node, Plane, f64)) {
if !n.visible {
return;
}
match attachment(n).or_else(|| g.attached_plane(n.id).map(|p| (p, 0.0))) {
Some((pl, depth)) => f(n, pl, depth),
None => n.children().into_iter().flatten().for_each(|c| each_attached(g, c, f)),
}
}
/// Call `f` with `n` and each node inside it, leaving out hidden nodes and what they hold.
fn each_shown<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) {
if !n.visible {
return;
}
f(n);
n.children().into_iter().flatten().for_each(|c| each_shown(c, f));
}
impl PerspectiveGrid {
/// Where Automatic Plane Positioning holds `plane`: the active plane only.
pub(super) fn inferred_offset(&self, plane: Plane) -> Option<f64> {
let p = self.inferred?;
if plane != self.plane {
return None;
}
let [.., n] = self.axes(plane)?;
Some(p[n.index()])
}
/// The planes that show: all three, or only the active one while Automatic Plane Positioning
/// holds it.
pub fn shown_planes(&self) -> Vec<Plane> {
match self.inferred {
Some(_) if self.plane != Plane::None => vec![self.plane],
_ => Plane::ALL.to_vec(),
}
}
/// The point of the grid's frame at plane coordinates `q` on `plane` at `depth`.
fn frame_point(&self, plane: Plane, depth: f64, q: Point) -> Option<[f64; 3]> {
let [u, v, n] = self.axes(plane)?;
let mut out = [0.0; 3];
out[u.index()] = q.x;
out[v.index()] = q.y;
out[n.index()] = depth;
Some(out)
}
/// The anchor point of shown art in perspective nearest `p` within `tol`: (distance, frame point).
fn anchor_near(&self, doc: &Document, p: Point, tol: f64) -> Option<(f64, [f64; 3])> {
let mut best: Option<(f64, [f64; 3])> = None;
let mut visit = |n: &Node, plane: Plane, depth: f64| {
// The plane's inverse map, worked out only once an anchor is within reach.
let mut hi = None;
each_shown(n, &mut |c| {
let NodeKind::Path { path, .. } = &c.kind else { return };
for a in path.subpaths.iter().flat_map(|sp| sp.anchors.iter()) {
let d = a.p.distance(p);
if !(d <= tol && best.is_none_or(|b| d < b.0)) {
continue;
}
let inv = hi.get_or_insert_with(|| self.homography_at(plane, depth).and_then(|h| h.inverse()));
if let Some(at) = inv.as_ref().and_then(|m| m.apply(a.p)).and_then(|q| self.frame_point(plane, depth, q)) {
best = Some((d, at));
}
}
});
};
for l in &doc.layers {
each_attached(self, l, &mut visit);
}
best
}
/// The gridline intersection of a shown plane nearest `p` within `tol`: (distance, frame point).
fn intersection_near(&self, p: Point, tol: f64) -> Option<(f64, [f64; 3])> {
let mut best: Option<(f64, [f64; 3])> = None;
for plane in self.shown_planes() {
let depth = self.offset(plane);
let Some(h) = self.homography_at(plane, depth) else { continue };
let Some(q) = h.inverse().and_then(|hi| hi.apply(p)) else { continue };
let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { continue };
// The drawn lines nearest the pointer along each axis, and their neighbors: the
// projection skews and shrinks the cells, so the intersection nearest on the page can be
// one over from the nearest in the plane.
let near = |v: f64, step: f64, last: usize| {
let i = (v / step).round().clamp(0.0, last as f64) as i64;
(i - 2..=i + 2).filter(move |k| (0..=last as i64).contains(k)).map(move |k| k as f64 * step)
};
for (u, v) in near(q.x, su, nu).flat_map(|u| near(q.y, sv, nv).map(move |v| (u, v))) {
let q = Point::new(u, v);
let Some(d) = h.apply(q).map(|at| at.distance(p)) else { continue };
if d <= tol
&& best.is_none_or(|b| d < b.0)
&& let Some(at) = self.frame_point(plane, depth, q)
{
best = Some((d, at));
}
}
}
best
}
/// What Automatic Plane Positioning finds within `tol` of page point `p`: the nearest anchor
/// point of shown art in perspective, else the nearest gridline intersection of a shown plane,
/// as a point of the grid's frame. `None` while the grid is hidden or has no active plane.
pub fn infer_at(&self, doc: &Document, p: Point, tol: f64, targets: PlaneTargets) -> Option<(InferSource, [f64; 3])> {
if !self.visible || self.plane == Plane::None || !(tol.is_finite() && p.x.is_finite() && p.y.is_finite()) {
return None;
}
let anchor = if targets.anchors { self.anchor_near(doc, p, tol) } else { None };
let found = match anchor {
Some((_, at)) => Some((InferSource::Anchor, at)),
None if targets.gridlines => self.intersection_near(p, tol).map(|(_, at)| (InferSource::Gridline, at)),
None => None,
};
found.filter(|(_, at)| at.iter().all(|v| v.is_finite()))
}
/// Put a plane that Automatic Plane Positioning holds in the grid stored in `doc` back in its
/// place. Returns whether one was held.
pub fn end_positioning(doc: &mut Document) -> bool {
if !Self::positioning(doc) {
return false;
}
doc.unknown.get_mut(DOC_KEY).and_then(|v| v.as_object_mut()).is_some_and(|o| o.remove("inferred").is_some())
}
/// Drop the point Automatic Plane Positioning holds when the grid no longer shows, has no
/// active plane, or would put the active plane behind the viewer through it.
pub fn keep_positioning_valid(&mut self) {
if self.inferred.is_some() && (!self.visible || self.plane == Plane::None || self.validate().is_err()) {
self.inferred = None;
}
}
/// Whether Automatic Plane Positioning holds a plane of the grid stored in `doc`.
pub fn positioning(doc: &Document) -> bool {
doc.unknown.get(DOC_KEY).and_then(|v| v.get("inferred")).is_some_and(|v| !v.is_null())
}
}
/// The Perspective Selection tool's step for Shift held over `p` with no button down: the command
/// that moves the active plane through the anchor point or gridline intersection there, unless
/// the plane is held through that point already.
pub(super) fn hover_action(cx: &ToolContext, g: &PerspectiveGrid, p: Point) -> Option<Action> {
let tol = cx.tol(HIT_PX);
let (_, at) = g.infer_at(cx.doc, p, tol, cx.plane_targets)?;
if g.inferred.is_some_and(|held| held.iter().zip(&at).all(|(a, b)| (a - b).abs() <= 1e-9)) {
return None;
}
Some(Action::Exec("perspective.plane.infer".into(), json!({"at": [p.x, p.y], "tolerance": tol})))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::*;
use crate::{Mods, PointerEvent, PointerKind, Tool, ToolKey};
use vectorcraft_doc::Selection;
use vectorcraft_geom::Rect;
fn grid() -> PerspectiveGrid {
PerspectiveGrid::preset(2, Rect::new(0.0, 0.0, 800.0, 600.0))
}
#[test]
fn a_gridline_intersection_gives_the_frame_point_the_planes_pass_through() {
let mut g = grid();
let (d, cell) = (Document::new(800.0, 600.0), g.cell);
// Three cells along and two up the left wall (two-point: u recedes along Z, v is Y).
let p = g.to_page(Plane::Left, Point::new(3.0 * cell, 2.0 * cell)).unwrap();
let (source, at) = g.infer_at(&d, p, 1.0, PlaneTargets::ALL).unwrap();
assert_eq!(source, InferSource::Gridline);
for (got, want) in at.iter().zip([0.0, 2.0 * cell, 3.0 * cell]) {
assert!((got - want).abs() < 1e-6, "{at:?}");
}
// Held, the active plane lies at the point's coordinate along its normal, the other planes
// hide, and their own places stay.
g.inferred = Some(at);
g.plane = Plane::Ground;
assert!((g.offset(Plane::Ground) - 2.0 * cell).abs() < 1e-6);
assert_eq!((g.placed_offset(Plane::Ground), g.offset(Plane::Left)), (0.0, 0.0));
assert_eq!(g.shown_planes(), vec![Plane::Ground]);
assert_eq!(g.plane_widgets().len(), 1);
// The plane drawn there passes through the point the pointer was over.
let back = g.to_page(Plane::Ground, Point::new(0.0, 3.0 * cell)).unwrap();
assert!((back - p).hypot() < 1e-6, "{back:?} {p:?}");
// Another plane made active passes through it too.
g.plane = Plane::Right;
assert!((g.offset(Plane::Right) - 3.0 * cell).abs() < 1e-6);
assert_eq!(g.offset(Plane::Ground), 0.0);
// With no active plane nothing is held.
g.plane = Plane::None;
assert_eq!(g.shown_planes(), Plane::ALL.to_vec());
}
#[test]
fn the_pointer_must_be_within_reach_of_a_target_that_is_on() {
// Only the right wall shows, in its own place: the other planes' lines are out of the way.
let g = PerspectiveGrid { plane: Plane::Right, inferred: Some([0.0; 3]), ..grid() };
let (d, cell) = (Document::new(800.0, 600.0), g.cell);
let on = g.to_page(Plane::Right, Point::new(2.0 * cell, cell)).unwrap();
let mid = g.to_page(Plane::Right, Point::new(2.5 * cell, 1.5 * cell)).unwrap();
assert!(g.infer_at(&d, on + vectorcraft_geom::Vec2::new(2.0, 0.0), 3.0, PlaneTargets::ALL).is_some());
assert!(g.infer_at(&d, mid, 3.0, PlaneTargets::ALL).is_none(), "the middle of a cell is no intersection");
assert!(g.infer_at(&d, on, 3.0, PlaneTargets { anchors: true, gridlines: false }).is_none());
assert!(g.infer_at(&d, on, f64::NAN, PlaneTargets::ALL).is_none());
assert!(g.infer_at(&d, Point::new(f64::INFINITY, 0.0), 3.0, PlaneTargets::ALL).is_none());
// Hidden, or without an active plane, the grid gives no point.
assert!(PerspectiveGrid { visible: false, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none());
assert!(PerspectiveGrid { plane: Plane::None, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none());
// Beyond the plane's last line there is no intersection.
let past = g.to_page(Plane::Right, Point::new(g.right_extent() + 5.0 * cell, cell)).unwrap();
assert!(g.infer_at(&d, past, 3.0, PlaneTargets::ALL).is_none());
}
#[test]
fn a_hidden_path_inside_art_in_perspective_has_no_anchor_to_take() {
let g = PerspectiveGrid { plane: Plane::Right, ..grid() };
let mut d = Document::new(800.0, 600.0);
g.store(&mut d);
// A group on the right wall holding one small square, a corner in the middle of a cell.
let at = g.to_page(Plane::Right, Point::new(2.5 * g.cell, 1.5 * g.cell)).unwrap();
let (layer, group, square) = (d.layers[0].id, d.alloc_id(), d.alloc_id());
let mut path = Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default());
path.visible = false;
let mut art = Node::group(group, vec![std::sync::Arc::new(path)]);
super::super::set_attachment(&mut art, Plane::Right, 0.0);
d.insert(Some(layer), 0, art).unwrap();
let anchors = PlaneTargets { anchors: true, gridlines: false };
assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "the square is hidden");
d.node_mut(square).unwrap().visible = true;
let (source, point) = g.infer_at(&d, at, 0.5, anchors).unwrap();
assert_eq!(source, InferSource::Anchor);
for (got, want) in point.iter().zip([2.5 * g.cell, 1.5 * g.cell, 0.0]) {
assert!((got - want).abs() < 1e-6, "{point:?}");
}
// A grid stored before attachments were kept on the objects lists them itself.
let mut d = Document::new(800.0, 600.0);
let (layer, square) = (d.layers[0].id, d.alloc_id());
d.insert(
Some(layer),
0,
Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default()),
)
.unwrap();
assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "not in perspective");
let mut legacy = g.clone();
legacy.attached.insert(square.0.to_string(), Plane::Right);
assert_eq!(legacy.infer_at(&d, at, 0.5, anchors).map(|f| f.0), Some(InferSource::Anchor));
}
#[test]
fn the_stored_point_ends_with_end_positioning() {
let mut d = Document::new(800.0, 600.0);
let mut g = grid();
g.store(&mut d);
assert!(!PerspectiveGrid::positioning(&d));
assert!(!PerspectiveGrid::end_positioning(&mut d));
g.inferred = Some([1.0, 2.0, 3.0]);
g.store(&mut d);
assert!(PerspectiveGrid::positioning(&d));
assert_eq!(PerspectiveGrid::current(&d).inferred, Some([1.0, 2.0, 3.0]));
// `perspective.grid.set` leaves the point as it is.
assert_eq!(g.merged(&json!({"inferred": [9, 9, 9], "cell": 25})).unwrap().inferred, Some([1.0, 2.0, 3.0]));
assert!(PerspectiveGrid { inferred: Some([f64::NAN, 0.0, 0.0]), ..g.clone() }.validate().is_err());
assert!(PerspectiveGrid::end_positioning(&mut d));
assert_eq!(PerspectiveGrid::current(&d), PerspectiveGrid { inferred: None, ..g });
}
#[test]
fn shift_over_an_intersection_asks_for_the_plane_once() {
let mut d = Document::new(800.0, 600.0);
let mut g = grid();
g.store(&mut d);
let (s, p) = (Selection::default(), paint());
let at = g.to_page(Plane::Left, Point::new(2.0 * g.cell, 3.0 * g.cell)).unwrap();
let shift = Mods { shift: true, ..Default::default() };
let hover = |d: &Document, mods: Mods| {
let c = cx(d, &s, &p);
let mut t = super::super::PerspectiveSelectionTool::default();
t.pointer(&c, &PointerEvent { mods, ..PointerEvent::new(PointerKind::Move, at.x, at.y) })
};
assert!(hover(&d, Mods::default()).is_empty(), "without Shift the pointer only hovers");
let acts = hover(&d, shift);
let [Action::Exec(cmd, v)] = acts.as_slice() else { panic!("{acts:?}") };
assert_eq!((cmd.as_str(), &v["at"]), ("perspective.plane.infer", &json!([at.x, at.y])));
// Held through that point already, the hover asks for nothing more.
g.inferred = g.infer_at(&d, at, 1.0, PlaneTargets::ALL).map(|f| f.1);
g.store(&mut d);
assert!(hover(&d, shift).is_empty());
// Escape puts the plane back.
let c = cx(&d, &s, &p);
let mut t = super::super::PerspectiveSelectionTool::default();
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))]);
}
}
@@ -289,6 +289,9 @@ impl Tool for PerspectiveSelectionTool {
_ => vec![],
}
}
// Automatic Plane Positioning: Shift held over an anchor point of art in perspective or
// over a gridline intersection, with no button down. During a drag Shift constrains.
(PointerKind::Move, SelDrag::Idle) if m.shift => super::infer::hover_action(cx, &g, p).into_iter().collect(),
(_, d) => {
self.drag = d;
vec![]
@@ -296,7 +299,8 @@ impl Tool for PerspectiveSelectionTool {
}
}
/// Escape during a move, a resize or a plane widget drag cancels it: the objects and the plane
/// go back to the start of the drag.
/// go back to the start of the drag. With no drag, Escape puts a plane that Automatic Plane
/// Positioning holds back in its place.
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape && self.busy() {
self.measure = None;
@@ -305,6 +309,9 @@ impl Tool for PerspectiveSelectionTool {
_ => vec![Action::Cancel],
};
}
if key == ToolKey::Escape && PerspectiveGrid::current(cx.doc).inferred.is_some() {
return vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))];
}
if let (ToolKey::Digit(5), SelDrag::Move { perp, began, shift, .. }) = (key, &mut self.drag) {
*perp = !*perp;
*shift = mods.shift;
+29 -2
View File
@@ -50,17 +50,44 @@ impl WidgetCorner {
}
}
/// Perspective Grid Options: whether the Plane Switching Widget shows, and where.
/// Perspective Grid Options: whether the Plane Switching Widget shows, and where, and what
/// Automatic Plane Positioning takes a point from ([`super::infer`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct WidgetOptions {
pub show: bool,
pub position: WidgetCorner,
/// Automatic Plane Positioning › Anchor Point of Perspective Artwork.
pub anchor_point: bool,
/// Automatic Plane Positioning › Intersection of Gridlines.
pub gridline_intersection: bool,
}
impl Default for WidgetOptions {
fn default() -> Self {
Self { show: true, position: WidgetCorner::TopLeft }
Self { show: true, position: WidgetCorner::TopLeft, anchor_point: true, gridline_intersection: true }
}
}
impl WidgetOptions {
/// What Automatic Plane Positioning takes a point from.
pub fn targets(self) -> PlaneTargets {
PlaneTargets { anchors: self.anchor_point, gridlines: self.gridline_intersection }
}
}
/// What Automatic Plane Positioning takes a point from: the anchor points of art in perspective,
/// the gridline intersections of the planes that show.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlaneTargets {
pub anchors: bool,
pub gridlines: bool,
}
impl PlaneTargets {
pub const ALL: Self = Self { anchors: true, gridlines: true };
pub fn any(self) -> bool {
self.anchors || self.gridlines
}
}
+26 -27
View File
@@ -6,9 +6,9 @@
//! points with straight segments and the release fits them; Alt on release (or ending near the start) closes the path, and starting
//! near an end of a selected open path continues it. Shift held at the press draws a straight
//! Pencil line at 45° steps from the Constrain Angle instead, and Alt held at the press (with Alt
//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil's new path starts and ends on
//! Smart Guides ([`DrawSnap`]: an anchor, a path, in line with the art), hovering too; the points
//! between follow the hand. The Paintbrush records the pen pressure of each point (a stroke a pen
//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil ignores Smart
//! Guides and Snap to Point: it shows no Smart Guides, hovering or drawing, and its ends follow the
//! hand. Snap to Grid and Snap to Pixel still move its ends (`grid_snaps`). The Paintbrush records the pen pressure of each point (a stroke a pen
//! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and
//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY,
//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob
@@ -860,27 +860,29 @@ impl GestureTool {
}
}
/// Do the ends of its strokes snap (the Pencil)?
fn snaps(&self) -> bool {
self.id == "pencil"
}
/// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to
/// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the
/// Pencil's straight line's do: the press, and the release unless Shift keeps it on a 45° step.
/// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap: the press,
/// and the release unless Shift keeps it on a 45° step.
fn knife_snaps(&self, cx: &ToolContext) -> bool {
self.id == "knife" && self.straight && cx.smart_guides && !cx.snaps_to_pixel(crate::PixelOp::Drawing) && !cx.snap_to_grid
}
/// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's
/// without Shift?
/// Do the Pencil's ends snap? Only to the grid or to pixels, with View → Snap to Grid or Snap
/// to Pixel on: those are separate from Smart Guides (and turn them off), and the grid case is
/// its own question (#2958). Smart Guides and Snap to Point never move them.
fn grid_snaps(&self, cx: &ToolContext) -> bool {
self.id == "pencil" && (cx.snap_to_grid || cx.snaps_to_pixel(crate::PixelOp::Drawing))
}
/// Does the end of a straight line without Shift snap: the Pencil's Alt line's to the grid or
/// pixels, a straight Knife cut's to anchors and paths?
fn line_end_snaps(&self, cx: &ToolContext) -> bool {
self.straight && self.unconstrained && (self.snaps() || self.knife_snaps(cx))
self.straight && self.unconstrained && (self.grid_snaps(cx) || self.knife_snaps(cx))
}
/// Where a stroke or straight line released at `p` ends: where it snaps when its end snaps.
fn release_end(&mut self, cx: &ToolContext, p: Point) -> Point {
if (self.snaps() && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p }
if (self.grid_snaps(cx) && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p }
}
/// Is a straight line with its end at `end` back at its press point (within a pixel), so that
@@ -1299,10 +1301,6 @@ impl Tool for GestureTool {
self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p);
}
match ev.kind {
PointerKind::Move if self.snaps() => {
self.snap.hover(cx, p, &[], None);
vec![]
}
PointerKind::Down => {
self.active = true;
self.began = false;
@@ -1326,11 +1324,12 @@ impl Tool for GestureTool {
_ => vec![],
};
self.redraw = if self.draws_path() && !self.smoothing && self.extend.is_none() { self.find_redraw(cx, p) } else { None };
// A path continued starts at its end, one redrawn on it; a new one where it snaps.
// A straight line is constrained from the end it continues, so it starts there.
// A path continued starts at its end, one redrawn on it; a new one at the press,
// or on the grid or a pixel when they snap. A straight line is constrained from the
// end it continues, so it starts there.
let start = if let Some((_, _, end)) = extend.filter(|_| self.straight) {
end
} else if self.snaps() && !self.smoothing && self.extend.is_none() && self.redraw.is_none() {
} else if self.grid_snaps(cx) && !self.smoothing && self.extend.is_none() && self.redraw.is_none() {
self.snap.press(cx, p, &[], None)
} else if self.knife_snaps(cx) {
// A straight Knife cut, its overlay and Shift's 45° steps start from the snapped point.
@@ -1354,13 +1353,13 @@ impl Tool for GestureTool {
self.moved |= self.points.first().is_some_and(|start| p.distance(*start) > vectorcraft_geom::EPS);
let p = self.constrained(cx, p, ev.mods);
let mut end = p;
if self.snaps() && !self.smoothing && !self.straight {
// Where the stroke would end: shown, taken on release.
if self.grid_snaps(cx) && !self.smoothing && !self.straight {
// Where the stroke would end on the grid or a pixel: taken on release.
end = self.snap.drag(cx, p, None);
}
let p = if self.line_end_snaps(cx) {
// Alt's line ends where a stroke would, and a Knife cut's on the anchors and
// paths its press snaps to: shown, taken on release.
// Alt's line ends on the grid or a pixel when they snap, and a Knife cut on the
// anchors and paths its press snaps to: shown, taken on release.
self.snap.drag(cx, p, None)
} else {
p
@@ -1382,7 +1381,7 @@ impl Tool for GestureTool {
} else if self.points.last().is_some_and(|l| l.distance(p) < cx.tol(1.0)) || self.points.len() >= crate::MAX_STROKE_SAMPLES {
// A release here keeps the last point unless it snaps (`Up`), so the ring
// follows the point `finish` will test.
let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.snaps());
let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.grid_snaps(cx));
let release_end = kept.unwrap_or(end);
self.near_start = self.release_closes_near_start(cx, release_end);
self.connects = self.connects_at(cx, release_end).is_some();
@@ -1439,7 +1438,7 @@ impl Tool for GestureTool {
}
} else if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) {
self.push(end, ev);
} else if self.snaps()
} else if self.grid_snaps(cx)
&& !self.smoothing
&& self.points.len() > 1
&& let Some(last) = self.points.last_mut()
+60 -17
View File
@@ -22,25 +22,67 @@ fn drag_held(t: &mut GestureTool, cx: &ToolContext, pts: &[(f64, f64)], m: Mods)
v
}
/// The Pencil's new path starts and ends on Smart Guides (#506), the points between where
/// the hand went.
/// The Pencil follows the hand from the press to the release: it ignores Smart Guides and Snap to Point and shows no
/// Smart Guides, hovering or drawing over the art, with Smart Guides on or with only Snap to Point.
#[test]
fn pencil_ends_snap_to_smart_guides() {
fn pencil_follows_the_hand_and_shows_no_smart_guides() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = GestureTool::new("pencil");
let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (250.0, 320.0), (198.0, 203.0)], Mods::default());
let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[100.0, 100.0], [151.0, 300.0], [250.0, 320.0], [200.0, 200.0]]));
let on = cx(&d, &s, &p);
let snap_to_point = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
// Near the corners at (100, 100) and (200, 200), within Snap to Point's 2 px of them.
let hand = [(101.0, 99.0), (151.0, 300.0), (250.0, 320.0), (199.0, 201.0)];
for cx in [&on, &snap_to_point] {
let mut t = GestureTool::new("pencil");
t.pointer(cx, &PointerEvent::new(PointerKind::Move, hand[0].0, hand[0].1));
assert!(t.overlays(cx).is_empty(), "hovering: {:?}", t.overlays(cx));
t.pointer(cx, &PointerEvent::new(PointerKind::Down, hand[0].0, hand[0].1));
for &(x, y) in &hand[1..] {
t.pointer(cx, &PointerEvent::new(PointerKind::Drag, x, y));
assert!(t.snap.guides().is_empty(), "drawing: {:?}", t.snap.guides());
}
let last = hand[hand.len() - 1];
let acts = t.pointer(cx, &PointerEvent::new(PointerKind::Up, last.0, last.1));
let Some(Action::Preview(_, v)) = acts.first() else { panic!("{acts:?}") };
assert_eq!(v["points"], json!(hand.map(|(x, y)| [x, y])));
}
// The Paintbrush follows the hand all the way.
let mut t = GestureTool::new("paintbrush");
let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0)], Mods::default());
let acts = drag(&mut t, &on, &[(102.0, 98.0), (151.0, 300.0)], Mods::default());
let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") };
assert_eq!(v["points"][0], json!([102.0, 98.0]));
}
/// Snap to Grid and Snap to Pixel are not Smart Guides: they still move the Pencil's ends (and an
/// Alt line's), while the points between follow the hand.
#[test]
fn pencil_ends_still_snap_to_the_grid_and_pixels() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) };
let pixel = ToolContext { snap_to_pixel: true, ..cx(&d, &s, &p) };
let on = |cx: &ToolContext, q: (f64, f64)| match cx.snap_to_grid {
true => vectorcraft_geom::snap::snap_point_to_grid(Point::new(q.0, q.1), cx.grid_step()),
false => Point::new(q.0.round(), q.1.round()),
};
let hand = [(301.3, 302.6), (351.4, 420.2), (447.7, 452.9)];
for cx in [&grid, &pixel] {
let (first, last) = (on(cx, hand[0]), on(cx, hand[2]));
assert!(first != Point::new(hand[0].0, hand[0].1) && last != Point::new(hand[2].0, hand[2].1));
let mut t = GestureTool::new("pencil");
let acts = drag(&mut t, cx, &hand, Mods::default());
let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[first.x, first.y], [351.4, 420.2], [last.x, last.y]]));
// Alt's straight line ends on the grid or a pixel too.
let mut t = GestureTool::new("pencil");
let acts = drag_held(&mut t, cx, &[hand[0], hand[2]], Mods { alt: true, ..Mods::default() });
let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") };
assert_eq!(v["points"][1], json!([last.x, last.y]));
}
}
/// #852: the Paintbrush sends each point's pen pressure; a mouse (always fully pressed) and
/// the Pencil send plain points.
#[test]
@@ -693,10 +735,10 @@ fn pencil_shift_draws_a_straight_line_at_45_degree_steps() {
}
}
/// #3799: a Shift line leaves no Smart Guides of its press on screen while it is dragged
/// (its end doesn't snap), and Alt at its release leaves it open.
/// #3799: a Shift line shows no Smart Guides, at its press or while it is dragged, and Alt at its
/// release leaves it open.
#[test]
fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() {
fn pencil_shift_line_shows_no_guides_and_stays_open_with_alt() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
@@ -704,7 +746,7 @@ fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() {
let shift = Mods { shift: true, ..Default::default() };
let mut t = GestureTool::new("pencil");
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 102.0, 98.0).with_mods(shift));
assert!(!t.overlays(&cx).is_empty(), "the press snaps to the corner and shows it");
assert!(t.snap.guides().is_empty(), "the press: {:?}", t.snap.guides());
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 140.0).with_mods(shift));
assert!(t.overlays(&cx).is_empty(), "{:?}", t.overlays(&cx));
let shift_alt = Mods { shift: true, alt: true, ..Default::default() };
@@ -1745,10 +1787,11 @@ fn paintbrush_alt_with_a_two_anchor_curve_selected_smooths() {
}
}
/// #3799: Alt's line starts and ends on Smart Guides as a stroke does, and pressed on an end of
/// a selected open path it continues the path from that end to the pointer.
/// #3799: Alt's line runs from the press to the pointer as a stroke does, snapping to nothing,
/// and pressed on an end of a selected open path it continues the path from that end to the
/// pointer.
#[test]
fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() {
fn pencil_alt_line_follows_the_hand_and_continues_a_selected_path() {
let (mut d, _) = doc_with_rect();
let alt = Mods { alt: true, ..Default::default() };
let p = paint();
@@ -1758,7 +1801,7 @@ fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() {
let mut t = GestureTool::new("pencil");
let acts = drag_held(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (198.0, 203.0)], alt);
let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[100.0, 100.0], [200.0, 200.0]]));
assert_eq!(v["points"], json!([[102.0, 98.0], [198.0, 203.0]]));
}
let l = d.layers[0].id;
let id = d.alloc_id();
+1
View File
@@ -604,6 +604,7 @@ pub(crate) mod testutil {
construction_angles: guides::construction_angles(guides::DEFAULT_CONSTRUCTION_ANGLES),
screen: None,
plane_widget: Some(Default::default()),
plane_targets: distort::perspective::widget::PlaneTargets::ALL,
precise_cursors: false,
global_edit: &[],
}
+3 -3
View File
@@ -398,7 +398,7 @@ fn settled_wide_strips(q: &Quantized, img: &Raster, own: &[bool], gray: bool, co
/// stay more than 0.065 as far as a single color does. So is a sepia, single-hue or duotone
/// picture whose tones follow one curve through the color cube (19 in 20 of its opaque pixels on
/// it, see [`on_one_curve`]). Neither is, however far eight colors stay, when sixteen colors stay
/// at most a fifth as far as eight do. That exception holds for flat art of up to sixteen clean
/// at most a tenth as far as eight do. That exception holds for flat art of up to sixteen clean
/// levels, gray or tinted, where sixteen colors come within about a level of every pixel. On gray
/// and tinted photos sixteen colors stay 0.18 to 0.57 as far as eight do, and on most anti-aliased
/// or noisy gray flat art 0.24 to 0.5 as far, so the exception holds for neither.
@@ -437,9 +437,9 @@ pub(crate) fn continuous_tone(img: &Raster) -> bool {
}
let one_line = || 20 * neutral >= 19 * opaque || 20 * on_one_curve(img) >= 19 * opaque;
if eight > 0.1 * one {
return !(unsaid(16) <= 0.2 * eight && one_line());
return !(unsaid(16) <= 0.1 * eight && one_line());
}
unsaid(16) > 0.2 * eight && one_line()
unsaid(16) > 0.1 * eight && one_line()
}
/// How far (levels) a pixel may lie from the tone curve of its picture and still count as on it,
+10
View File
@@ -2033,6 +2033,16 @@ fn a_gray_photo_is_continuous_tone_as_its_color_original_is() {
}
}
/// A gray photo with little or no noise (a render, a denoised scan) is continuous tone, as its
/// color original is. Sixteen colors stay 0.19 as far from its pixels as eight do.
#[test]
fn a_clean_gray_photo_is_continuous_tone_as_its_color_original_is() {
for noise in [0.0, 1.0, 2.0, 3.0] {
assert!(quantize::continuous_tone(&photo_scene(noise, false)), "color, noise {noise}");
assert!(quantize::continuous_tone(&photo_scene(noise, true)), "gray, noise {noise}");
}
}
/// Sepia: dark brown to cream.
const SEPIA: [[f64; 3]; 2] = [[45.0, 28.0, 15.0], [250.0, 235.0, 205.0]];
/// A single blue hue: navy to pale blue.
+60 -35
View File
@@ -41,6 +41,7 @@ use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::mpsc::Sender;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::ParamsPlace;
use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
@@ -427,17 +428,19 @@ impl Hiding {
}
/// The paths outside the read roots that `v`'s strings and keys name at any depth, written as paths
/// ([`unreadable_path_like`]) or held by a path param
/// ([`vectorcraft_engine::file_access::is_path_key`]), a relative one too, each as a hidden library id
/// (`loaded/<path>`) with `loaded/<file name>` shown. A reply hides them as it hides a hidden library's
/// path, with that file name also for a hidden library shown as `loaded/<file name> (2)`, so that it
/// reads the same whether or not a library was loaded from one of them.
/// ([`unreadable_path_like`]) or held by a path param, a relative one too, each as a hidden library id
/// (`loaded/<path>`) with `loaded/<file name>` shown. A param is a path param as the command it is
/// for reads it ([`ParamsPlace`]: `engine.execute`'s `params`, a `command.batch` step's and a
/// recorded step's), so a web link or an export's folder grouping is not one. A reply hides them as
/// it hides a hidden library's path, with that file name also for a hidden library shown as
/// `loaded/<file name> (2)`, so that it reads the same whether or not a library was loaded from one
/// of them.
fn sent_paths(v: &Value, out: &mut Vec<(String, String)>) {
collect_sent_paths(v, false, out);
collect_sent_paths(v, ParamsPlace::top(None), false, out);
}
/// [`sent_paths`] on `v`, which a path param holds when `path_param` is set.
fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String)>) {
/// [`sent_paths`] on `v`, found at `place`, which a path param holds when `path_param` is set.
fn collect_sent_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec<(String, String)>) {
fn add(s: &str, path_param: bool, out: &mut Vec<(String, String)>) {
if !unreadable_path_like(s) && !(path_param && !readable_value(s)) {
return;
@@ -459,11 +462,18 @@ fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String
}
match v {
Value::String(s) => add(s, path_param, out),
Value::Array(items) => items.iter().for_each(|item| collect_sent_paths(item, path_param, out)),
Value::Array(items) => {
let step = ParamsPlace::step(items);
for (i, item) in items.iter().enumerate() {
collect_sent_paths(item, place.item(i, step), path_param, out);
}
}
Value::Object(fields) => {
let carried = ParamsPlace::carried(fields);
for (key, item) in fields {
add(key, false, out);
collect_sent_paths(item, vectorcraft_engine::file_access::is_path_key(key), out);
let (below, location) = place.member(key, carried);
collect_sent_paths(item, below, location.is_some(), out);
}
}
_ => {}
@@ -1057,7 +1067,7 @@ fn steps_mut(set: &mut Value) -> impl Iterator<Item = (String, &mut serde_json::
/// [`leave_out_unreadable_params`] takes out, each in one pass over the params.
fn leave_out_unreadable_step(command: &str, params: &mut serde_json::Map<String, Value>) {
leave_out_unreadable_pref_steps(command, params);
leave_out_unreadable_params(params);
leave_out_unreadable_params(params, ParamsPlace::of(command));
}
/// Takes out of the params of a step running `command` the folder preferences' values the request
@@ -1087,39 +1097,46 @@ fn leave_out_unreadable_pref_steps(command: &str, params: &mut serde_json::Map<S
}
}
/// Takes out of a recorded step's params, at any depth (the commands of a `command.batch` step), the
/// paths the request may not read: the value of a path param
/// ([`vectorcraft_engine::file_access::is_path_key`]: `path`, `file`, `diffPath`, `destinationFolder`
/// and the like), each path of a list under such a param, and under any other param, as a key too, a
/// string written as a path ([`unreadable_path_like`]). An empty or blank value names no path and stays.
fn leave_out_unreadable_params(params: &mut serde_json::Map<String, Value>) {
use vectorcraft_engine::file_access::is_path_key;
/// Takes out of a recorded step's params at `place`, at any depth (the commands of a `command.batch`
/// step), the paths the request may not read: the value of a path param as the command reads it
/// ([`ParamsPlace`]: `path`, `file`, `diffPath`, `destinationFolder` and the like, but not a key that
/// names part of the document in that command), each path of a list under such a param, and under
/// any other param, as a key too, a string written as a path ([`unreadable_path_like`]). A web link,
/// a choice or a switch whose name ends like a path param's (`alignToPath`, `linksFolder`) stays, and
/// so does an empty or blank value, which names no path.
fn leave_out_unreadable_params(params: &mut serde_json::Map<String, Value>, place: ParamsPlace) {
let shown = |p: &str| p.trim().is_empty() || readable_value(p);
let carried = ParamsPlace::carried(params);
params.retain(|key, v| {
!unreadable_path_like(key)
&& match v.as_str() {
Some(p) => !unreadable_path_like(p) && !(is_path_key(key) && !shown(p)),
Some(p) => !unreadable_path_like(p) && !(place.member(key, carried).1.is_some() && !shown(p)),
None => true,
}
});
let carried = ParamsPlace::carried(params);
for (key, v) in params.iter_mut() {
let (below, location) = place.member(key, carried);
if let Value::Array(paths) = v
&& is_path_key(key)
&& location.is_some()
{
paths.retain(|p| p.as_str().is_none_or(shown));
}
leave_out_unreadable_values(v);
leave_out_unreadable_values(v, below);
}
}
/// [`leave_out_unreadable_params`] on each object `v` holds, and a string written as a path that the
/// request may not read ([`unreadable_path_like`]) taken out of each list.
fn leave_out_unreadable_values(v: &mut Value) {
/// [`leave_out_unreadable_params`] on each object `v`, found at `place`, holds, and a string written
/// as a path that the request may not read ([`unreadable_path_like`]) taken out of each list.
fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) {
match v {
Value::Object(fields) => leave_out_unreadable_params(fields),
Value::Object(fields) => leave_out_unreadable_params(fields, place),
Value::Array(items) => {
items.retain(|item| !item.as_str().is_some_and(unreadable_path_like));
items.iter_mut().for_each(leave_out_unreadable_values);
let step = ParamsPlace::step(items);
for (i, item) in items.iter_mut().enumerate() {
leave_out_unreadable_values(item, place.item(i, step));
}
}
_ => {}
}
@@ -1284,7 +1301,7 @@ fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before:
return;
}
let mut given = Vec::new();
written_paths(sent, false, &mut given);
written_paths(sent, ParamsPlace::top(None), false, &mut given);
let kept = kept_written_paths(reply, &given);
let mut hiding = unreadable_library_ids(app);
hiding.merge(before);
@@ -1294,10 +1311,10 @@ fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before:
// first folder on the way to it that is a file or is missing.
let current = vectorcraft_engine::cmd::recovery::folder(&app.session).map(|(f, _)| f);
for folder in app.recovery.named.iter().chain(current.as_ref()) {
collect_sent_paths(&json!(folder), true, &mut paths);
collect_sent_paths(&json!(folder), ParamsPlace::top(None), true, &mut paths);
for on_the_way in std::path::Path::new(folder).ancestors().skip(1).map(|p| p.to_string_lossy()) {
if !on_the_way.is_empty() && writes_whole_path(reply, &on_the_way) {
collect_sent_paths(&json!(on_the_way), true, &mut paths);
collect_sent_paths(&json!(on_the_way), ParamsPlace::top(None), true, &mut paths);
}
}
}
@@ -1326,16 +1343,24 @@ fn writes_whole_path(v: &Value, path: &str) -> bool {
}
}
/// The strings that `v`'s path params hold at any depth ([`vectorcraft_engine::file_access::is_path_key`])
/// that name a file inside the write roots; `v` is a path param's value when `path_param` is set.
fn written_paths(v: &Value, path_param: bool, out: &mut Vec<String>) {
use vectorcraft_engine::file_access::{Access, current, is_path_key};
/// The strings that `v`'s path params hold at any depth, as the command they are for reads them
/// ([`ParamsPlace`]), that name a file inside the write roots; `v`, found at `place`, is a path
/// param's value when `path_param` is set.
fn written_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec<String>) {
use vectorcraft_engine::file_access::{Access, current};
match v {
Value::String(s) if path_param && !s.is_empty() && current().is_some_and(|r| r.check(s, Access::Write).is_ok()) => out.push(s.clone()),
Value::Array(items) => items.iter().for_each(|item| written_paths(item, path_param, out)),
Value::Array(items) => {
let step = ParamsPlace::step(items);
for (i, item) in items.iter().enumerate() {
written_paths(item, place.item(i, step), path_param, out);
}
}
Value::Object(fields) => {
let carried = ParamsPlace::carried(fields);
for (key, item) in fields {
written_paths(item, is_path_key(key), out);
let (below, location) = place.member(key, carried);
written_paths(item, below, location.is_some(), out);
}
}
_ => {}
+66 -2
View File
@@ -306,7 +306,7 @@ fn a_spaced_absolute_path_outside_the_read_root_is_left_out() {
assert!(super::unreadable_path_like(" /outside/root/x"));
assert!(super::unreadable_path_like("\tfile:///outside/root/x "));
assert!(!super::unreadable_path_like(&inside), "{inside}");
super::leave_out_unreadable_params(params.as_object_mut().unwrap());
super::leave_out_unreadable_params(params.as_object_mut().unwrap(), vectorcraft_engine::cmd::ParamsPlace::top(None));
});
assert_eq!(params, json!({"keep": inside, "list": []}));
}
@@ -337,10 +337,74 @@ fn a_url_naming_another_host_stays_without_a_read_root() {
assert!(super::readable_value("file://host/share/a.svg"));
let mut params = json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]});
let fields = params.as_object_mut().unwrap();
super::leave_out_unreadable_params(fields);
super::leave_out_unreadable_params(fields, vectorcraft_engine::cmd::ParamsPlace::top(None));
assert_eq!(params, json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]}));
}
/// Under a read root, a recorded step loses a relative path outside it under a key that names a file
/// or a folder as its command reads it (also inside a `command.batch` step), and a `file:` URL outside
/// it under any key. A web link, a choice or a switch whose name ends like a path key's, and a key
/// that names part of the document in its command, keep their values; the same key in a command that
/// doesn't take it as a param names a file.
#[test]
fn recorded_steps_filter_only_unreadable_locations() {
use vectorcraft_engine::cmd::ParamsPlace;
let root = std::env::temp_dir().join(format!("vc-recorded-locations-{}", std::process::id()));
std::fs::create_dir_all(&root).unwrap();
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap();
let steps = [
("document.compare", json!({"diffPath": "elsewhere/a.svg", "directory": "elsewhere", "keep": 1})),
("attributes.set", json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"})),
("object.slice.options", json!({"url": "file:///elsewhere/a.html"})),
("object.path.simplify", json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"})),
("document.exportPresets.save", json!({"settings": {"folders": "item/format", "formats": [{"folder": "elsewhere/png"}]}})),
("text.createInPath", json!({"path": "elsewhere/shape"})),
("object.setLiveShape", json!({"path": "elsewhere/shape"})),
("command.batch", json!({"commands": [{"command": "document.save", "params": {"path": "elsewhere/b.svg"}}]})),
];
let filtered: Vec<Value> = vectorcraft_engine::file_access::confine(roots.as_ref(), || {
steps
.iter()
.map(|(id, params)| {
let mut params = params.clone();
super::leave_out_unreadable_params(params.as_object_mut().unwrap(), ParamsPlace::of(id));
params
})
.collect()
});
let _ = std::fs::remove_dir_all(root);
let want = [
json!({"keep": 1}),
json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"}),
json!({}),
json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"}),
json!({"settings": {"folders": "item/format", "formats": [{}]}}),
json!({"path": "elsewhere/shape"}),
json!({}),
json!({"commands": [{"command": "document.save", "params": {}}]}),
];
assert_eq!(filtered, want);
}
/// A request's relative path outside the read root is hidden in a reply where the command it calls
/// reads it as a file, and a web link or a key that names part of the document there is not.
#[test]
fn a_request_sends_paths_as_its_command_reads_them() {
let root = std::env::temp_dir().join(format!("vc-sent-command-paths-{}", std::process::id()));
std::fs::create_dir_all(&root).unwrap();
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap();
let mut sent = Vec::new();
vectorcraft_engine::file_access::confine(roots.as_ref(), || {
super::sent_paths(&json!({"command": "attributes.set", "params": {"url": "https://example.com/a/page.html"}}), &mut sent);
super::sent_paths(&json!({"command": "object.path.simplify", "params": {"wholePaths": "out/w.svg"}}), &mut sent);
super::sent_paths(&json!({"command": "document.compare", "params": {"diffPath": "out/d.svg"}}), &mut sent);
super::sent_paths(&json!({"command": "file.place", "params": {"directory": "out/folder"}}), &mut sent);
});
let _ = std::fs::remove_dir_all(root);
let pair = |path: &str, name: &str| (format!("loaded/{path}"), format!("loaded/{name}"));
assert_eq!(sent, [pair("out/d.svg", "d.svg"), pair("out/folder", "folder")]);
}
/// A hidden path quoted with `{:?}` is hidden with its quotes and control characters escaped.
#[test]
fn a_reply_hides_a_quoted_path_with_escaped_quotes() {
+2
View File
@@ -122,6 +122,7 @@ pub(crate) mod shapes;
pub mod shortcut_import;
pub(crate) mod simplify_slider;
pub mod slices;
pub mod smart_punctuation;
pub(crate) mod smooth_slider;
pub mod spot_colors;
pub mod svg_filter;
@@ -430,6 +431,7 @@ registry! {
VectorHalftone: [halftone::KIND] => halftone::SPEC,
SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC,
SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC,
SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC,
PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC,
Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC,
LiquifyOptions: [liquify::KIND] => liquify::SPEC,
+6 -3
View File
@@ -520,7 +520,7 @@ mod tests {
}
/// Text Wrap Options › Offset is a distance, and its range is the one `object.textWrap.options`
/// keeps an Offset to.
/// accepts: the command takes the range's ends and refuses an Offset outside them.
#[test]
fn text_wrap_offset_is_a_distance_within_the_commands_range() {
assert!(lengths("object.textWrap.options").contains(&"offset"));
@@ -534,8 +534,11 @@ mod tests {
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("object.textWrap.make", &json!({})).unwrap();
for (sent, end) in [(5000.0, *range.end()), (-5000.0, *range.start())] {
assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": sent })).unwrap()["offset"], json!(end));
for end in [*range.end(), *range.start()] {
assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": end })).unwrap()["offset"], json!(end));
}
for sent in [5000.0, -5000.0] {
assert!(s.execute("object.textWrap.options", &json!({ "offset": sent })).is_err(), "{sent}");
}
}
+21 -1
View File
@@ -2,7 +2,8 @@
//! asks which pages (a preview with page navigation), the box to crop to and the password.
//!
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the
//! one placed; 1-based), `allPages` and `range` (open), `cropTo` and `password`. `__locked` is set
//! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for
//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set
//! until the password is accepted: OK then unlocks the file. `__place` keeps the other `file.place`
//! params (Link, Template, `at`…). The file's bytes stay out of the fields, in
//! [`crate::state::UiState::dialog_file`].
@@ -142,6 +143,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
"page": 1,
"allPages": true,
"range": "",
"linkPages": false,
"cropTo": CropTo::default().id(),
"password": "",
"__locked": locked,
@@ -183,6 +185,17 @@ fn password(d: &Dialog) -> Option<String> {
Some(d.str("password")).filter(|p| !p.is_empty())
}
/// Can the pages open linked: the file was read from a path (a linked page is read from its
/// file again) and opens without a password (`document.open`'s `linkPages` refuses one).
fn can_link(d: &Dialog) -> bool {
d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none()
}
/// Import PDF Pages as Links is checked, and can be.
fn links_on(d: &Dialog) -> bool {
d.bool("linkPages") && can_link(d)
}
/// OK: unlock the file with the password, else open the pages or place the page.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let file = app.ui.dialog_file.clone().ok_or("the PDF is no longer loaded")?;
@@ -213,6 +226,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if !d.bool("allPages") && !range.trim().is_empty() {
p["pages"] = json!(range);
}
if links_on(&d) {
p["linkPages"] = json!(true);
}
io::open_document(app, &name, &file.bytes, path, &p).map(|_| ())
};
match r {
@@ -291,6 +307,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
}
});
widgets::dim_label(ui, tl!("e.g. 1-3, 5"));
ui.add_space(10.0);
if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) {
d.fields.insert("linkPages".into(), json!(!d.bool("linkPages")));
}
}
});
});
@@ -1,8 +1,9 @@
//! Perspective Grid Options (double-click the Perspective Grid tool): whether the Plane Switching
//! Widget shows and which corner of the window it sits in. OK runs `perspective.widget.options`
//! (the options live in the preferences).
//! Widget shows and which corner of the window it sits in, and what Automatic Plane Positioning
//! takes a point from. OK runs `perspective.widget.options` (the options live in the preferences).
//!
//! Fields: `show` (bool) and `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`).
//! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`),
//! `anchorPoint` (bool) and `gridlineIntersection` (bool).
use serde_json::{Value, json};
use vectorcraft_tools::distort::perspective::widget::WidgetCorner;
@@ -38,5 +39,13 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
ui.add_space(8.0);
let corners: Vec<(&str, &str)> = WidgetCorner::ALL.iter().map(|c| (c.id(), c.label())).collect();
ui.add_enabled_ui(on, |ui| form::choice(ui, d, "position", tl!("Widget Position:"), (110.0, 160.0), &corners));
ui.add_space(8.0);
widgets::section_header(ui, tl!("Automatic Plane Positioning"));
for (key, label) in [("anchorPoint", tl!("Anchor Point of Perspective Artwork")), ("gridlineIntersection", tl!("Intersection of Gridlines"))] {
let on = d.bool(key);
if widgets::check(ui, label, on, true) {
d.fields.insert(key.into(), json!(!on));
}
}
false
}
@@ -0,0 +1,169 @@
//! Type › Smart Punctuation…: which keyboard characters to replace with their typographic forms,
//! where (the selected type or the whole document) and whether to report how many of each were
//! replaced. OK runs `type.smartPunctuation` as one undo step, and the dialog opens on the fields
//! confirmed last.
//!
//! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and
//! `fractions`, `scope` (`selection` or `document`) and `report`.
use serde_json::{Value, json};
use super::{DialogResult, DialogSpec, form, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Smart Punctuation.
pub const KIND: &str = "smartPunctuation";
const CMD: &str = "type.smartPunctuation";
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Smart Punctuation").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM };
/// The replacement options in the dialog's order: (field, the key of their count in the
/// command's reply, label).
fn options() -> [(&'static str, &'static str, &'static str); 7] {
[
("fiLigatures", "fiLigatures", tl!("ff, fi, ffi Ligatures")),
("flLigatures", "flLigatures", tl!("ff, fl, ffl Ligatures")),
("quotes", "quotes", tl!("Smart Quotes")),
("spaces", "spaces", tl!("Smart Spaces")),
("dashes", "dashes", tl!("En, Em Dashes")),
("ellipsis", "ellipses", tl!("Ellipses")),
("fractions", "fractions", tl!("Expert Fractions")),
]
}
/// The fields the menu item opens with: those confirmed last, else quotes, dashes and ellipses on
/// (the command's defaults). With nothing selected, the whole document.
pub fn fields(app: &VectorcraftApp) -> Value {
let mut f = match &app.ui.smart_punctuation {
Value::Object(o) => Value::Object(o.clone()),
_ => json!({
"fiLigatures": false,
"flLigatures": false,
"quotes": true,
"spaces": false,
"dashes": true,
"ellipsis": true,
"fractions": false,
"scope": "selection",
"report": false,
}),
};
if !has_selection(app) {
f["scope"] = json!("document");
}
f
}
fn has_selection(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|d| !d.selection.is_empty())
}
/// The command's parameters: the switches and the scope.
fn params(d: &Dialog) -> Value {
let mut p = serde_json::Map::new();
for (key, ..) in options() {
p.insert(key.into(), json!(d.bool(key)));
}
p.insert("scope".into(), json!(if d.str("scope") == "document" { "document" } else { "selection" }));
Value::Object(p)
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
for (key, _, label) in options() {
form::check(ui, d, key, label);
}
ui.add_space(8.0);
widgets::section_header(ui, tl!("Replace In"));
let selected = has_selection(app);
let scope = d.str("scope");
for (value, label, enabled) in [("selection", tl!("Selected Text Only"), selected), ("document", tl!("Entire Document"), true)] {
let on = if selected { scope == value } else { value == "document" };
if widgets::radio(ui, label, on, enabled) {
d.fields.insert("scope".into(), json!(value));
}
}
ui.add_space(8.0);
form::check(ui, d, "report", tl!("Report Results"));
false
}
/// Runs the command, keeps the fields for the next time, and with Report Results on lists how many
/// of each chosen replacement it made.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
let r = run_and_close(app, CMD, params(d))?;
app.ui.smart_punctuation = Value::Object(d.fields.clone());
if d.bool("report") {
let lines: Vec<String> = options()
.into_iter()
.filter(|(key, ..)| d.bool(key))
.map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0)))
.collect();
super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n"));
}
Ok(r)
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
fn app_with_text(text: &str) -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 40, "text": text, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
(app, id)
}
fn plain(app: &VectorcraftApp, id: u64) -> String {
match &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
_ => String::new(),
}
}
/// The menu item opens the dialog; OK replaces in one undo step, reports each chosen
/// replacement's count, and the next opening starts from the fields confirmed.
#[test]
fn menu_item_opens_the_dialog_and_ok_reports_the_counts() {
let (mut app, id) = app_with_text("\"Hi\". 1/2 -- off");
app.run("select.set", json!({"ids": [id]})).unwrap();
crate::menus::invoke(&mut app, CMD, json!({}));
let d = app.ui.dialog.as_mut().expect("Smart Punctuation opens");
assert_eq!((d.kind.as_str(), d.str("scope")), (KIND, "selection".to_string()));
for key in ["spaces", "fractions", "fiLigatures", "report"] {
d.fields.insert(key.into(), json!(true));
}
d.fields.insert("ellipsis".into(), json!(false));
let undo = app.session.doc().unwrap().history.undo.len();
super::super::confirm(&mut app).unwrap();
assert_eq!(plain(&app, id), "“Hi”. ½ – o\u{FB00}");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
let told = app.ui.dialog.as_ref().expect("Report Results shows the counts");
assert_eq!(told.kind, crate::dialogs::confirm::MESSAGE);
assert_eq!(told.str("detail"), "ff, fi, ffi Ligatures: 1\nSmart Quotes: 2\nSmart Spaces: 1\nEn, Em Dashes: 1\nExpert Fractions: 1");
app.ui.dialog = None;
crate::menus::invoke(&mut app, CMD, json!({}));
let again = app.ui.dialog.as_ref().unwrap();
assert!(again.bool("fractions") && again.bool("report") && !again.bool("ellipsis"));
}
/// With nothing selected the dialog replaces in the entire document, and without Report
/// Results it shows no message. An unchanged document keeps its undo history.
#[test]
fn with_nothing_selected_the_whole_document_is_replaced() {
let (mut app, id) = app_with_text("a--b");
app.run("select.none", json!({})).unwrap();
crate::menus::invoke(&mut app, CMD, json!({}));
assert_eq!(app.ui.dialog.as_ref().unwrap().str("scope"), "document");
super::super::confirm(&mut app).unwrap();
assert_eq!(plain(&app, id), "a–b");
assert!(app.ui.dialog.is_none());
let undo = app.session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut app, CMD, json!({}));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
}
}
@@ -83,6 +83,47 @@ fn all_pages_and_a_crop_box() {
assert_eq!(artboard_widths(&app), [10.0, 40.0, 30.0]);
}
/// Each layer's objects in the active document: placed documents (true) or not.
fn placed_pages(app: &VectorcraftApp) -> Vec<bool> {
let doc = &app.session.active().unwrap().doc;
doc.layers.iter().flat_map(|l| l.children().cloned().unwrap_or_default()).map(|n| matches!(n.kind, NodeKind::PlacedDocument(_))).collect()
}
#[test]
fn import_pdf_pages_as_links_opens_each_page_linked() {
let dir = vectorcraft_testkit::TempDir::new("import-pdf-link-pages");
let path = dir.join("three.pdf").to_string_lossy().into_owned();
std::fs::write(&path, three_pages()).unwrap();
let mut app = app();
io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap();
assert_eq!(field(&app, "linkPages"), false, "off by default");
frame(&mut app);
set(&mut app, "linkPages", json!(true));
set(&mut app, "allPages", json!(false));
set(&mut app, "range", json!("1, 3"));
frame(&mut app);
confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(artboard_widths(&app), [100.0, 300.0]);
assert_eq!(placed_pages(&app), [true, true]);
// A file given without its path, or opened with a password, can't link its pages: they open as art.
io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap();
set(&mut app, "linkPages", json!(true));
frame(&mut app);
confirm(&mut app).unwrap();
assert_eq!(placed_pages(&app), [false, false, false]);
let two = pdf(&[PdfPage::new(10.0, 10.0, "0 g 0 0 5 5 re f"), PdfPage::new(20.0, 10.0, "0 g 0 0 5 5 re f")], Some("pw"));
let locked = dir.join("two.pdf").to_string_lossy().into_owned();
std::fs::write(&locked, &two).unwrap();
io::open_bytes(&mut app, &locked, &two, Some(locked.clone())).unwrap();
set(&mut app, "password", json!("pw"));
confirm(&mut app).unwrap();
set(&mut app, "linkPages", json!(true));
frame(&mut app);
confirm(&mut app).unwrap();
assert_eq!(placed_pages(&app), [false, false]);
}
#[test]
fn single_page_pdfs_open_directly() {
let mut app = app();
@@ -250,6 +250,26 @@ fn double_clicking_the_tool_opens_perspective_grid_options() {
assert!(!app.session.prefs.perspective_widget.show);
}
#[test]
fn perspective_grid_options_hold_automatic_plane_positioning() {
let mut app = app();
app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap();
assert_eq!((field(&app, "anchorPoint"), field(&app, "gridlineIntersection")), (json!(true), json!(true)), "both on by default");
frame(&mut app);
set(&mut app, "gridlineIntersection", json!(false));
frame(&mut app);
super::confirm(&mut app).unwrap();
assert_eq!(kind(&app), None);
let o = app.session.prefs.perspective_widget;
assert!(o.anchor_point && !o.gridline_intersection && o.show);
// The dialog opens on what was set, and a value that is not true or false is refused.
app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap();
assert_eq!(field(&app, "gridlineIntersection"), json!(false));
set(&mut app, "anchorPoint", json!("off"));
assert!(super::confirm(&mut app).is_err());
assert!(app.session.prefs.perspective_widget.anchor_point);
}
#[test]
fn digit_keys_switch_planes_and_the_widget_follows_the_window() {
let mut app = app();

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