mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 18:04:03 +01:00
Merge main into feat/find-replace-dialog
# Conflicts: # crates/ui-egui/src/palette.rs
This commit is contained in:
commit
8ea38f6164
220 files changed
+15468
-2929
No files matched your search
@@ -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"
|
||||
Generated
+12
@@ -1043,6 +1043,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -6681,6 +6692,7 @@ dependencies = [
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-metafile",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"vectorcraft-brush",
|
||||
|
||||
@@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
|
||||
@@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
|
||||
@@ -1008,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
|
||||
}
|
||||
|
||||
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
|
||||
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
|
||||
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
|
||||
/// the exports leave for brush art when they cull.
|
||||
pub fn reach(n: &Node) -> f64 {
|
||||
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none());
|
||||
if !n.appearance.items.iter().any(paints) {
|
||||
return 0.0;
|
||||
}
|
||||
let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
|
||||
16.0 * w + 8.0
|
||||
}
|
||||
|
||||
/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and
|
||||
/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the
|
||||
/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as
|
||||
/// it is painted with its own appearance and not its paths'. Symbol art is not looked into
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it).
|
||||
pub fn reach_within(n: &Node) -> f64 {
|
||||
let members = match &n.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(),
|
||||
NodeKind::Compound { .. } => &[],
|
||||
_ => n.children().map_or(&[][..], |c| &c[..]),
|
||||
};
|
||||
members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max)
|
||||
}
|
||||
|
||||
/// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any
|
||||
/// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed.
|
||||
pub fn expand(doc: &Document, n: &Node) -> Option<Node> {
|
||||
|
||||
+440
-16
@@ -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();
|
||||
|
||||
+466
-37
@@ -56,19 +56,114 @@ fn is_tiff(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*")
|
||||
}
|
||||
|
||||
/// The width and height of the first image of TIFF `bytes` when it has more strips or tiles than
|
||||
/// the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles per plane
|
||||
/// times planes past `usize::MAX`. A file that stores one plane per channel (PlanarConfiguration 2)
|
||||
/// has a plane for each channel; other files have one. The decoder multiplies these counts without
|
||||
/// a check, which panics where overflow checks are on. Such an image, when it is at least a pixel
|
||||
/// wide, claims at least 2^32 samples.
|
||||
/// Where a tag repeats, the value giving the most strips or tiles counts. `None` for other images
|
||||
/// What [`jpeg_frames`] found in a JPEG's headers.
|
||||
enum Frames {
|
||||
/// Every frame header declares a size the check accepts, or there is none.
|
||||
Fit,
|
||||
/// The width and height of the first frame header the check refuses.
|
||||
Misfit(u16, u16),
|
||||
/// The steps ran past [`MAX_JPEG_HEADER_STEPS`].
|
||||
OverBudget,
|
||||
}
|
||||
|
||||
/// Checks the width and height each 8-bit baseline, extended or progressive frame header in the
|
||||
/// headers of a JPEG declares with `fits`. The JPEG is the bytes after its start-of-image marker:
|
||||
/// `parts[0]` followed by `parts[1]`. The headers are read as the decoder reads them, up to the
|
||||
/// first start-of-scan or end-of-image marker: every other marker is followed by its segment's
|
||||
/// length, and bytes between segments are passed over, as are fill bytes (0xFF, and 0x00 after
|
||||
/// one) before a marker. `steps` counts each byte looked at and each segment passed over.
|
||||
fn jpeg_frames(parts: [&[u8]; 2], steps: &mut u64, fits: impl Fn(u16, u16) -> bool) -> Frames {
|
||||
let byte = |i: usize| match i.checked_sub(parts[0].len()) {
|
||||
None => parts[0].get(i).copied(),
|
||||
Some(j) => parts[1].get(j).copied(),
|
||||
};
|
||||
let u16_at = |i: usize| Some(u16::from_be_bytes([byte(i)?, byte(i.checked_add(1)?)?]));
|
||||
let mut p = 0usize;
|
||||
loop {
|
||||
*steps += 1;
|
||||
if *steps > MAX_JPEG_HEADER_STEPS {
|
||||
return Frames::OverBudget;
|
||||
}
|
||||
let Some(b) = byte(p) else { return Frames::Fit };
|
||||
p += 1;
|
||||
if b != 0xFF {
|
||||
continue;
|
||||
}
|
||||
while matches!(byte(p), Some(0xFF | 0)) {
|
||||
p += 1;
|
||||
*steps += 1;
|
||||
if *steps > MAX_JPEG_HEADER_STEPS {
|
||||
return Frames::OverBudget;
|
||||
}
|
||||
}
|
||||
let Some(marker) = byte(p) else { return Frames::Fit };
|
||||
p += 1;
|
||||
if matches!(marker, 0xDA | 0xD9) {
|
||||
return Frames::Fit;
|
||||
}
|
||||
// Length (2 bytes), then for a frame header its precision, height and width.
|
||||
let Some(len) = u16_at(p) else { return Frames::Fit };
|
||||
if matches!(marker, 0xC0..=0xC2)
|
||||
&& byte(p.saturating_add(2)) == Some(8)
|
||||
&& let (Some(h), Some(w)) = (u16_at(p.saturating_add(3)), u16_at(p.saturating_add(5)))
|
||||
&& !fits(w, h)
|
||||
{
|
||||
return Frames::Misfit(w, h);
|
||||
}
|
||||
if len < 2 {
|
||||
return Frames::Fit;
|
||||
}
|
||||
p = p.saturating_add(usize::from(len));
|
||||
}
|
||||
}
|
||||
|
||||
/// Most strips or tiles the first image of a TIFF may have: VectorCraft's own limit, 1/1024 of
|
||||
/// [`crate::MAX_RASTER_ALLOC`] (524,288 in the web app, 2,097,152 on the desktop). The decoder
|
||||
/// reads an offset and a byte count of 8 bytes each for every one into memory before anything else.
|
||||
pub const MAX_TIFF_CHUNKS: u64 = crate::MAX_RASTER_ALLOC / 1024;
|
||||
|
||||
/// Most pixels the JPEG of a JPEG-compressed TIFF tile may declare when it declares more pixels
|
||||
/// than the whole image has: VectorCraft's own limit (2048 × 2048, 16 MB as CMYK).
|
||||
pub const MAX_JPEG_TILE_PIXELS: u64 = 1 << 22;
|
||||
|
||||
/// Most steps reading the JPEG headers of a TIFF's strips or tiles may take (a byte looked at, a
|
||||
/// segment passed over or a strip offset read): VectorCraft's own limit.
|
||||
const MAX_JPEG_HEADER_STEPS: u64 = 1 << 24;
|
||||
|
||||
/// The width and height of the first image of TIFF or BigTIFF `bytes` when it has more strips or
|
||||
/// tiles than the `tiff` decoder can count: strips per plane times planes past `u32::MAX`, or tiles
|
||||
/// per plane times planes past `usize::MAX`. A file that stores one plane per channel
|
||||
/// (PlanarConfiguration 2) has a plane for each channel; other files have one. The decoder
|
||||
/// multiplies these counts without a check, which panics where overflow checks are on. Such an
|
||||
/// image, when it is at least a pixel wide, claims at least 2^32 samples.
|
||||
/// It also gives them for an image with more than [`MAX_TIFF_CHUNKS`] strips or tiles, counted from
|
||||
/// its size or from the number of values its StripOffsets and StripByteCounts tags hold, or its
|
||||
/// TileOffsets and TileByteCounts tags for a tiled image. An image the decoder reads as strips (it
|
||||
/// has both strip tables and neither tile table) counts strips, and one it reads as tiles counts
|
||||
/// tiles; the decoder refuses an image with any other mix of these tags before it reads a table.
|
||||
/// For a JPEG-compressed image (Compression 7) it gives the width and height a strip's or tile's
|
||||
/// JPEG declares in a frame header (in the JPEGTables, or in the strip or tile before its first
|
||||
/// scan) when they are wider or taller than the strip or tile, or, for a tile, when they make more
|
||||
/// than [`MAX_JPEG_TILE_PIXELS`] pixels and more than the image has. The decoder allocates the
|
||||
/// pixels the JPEG declares. It gives the image's width and height when reading those headers
|
||||
/// takes more than 16,777,216 steps (a byte looked at, a segment passed over or a strip offset
|
||||
/// read), when the strip or tile offsets are of a type other than BYTE, UNDEFINED, SHORT, LONG,
|
||||
/// IFD, LONG8 or IFD8, and when the image's width and height, a striped image's RowsPerStrip or a
|
||||
/// tiled image's tile size isn't a single value of one of those types.
|
||||
/// Where a tag repeats, the value giving the most strips or tiles counts, and the JPEG check uses
|
||||
/// the last entry of a field type the decoder knows, as the decoder does. `None` for other images
|
||||
/// and for bytes that aren't a TIFF.
|
||||
pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
let le = bytes.starts_with(b"II*\0");
|
||||
if !le && !bytes.starts_with(b"MM\0*") {
|
||||
let le = bytes.starts_with(b"II");
|
||||
let head = bytes.get(..4)?;
|
||||
// A BigTIFF counts and points with 8 bytes where a TIFF uses 4, so its entries are 20 bytes.
|
||||
let big = if head == b"II*\0" || head == b"MM\0*" {
|
||||
false
|
||||
} else if head == b"II+\0" || head == b"MM\0+" {
|
||||
true
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let u16_at = |at: usize| -> Option<u16> {
|
||||
let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?;
|
||||
Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
|
||||
@@ -77,32 +172,71 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
|
||||
};
|
||||
let ifd = usize::try_from(u32_at(4)?).ok()?;
|
||||
// (tag, the entry's single BYTE, SHORT, LONG or IFD value, which sits in the entry, or its
|
||||
// single LONG8 or IFD8 value that fits in 32 bits, which sits where the entry points)
|
||||
let entry = |i: usize| -> Option<(u16, Option<u32>)> {
|
||||
let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?;
|
||||
let (ty, count, at) = (u16_at(e.checked_add(2)?)?, u32_at(e.checked_add(4)?)?, e.checked_add(8)?);
|
||||
let value = match (ty, count) {
|
||||
(1, 1) => bytes.get(at).map(|&b| u32::from(b)),
|
||||
(3, 1) => u16_at(at).map(u32::from),
|
||||
(4 | 13, 1) => u32_at(at),
|
||||
(16 | 18, 1) => {
|
||||
let at = usize::try_from(u32_at(at)?).ok()?;
|
||||
let (lo, hi) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
|
||||
let wide = if le { u64::from(hi) << 32 | u64::from(lo) } else { u64::from(lo) << 32 | u64::from(hi) };
|
||||
u32::try_from(wide).ok()
|
||||
}
|
||||
let u64_at = |at: usize| -> Option<u64> {
|
||||
let b: [u8; 8] = bytes.get(at..at.checked_add(8)?)?.try_into().ok()?;
|
||||
Some(if le { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) })
|
||||
};
|
||||
let word_len: usize = if big { 8 } else { 4 };
|
||||
let word = |at: usize| if big { u64_at(at) } else { u32_at(at).map(u64::from) };
|
||||
// The bytes one value of each field type takes; 0 for types the decoder doesn't know.
|
||||
let width_of = |ty: u16| -> usize {
|
||||
match ty {
|
||||
1 | 2 | 6 | 7 => 1,
|
||||
3 | 8 => 2,
|
||||
4 | 9 | 11 | 13 => 4,
|
||||
5 | 10 | 12 | 16..=18 => 8,
|
||||
_ => 0,
|
||||
}
|
||||
};
|
||||
let ifd = usize::try_from(word(if big { 8 } else { 4 })?).ok()?;
|
||||
let entries = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) };
|
||||
let first = ifd.checked_add(if big { 8 } else { 2 })?;
|
||||
// (tag, field type, number of values, where the values are: in the entry when they fit in its
|
||||
// last word, otherwise where that word points)
|
||||
let entry = |i: usize| -> Option<(u16, u16, u64, Option<usize>)> {
|
||||
let e = first.checked_add(i.checked_mul(4 + 2 * word_len)?)?;
|
||||
let (tag, ty, count) = (u16_at(e)?, u16_at(e.checked_add(2)?)?, word(e.checked_add(4)?)?);
|
||||
let at = e.checked_add(4 + word_len)?;
|
||||
let fits = u64::try_from(width_of(ty)).ok()?.checked_mul(count).is_some_and(|n| n <= word_len as u64);
|
||||
let values = if fits { Some(at) } else { word(at).and_then(|p| usize::try_from(p).ok()) };
|
||||
Some((tag, ty, count, values))
|
||||
};
|
||||
// Value `i` of an entry's BYTE, UNDEFINED, SHORT, LONG, IFD, LONG8 or IFD8 values at `at`.
|
||||
let nth = |ty: u16, at: usize, i: u64| -> Option<u64> {
|
||||
let p = at.checked_add(usize::try_from(i).ok()?.checked_mul(width_of(ty))?)?;
|
||||
match ty {
|
||||
1 | 7 => bytes.get(p).map(|&b| u64::from(b)),
|
||||
3 => u16_at(p).map(u64::from),
|
||||
4 | 13 => u32_at(p).map(u64::from),
|
||||
16 | 18 => u64_at(p),
|
||||
_ => None,
|
||||
};
|
||||
Some((u16_at(e)?, value))
|
||||
}
|
||||
};
|
||||
let (mut width, mut height, mut planes, mut planar) = (0u32, 0u32, 1u32, false);
|
||||
let (mut rows, mut tile_w, mut tile_h) = (None::<u32>, None::<u32>, None::<u32>);
|
||||
// The most values a strip table and a tile table hold.
|
||||
let (mut strip_chunks, mut tile_chunks) = (0u64, 0u64);
|
||||
// The decoder keeps the last entry of a tag whose field type it knows. These are the last such
|
||||
// entries (type, count, where) of the tags `LAST` lists.
|
||||
const LAST: [u16; 11] = [256, 257, 259, 278, 322, 323, 273, 279, 324, 325, 347];
|
||||
let mut last = [None::<(u16, u64, Option<usize>)>; LAST.len()];
|
||||
let least = |was: Option<u32>, v: u32| Some(was.map_or(v, |w| w.min(v)));
|
||||
for i in 0..usize::from(u16_at(ifd)?) {
|
||||
let Some((tag, value)) = entry(i) else { break };
|
||||
let Some(v) = value else { continue };
|
||||
// The entry's single BYTE, UNDEFINED, SHORT, LONG or IFD value, or its single LONG8 or IFD8
|
||||
// value when that fits in 32 bits.
|
||||
let single = |ty: u16, count: u64, at: Option<usize>| at.filter(|_| count == 1).and_then(|at| nth(ty, at, 0)).and_then(|v| u32::try_from(v).ok());
|
||||
for i in 0..usize::try_from(entries).unwrap_or(usize::MAX) {
|
||||
let Some((tag, ty, count, at)) = entry(i) else { break };
|
||||
match tag {
|
||||
273 | 279 => strip_chunks = strip_chunks.max(count),
|
||||
324 | 325 => tile_chunks = tile_chunks.max(count),
|
||||
_ => {}
|
||||
}
|
||||
if width_of(ty) > 0
|
||||
&& let Some(slot) = LAST.iter().position(|&t| t == tag).and_then(|k| last.get_mut(k))
|
||||
{
|
||||
*slot = Some((ty, count, at));
|
||||
}
|
||||
let Some(v) = single(ty, count, at) else { continue };
|
||||
match tag {
|
||||
256 => width = width.max(v),
|
||||
257 => height = height.max(v),
|
||||
@@ -115,13 +249,87 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
}
|
||||
}
|
||||
let planes = if planar { u128::from(planes) } else { 1 };
|
||||
let tiles = match (tile_w, tile_h) {
|
||||
(Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes > usize::MAX as u128,
|
||||
_ => false,
|
||||
let tiled = match (tile_w, tile_h) {
|
||||
(Some(tw @ 1..), Some(th @ 1..)) => u128::from(width.div_ceil(tw)) * u128::from(height.div_ceil(th)) * planes,
|
||||
_ => 0,
|
||||
};
|
||||
let tiles = tiled > usize::MAX as u128;
|
||||
let rows = rows.unwrap_or(height);
|
||||
let strips = rows > 0 && u128::from(height.saturating_sub(1) / rows + 1) * planes > u128::from(u32::MAX);
|
||||
(tiles || strips).then_some((width, height))
|
||||
let striped = height.saturating_sub(1).checked_div(rows).map_or(0, |n| u128::from(n + 1) * planes);
|
||||
let strips = striped > u128::from(u32::MAX);
|
||||
if tiles || strips {
|
||||
return Some((width, height));
|
||||
}
|
||||
let last_of = |tag: u16| LAST.iter().position(|&t| t == tag).and_then(|k| last.get(k).copied().flatten());
|
||||
// The single value the decoder reads from the last entry of `tag`: `None` without one, and
|
||||
// `Some(None)` when that entry doesn't hold a single value read here.
|
||||
let value_of = |tag: u16| last_of(tag).map(|(ty, count, at)| single(ty, count, at));
|
||||
// The decoder reads strips when the image has both strip tables and neither tile table, tiles
|
||||
// in the opposite case, and refuses every other image before it reads a table.
|
||||
let layout = match [273, 279, 324, 325].map(|tag| last_of(tag).is_some()) {
|
||||
[true, true, false, false] => Some((273, striped.max(u128::from(strip_chunks)))),
|
||||
[false, false, true, true] => Some((324, tiled.max(u128::from(tile_chunks)))),
|
||||
_ => None,
|
||||
};
|
||||
let (offsets_tag, chunks) = layout?;
|
||||
if chunks > u128::from(MAX_TIFF_CHUNKS) {
|
||||
return Some((width, height));
|
||||
}
|
||||
if value_of(259) != Some(Some(7)) {
|
||||
return None;
|
||||
}
|
||||
// The JPEG check uses the sizes the decoder reads. A size it needs that isn't a single value
|
||||
// read here refuses the image.
|
||||
let (Some(Some(w_img)), Some(Some(h_img))) = (value_of(256), value_of(257)) else { return Some((width, height)) };
|
||||
let tile = offsets_tag == 324;
|
||||
// RowsPerStrip, which the decoder reads only for strips.
|
||||
let rows = if tile { Some(h_img) } else { value_of(278).unwrap_or(Some(h_img)) };
|
||||
let Some(rows) = rows else { return Some((width, height)) };
|
||||
let (tw, th) = match (value_of(322).flatten(), value_of(323).flatten()) {
|
||||
(Some(tw), Some(th)) => (tw, th),
|
||||
_ if tile => return Some((width, height)),
|
||||
_ => (0, 0),
|
||||
};
|
||||
// A strip is as wide as the image and RowsPerStrip tall (at most the image's height); a tile's
|
||||
// JPEG may be as large as the tile, which the edge tiles of the image overhang.
|
||||
let fits = |w: u16, h: u16| {
|
||||
let (w, h) = (u32::from(w), u32::from(h));
|
||||
if tile {
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
w <= tw && h <= th && (pixels <= MAX_JPEG_TILE_PIXELS || pixels <= u64::from(w_img) * u64::from(h_img))
|
||||
} else {
|
||||
w <= w_img && h <= rows.min(h_img)
|
||||
}
|
||||
};
|
||||
// The decoder reads the JPEGTables after their start-of-image marker and without their last two
|
||||
// bytes, followed by each strip or tile after its first two bytes; without JPEGTables, each
|
||||
// strip or tile after its start-of-image marker.
|
||||
let tables = last_of(347)
|
||||
.and_then(|(_, count, at)| {
|
||||
let at = at?;
|
||||
let end = at.checked_add(usize::try_from(count).ok()?)?.min(bytes.len());
|
||||
bytes.get(at.checked_add(2)?..end.checked_sub(2)?)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let (ty, count, at) = last_of(offsets_tag)?;
|
||||
let at = at?;
|
||||
// The decoder also takes offsets of other types (a RATIONAL or ASCII value), which aren't read
|
||||
// here: such an image is refused.
|
||||
if !matches!(ty, 1 | 3 | 4 | 7 | 13 | 16 | 18) {
|
||||
return Some((width, height));
|
||||
}
|
||||
let mut steps = 0u64;
|
||||
for i in 0..count {
|
||||
steps += 1;
|
||||
let Some(at) = nth(ty, at, i).and_then(|o| usize::try_from(o).ok()) else { break };
|
||||
let part = bytes.get(at.saturating_add(2)..).unwrap_or_default();
|
||||
match jpeg_frames([tables, part], &mut steps, fits) {
|
||||
Frames::Fit => {}
|
||||
Frames::Misfit(w, h) => return Some((u32::from(w), u32::from(h))),
|
||||
Frames::OverBudget => return Some((width, height)),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too.
|
||||
@@ -891,7 +1099,7 @@ mod tests {
|
||||
f
|
||||
};
|
||||
assert_eq!(oversized_tiff(&header(2)), Some((u32::MAX, u32::MAX)));
|
||||
assert_eq!(oversized_tiff(&header(1)), None, "one plane: (2^32 − 1)² tiles can be counted in 64 bits");
|
||||
assert_eq!(oversized_tiff(&header(1)), Some((u32::MAX, u32::MAX)), "one plane: countable, but past MAX_TIFF_CHUNKS");
|
||||
assert!(tiff(&header(2)).is_none(), "not decoded");
|
||||
}
|
||||
|
||||
@@ -933,6 +1141,227 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A little-endian TIFF, or BigTIFF when `big`, holding `data` right after its header (from
|
||||
/// byte 8, or 16 in a BigTIFF), then one directory of `entries` (tag, field type, values). An
|
||||
/// entry's values sit in the entry when they fit, otherwise after the directory.
|
||||
fn tiff_file(big: bool, entries: &[(u16, u16, Vec<u64>)], data: &[u8]) -> Vec<u8> {
|
||||
let (word, head) = if big { (8, 16) } else { (4, 8) };
|
||||
let put = |f: &mut Vec<u8>, v: u64, n: usize| f.extend(&v.to_le_bytes()[..n]);
|
||||
let mut f = if big { b"II+\0\x08\0\0\0".to_vec() } else { b"II*\0".to_vec() };
|
||||
let ifd = head + data.len();
|
||||
put(&mut f, ifd as u64, word);
|
||||
f.extend(data);
|
||||
put(&mut f, entries.len() as u64, if big { 8 } else { 2 });
|
||||
let after = f.len() + entries.len() * (4 + 2 * word) + word;
|
||||
let mut tail = vec![];
|
||||
for (tag, ty, values) in entries {
|
||||
let width = match ty {
|
||||
1 | 7 => 1,
|
||||
3 => 2,
|
||||
4 => 4,
|
||||
_ => 8,
|
||||
};
|
||||
f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat());
|
||||
put(&mut f, values.len() as u64, word);
|
||||
let mut v = vec![];
|
||||
for &x in values {
|
||||
put(&mut v, x, width);
|
||||
}
|
||||
if v.len() <= word {
|
||||
v.resize(word, 0);
|
||||
f.extend(v);
|
||||
} else {
|
||||
put(&mut f, (after + tail.len()) as u64, word);
|
||||
tail.extend(v);
|
||||
}
|
||||
}
|
||||
put(&mut f, 0, word);
|
||||
f.extend(tail);
|
||||
f
|
||||
}
|
||||
|
||||
/// A JPEG of four components whose progressive frame header declares `w` × `h` pixels, with a
|
||||
/// scan header and no scan data.
|
||||
fn jpeg_header(w: u16, h: u16) -> Vec<u8> {
|
||||
let mut j = vec![0xFF, 0xD8, 0xFF, 0xC2, 0, 20, 8];
|
||||
j.extend(h.to_be_bytes());
|
||||
j.extend(w.to_be_bytes());
|
||||
j.push(4);
|
||||
for id in 1..=4 {
|
||||
j.extend([id, 0x11, 0]);
|
||||
}
|
||||
j.extend([0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0, 0xFF, 0xD9]);
|
||||
j
|
||||
}
|
||||
|
||||
/// The directory of a 1 × 1 CMYK image with alpha, JPEG-compressed in one strip of `len` bytes
|
||||
/// at byte `at`.
|
||||
fn jpeg_strip_entries(at: u64, len: u64) -> Vec<(u16, u16, Vec<u64>)> {
|
||||
vec![
|
||||
(256, 4, vec![1]),
|
||||
(257, 4, vec![1]),
|
||||
(258, 3, vec![8; 5]),
|
||||
(259, 3, vec![7]),
|
||||
(262, 3, vec![5]),
|
||||
(273, 4, vec![at]),
|
||||
(277, 3, vec![5]),
|
||||
(278, 4, vec![1]),
|
||||
(279, 4, vec![len]),
|
||||
(338, 3, vec![2]),
|
||||
]
|
||||
}
|
||||
|
||||
/// A strip's JPEG that declares more pixels than the strip holds would have the decoder
|
||||
/// allocate them: a 1 × 1 image whose JPEG claims 16384 × 16384 is refused before any decoder
|
||||
/// opens it, in a TIFF or a BigTIFF, with fill bytes or other bytes before the frame header,
|
||||
/// and with the frame header in the JPEGTables.
|
||||
#[test]
|
||||
fn a_jpeg_strip_declaring_more_than_its_strip_is_refused() {
|
||||
let big = jpeg_header(16384, 16384);
|
||||
let file = tiff_file(false, &jpeg_strip_entries(8, big.len() as u64), &big);
|
||||
assert_eq!(oversized_tiff(&file), Some((16384, 16384)));
|
||||
assert!(tiff(&file).is_none(), "not decoded");
|
||||
let bigtiff = tiff_file(true, &jpeg_strip_entries(16, big.len() as u64), &big);
|
||||
assert_eq!(oversized_tiff(&bigtiff), Some((16384, 16384)), "BigTIFF");
|
||||
// The decoder reads the last ImageWidth and ImageLength: 1 × 1 after 16384 × 16384, in one
|
||||
// strip without RowsPerStrip.
|
||||
let mut entries = jpeg_strip_entries(8, big.len() as u64);
|
||||
entries.retain(|e| e.0 != 278);
|
||||
entries.splice(0..0, [(256, 4, vec![16384]), (257, 4, vec![16384])]);
|
||||
assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some((16384, 16384)), "repeated sizes");
|
||||
// StripOffsets as a BYTE, which the decoder reads, and as a RATIONAL, which it reads as two
|
||||
// offsets.
|
||||
for (ty, expected) in [(1, (16384, 16384)), (5, (1, 1))] {
|
||||
let mut entries = jpeg_strip_entries(8, big.len() as u64);
|
||||
for e in &mut entries {
|
||||
if e.0 == 273 {
|
||||
e.1 = ty;
|
||||
}
|
||||
}
|
||||
assert_eq!(oversized_tiff(&tiff_file(false, &entries, &big)), Some(expected), "StripOffsets of type {ty}");
|
||||
}
|
||||
let one = jpeg_header(1, 1);
|
||||
assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, one.len() as u64), &one)), None, "a JPEG as large as its strip");
|
||||
let wide = jpeg_header(2, 1);
|
||||
assert_eq!(oversized_tiff(&tiff_file(false, &jpeg_strip_entries(8, wide.len() as u64), &wide)), Some((2, 1)), "one pixel too wide");
|
||||
for (what, prefix) in [("fill bytes", &[0xFF, 0x00, 0xFF][..]), ("other bytes", &[0x12, 0x34][..])] {
|
||||
let mut j = big[..2].to_vec();
|
||||
j.extend(prefix);
|
||||
j.extend(&big[2..]);
|
||||
let file = tiff_file(false, &jpeg_strip_entries(8, j.len() as u64), &j);
|
||||
assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "{what} before the frame header");
|
||||
}
|
||||
// The JPEGTables hold the frame header; the strip holds only the scan.
|
||||
let tables = [&big[..24], &[0xFF, 0xD9][..]].concat();
|
||||
let scan = [&[0xFF, 0xD8][..], &big[24..]].concat();
|
||||
let mut entries = jpeg_strip_entries(8 + tables.len() as u64, scan.len() as u64);
|
||||
entries.push((347, 7, tables.iter().map(|&b| u64::from(b)).collect()));
|
||||
let file = tiff_file(false, &entries, &[tables, scan].concat());
|
||||
assert_eq!(oversized_tiff(&file), Some((16384, 16384)), "frame header in the JPEGTables");
|
||||
// An encoder's 8 × 8 RGB JPEG, with its own segments before the frame header, in an
|
||||
// 8 × 8 image of one strip, and of strips 4 rows tall.
|
||||
let mut real = Vec::new();
|
||||
image::codecs::jpeg::JpegEncoder::new(&mut real).encode(&[90; 8 * 8 * 3], 8, 8, image::ExtendedColorType::Rgb8).unwrap();
|
||||
let rgb = |rows: u64| {
|
||||
let entries = [
|
||||
(256, 4, vec![8]),
|
||||
(257, 4, vec![8]),
|
||||
(258, 3, vec![8; 3]),
|
||||
(259, 3, vec![7]),
|
||||
(262, 3, vec![2]),
|
||||
(273, 4, vec![8]),
|
||||
(277, 3, vec![3]),
|
||||
(278, 4, vec![rows]),
|
||||
(279, 4, vec![real.len() as u64]),
|
||||
];
|
||||
oversized_tiff(&tiff_file(false, &entries, &real))
|
||||
};
|
||||
assert_eq!(rgb(8), None, "an encoder's JPEG as large as its strip");
|
||||
assert_eq!(rgb(4), Some((8, 8)), "an encoder's JPEG taller than its strip");
|
||||
}
|
||||
|
||||
/// A tile's JPEG may be as large as the tile, which overhangs the image, and when it is more
|
||||
/// than MAX_JPEG_TILE_PIXELS, no larger than the image.
|
||||
#[test]
|
||||
fn a_jpeg_tile_declaring_more_than_its_tile_is_refused() {
|
||||
let tiled_with = |tile: u64, j: &[u8], rows: Vec<u64>| {
|
||||
let mut entries: Vec<_> = jpeg_strip_entries(0, 0).into_iter().filter(|e| !matches!(e.0, 273 | 278 | 279)).collect();
|
||||
if !rows.is_empty() {
|
||||
entries.push((278, 4, rows));
|
||||
}
|
||||
entries.extend([(322, 4, vec![tile]), (323, 4, vec![tile]), (324, 4, vec![8]), (325, 4, vec![j.len() as u64])]);
|
||||
oversized_tiff(&tiff_file(false, &entries, j))
|
||||
};
|
||||
let tiled = |tile: u64, j: &[u8]| tiled_with(tile, j, vec![]);
|
||||
assert_eq!(tiled_with(16, &jpeg_header(16, 16), vec![1, 1]), None, "RowsPerStrip, unread in a tiled image");
|
||||
assert_eq!(tiled(16, &jpeg_header(16, 16)), None, "as large as the tile");
|
||||
assert_eq!(tiled(16, &jpeg_header(17, 16)), Some((17, 16)), "wider than the tile");
|
||||
assert_eq!(tiled(16, &jpeg_header(16, 17)), Some((16, 17)), "taller than the tile");
|
||||
assert_eq!(tiled(4096, &jpeg_header(2048, 2048)), None, "MAX_JPEG_TILE_PIXELS");
|
||||
assert_eq!(tiled(4096, &jpeg_header(2048, 2049)), Some((2048, 2049)), "past MAX_JPEG_TILE_PIXELS and the image");
|
||||
}
|
||||
|
||||
/// The decoder reads every strip's offset and byte count before anything else: an image with
|
||||
/// more than MAX_TIFF_CHUNKS strips, counted from its size or from its tables, is refused.
|
||||
#[test]
|
||||
fn tiffs_with_more_strips_than_their_tables_may_hold_are_refused() {
|
||||
let file = |height: u64, count: u32| {
|
||||
let entries = [
|
||||
(256, 4, vec![1]),
|
||||
(257, 4, vec![height]),
|
||||
(258, 3, vec![8]),
|
||||
(262, 3, vec![1]),
|
||||
(273, 4, vec![8]),
|
||||
(278, 4, vec![1]),
|
||||
(279, 4, vec![1]),
|
||||
];
|
||||
let mut f = tiff_file(false, &entries, &[0]);
|
||||
// StripOffsets' count, its values left out of the file.
|
||||
let at = 8 + 1 + 2 + 4 * 12 + 4;
|
||||
f[at..at + 4].copy_from_slice(&count.to_le_bytes());
|
||||
f
|
||||
};
|
||||
let most = MAX_TIFF_CHUNKS;
|
||||
assert_eq!(oversized_tiff(&file(most, 1)), None, "MAX_TIFF_CHUNKS rows of a strip each");
|
||||
assert_eq!(oversized_tiff(&file(most + 1, 1)), Some((1, u32::try_from(most + 1).unwrap())), "one strip more");
|
||||
assert_eq!(oversized_tiff(&file(1, u32::try_from(most).unwrap())), None, "MAX_TIFF_CHUNKS offsets");
|
||||
assert_eq!(oversized_tiff(&file(1, u32::try_from(most + 1).unwrap())), Some((1, 1)), "one offset more");
|
||||
assert!(tiff(&file(1, 1 << 25)).is_none(), "not decoded");
|
||||
// Tile sizes without tile tables: the decoder reads the strips and never counts the
|
||||
// 4,194,304 tiles of a pixel the sizes give.
|
||||
let strips_with_tile_sizes = |offsets: Option<u16>| {
|
||||
let mut entries = vec![
|
||||
(256, 4, vec![2048]),
|
||||
(257, 4, vec![2048]),
|
||||
(258, 3, vec![8]),
|
||||
(262, 3, vec![1]),
|
||||
(273, 4, vec![8]),
|
||||
(279, 4, vec![2048 * 2048]),
|
||||
(322, 4, vec![1]),
|
||||
(323, 4, vec![1]),
|
||||
];
|
||||
entries.extend(offsets.map(|tag| (tag, 4, vec![8])));
|
||||
entries.sort_by_key(|e| e.0);
|
||||
oversized_tiff(&tiff_file(false, &entries, &[0]))
|
||||
};
|
||||
assert_eq!(strips_with_tile_sizes(None), None, "a strip image with tile sizes of one pixel");
|
||||
assert_eq!(strips_with_tile_sizes(Some(324)), None, "strip and tile tables: the decoder refuses it unread");
|
||||
}
|
||||
|
||||
/// Strips whose JPEG headers take more than MAX_JPEG_HEADER_STEPS steps to read refuse the
|
||||
/// file: here every strip points at the same 1 MB without a marker.
|
||||
#[test]
|
||||
fn jpeg_strips_that_take_too_long_to_read_are_refused() {
|
||||
let file = |strips: u64| {
|
||||
let mut entries = jpeg_strip_entries(0, 0);
|
||||
entries.retain(|e| !matches!(e.0, 257 | 273 | 279));
|
||||
entries.extend([(257, 4, vec![strips]), (273, 4, vec![8; strips as usize]), (279, 4, vec![1 << 20; strips as usize])]);
|
||||
tiff_file(false, &entries, &std::iter::repeat_n(0, 1 << 20).collect::<Vec<u8>>())
|
||||
};
|
||||
assert_eq!(oversized_tiff(&file(8)), None, "about 8 million steps");
|
||||
assert_eq!(oversized_tiff(&file(17)), Some((1, 17)), "about 17 million steps");
|
||||
}
|
||||
|
||||
fn inks() -> Inks {
|
||||
Inks::new(3, 2, vec![0, 40, 100, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 12, 34, 56, 78]).unwrap()
|
||||
}
|
||||
|
||||
@@ -379,6 +379,22 @@ pub struct SeriesPaint {
|
||||
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque.
|
||||
/// Graph labels keep none.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_opacity: Option<f32>,
|
||||
/// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub group_isolate: bool,
|
||||
/// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_knockout: Option<crate::Knockout>,
|
||||
/// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub group_knockout_shape: bool,
|
||||
/// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own
|
||||
/// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -527,6 +543,10 @@ pub struct GraphSpec {
|
||||
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed: Option<Rect>,
|
||||
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
|
||||
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed_art: Option<Rect>,
|
||||
}
|
||||
|
||||
fn at_most_one(n: &usize) -> bool {
|
||||
@@ -610,6 +630,32 @@ impl GraphSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
|
||||
/// gives its own bounds, so a clipping group gives the bounds of its clip.
|
||||
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
if matches!(n.kind, crate::NodeKind::Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
for c in children {
|
||||
let (b, t) = art_bounds_of(c);
|
||||
had_type |= t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl Default for GraphSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -659,6 +705,7 @@ impl Default for GraphSpec {
|
||||
connect_points: true,
|
||||
edge_to_edge: false,
|
||||
placed: None,
|
||||
placed_art: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
+376
-88
@@ -1,7 +1,7 @@
|
||||
//! Hit testing over the document tree.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &
|
||||
return false;
|
||||
}
|
||||
// How a click reaches it, if one does.
|
||||
let start = opt;
|
||||
let Some(opt) = path_options(&nodes, &chain, opt) else { return false };
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`.
|
||||
let masked = nodes
|
||||
.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p)));
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`. A container
|
||||
// tests its clipping path in outline from the first layer with Preview off down to it, as
|
||||
// a click going down to it does ([`path_options`]).
|
||||
let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| {
|
||||
let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n)));
|
||||
n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline))
|
||||
});
|
||||
// A click may reach it there ([`may_hit`]: not a guide while guides are locked or
|
||||
// hidden, nor a Shaper group's hidden part), and its own art is what a click would hit
|
||||
// in it: a group's hidden, locked or masked contents don't count.
|
||||
@@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
/// measured by their art ([`Node::geometric_bounds_with`]).
|
||||
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
|
||||
let Some(children) = layer.children() else { return true };
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if layer.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) {
|
||||
tops.push(clip.id);
|
||||
}
|
||||
if !clip_contains(clip, p) {
|
||||
if !clip_contains(clip, p, opt.outline) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) {
|
||||
continue;
|
||||
@@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
|
||||
return;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
@@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Envelope { editing: true, .. })
|
||||
}
|
||||
|
||||
/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame:
|
||||
/// glyph outlines need the font engine, above this crate.
|
||||
fn clip_contains(clip: &Node, p: Point) -> bool {
|
||||
clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`])
|
||||
/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count.
|
||||
fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool {
|
||||
let areas = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
|
||||
/// [`clip_contains`].
|
||||
/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry
|
||||
/// effects of the clipping path and of what it clips by applied, as one path and fill rule
|
||||
/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a
|
||||
/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated
|
||||
/// above this crate, so the engine registers one with [`set_clip_region`].
|
||||
pub type ClipRegion = fn(&Node) -> Option<Option<(BezPath, FillRule)>>;
|
||||
|
||||
static CLIP_REGION: OnceLock<ClipRegion> = OnceLock::new();
|
||||
|
||||
/// Register how the region of a clipping path with live effects is found (the first registration
|
||||
/// stays).
|
||||
pub fn set_clip_region(f: ClipRegion) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = CLIP_REGION.set(f);
|
||||
}
|
||||
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
|
||||
/// path elements.
|
||||
struct EvaluatedClip {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
region: Option<Rc<Option<(BezPath, FillRule)>>>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip
|
||||
/// group whose clipping path has live effects asks for its region, and clip groups can be nested.
|
||||
const CLIPS_KEPT: usize = 16;
|
||||
|
||||
thread_local! {
|
||||
/// The regions [`clip_region`] keeps, the latest first.
|
||||
static CLIPS: RefCell<Vec<EvaluatedClip>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many regions [`clip_region`] evaluated on this thread.
|
||||
static CLIPS_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The region clipping path `clip` clips to with its live geometry effects applied
|
||||
/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes
|
||||
/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the
|
||||
/// [`LiveInputs`] have changed since.
|
||||
fn clip_region(clip: &Node) -> Option<Rc<Option<(BezPath, FillRule)>>> {
|
||||
let f = CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIPS.with_borrow_mut(|kept| {
|
||||
let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?;
|
||||
let e = kept.remove(i);
|
||||
let region = e.region.clone();
|
||||
kept.insert(0, e);
|
||||
Some(region)
|
||||
});
|
||||
if let Some(region) = kept {
|
||||
return region;
|
||||
}
|
||||
#[cfg(test)]
|
||||
CLIPS_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let region = f(clip).map(Rc::new);
|
||||
let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len());
|
||||
let size = elements.saturating_add(art_size(std::slice::from_ref(clip)));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size };
|
||||
CLIPS.with_borrow_mut(|kept| {
|
||||
kept.insert(0, e);
|
||||
kept.truncate(CLIPS_KEPT);
|
||||
let mut total = 0usize;
|
||||
kept.retain(|e| {
|
||||
total = total.saturating_add(e.size);
|
||||
total <= LIVE_KEPT_SIZE
|
||||
});
|
||||
});
|
||||
}
|
||||
region
|
||||
}
|
||||
|
||||
/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path.
|
||||
struct ClipBox {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
rect: Option<Rect>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip
|
||||
/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not
|
||||
/// only the latest few as with the regions.
|
||||
const CLIP_BOXES_KEPT: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes.
|
||||
static CLIP_BOXES: RefCell<(HashMap<NodeId, ClipBox>, usize)> = RefCell::new((HashMap::new(), 0));
|
||||
}
|
||||
|
||||
/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]),
|
||||
/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change.
|
||||
/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the
|
||||
/// pointer moving over more clip groups than fit still finds most of their boxes.
|
||||
pub(crate) fn reshaped_clip_box(clip: &Node) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect));
|
||||
if let Some(rect) = kept {
|
||||
return rect;
|
||||
}
|
||||
let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box()));
|
||||
let size = art_size(std::slice::from_ref(clip));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
CLIP_BOXES.with_borrow_mut(|(boxes, total)| {
|
||||
if let Some(old) = boxes.remove(&clip.id) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
|
||||
let Some(other) = boxes.keys().next().copied() else { break };
|
||||
if let Some(old) = boxes.remove(&other) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
}
|
||||
boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size });
|
||||
*total = total.saturating_add(size);
|
||||
});
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
/// The regions a click inside a clip group must fall in: those `clip` clips to with its live
|
||||
/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]).
|
||||
fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> {
|
||||
match clip_region(clip) {
|
||||
Some(region) => region.as_ref().iter().cloned().collect(),
|
||||
None => clip_regions(clip),
|
||||
}
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live
|
||||
/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate.
|
||||
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
|
||||
let frame = |n: &Node| {
|
||||
let b = n.geometric_bounds()?;
|
||||
@@ -698,7 +857,7 @@ fn hit_children(
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p) {
|
||||
if !edited && !clip_contains(clip, p, opt.outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
match &n.kind {
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
@@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// group's original shapes, which the canvas does not draw, and guide paths with
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
|
||||
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
@@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole);
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
|
||||
if self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& clip_outline(&clip, self.p, self.opt).is_some()
|
||||
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p) {
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole) {
|
||||
if self.find(c, path, whole, outline) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
@@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
fn below_preview_off(doc: &Document, n: &Node, scope: Option<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(n.id) else { return false };
|
||||
let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off))
|
||||
}
|
||||
|
||||
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
|
||||
@@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
|
||||
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
|
||||
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
|
||||
/// picks it.
|
||||
/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it
|
||||
/// has any.
|
||||
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
|
||||
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
|
||||
symbol_part_outline_in_view(doc, inst, path, HitOptions::default())
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view
|
||||
/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the
|
||||
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
|
||||
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
|
||||
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
|
||||
/// the object leave no region.
|
||||
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
@@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, whole);
|
||||
outline = outline || previews_off(n);
|
||||
if i != 0
|
||||
&& n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
|
||||
{
|
||||
match meet(Some(clip), limit) {
|
||||
Some(r) => limit = Some(r),
|
||||
None => return Some(out),
|
||||
}
|
||||
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
|
||||
limit = within;
|
||||
}
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, whole)?, limit, &mut out);
|
||||
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the
|
||||
/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no
|
||||
/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art
|
||||
/// is drawn: the effects leave no region, or the box is outside `limit`.
|
||||
fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Option<Rect>> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let region = if outline { None } else { clip_region(clip) };
|
||||
let bounds = match region.as_deref() {
|
||||
Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()),
|
||||
Some(_) => return None,
|
||||
None => clip.geometric_bounds(),
|
||||
};
|
||||
match bounds {
|
||||
Some(b) => meet(Some(b), limit).map(Some),
|
||||
None => Some(limit),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
@@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let inner = match first.geometric_bounds() {
|
||||
Some(c) => match meet(Some(c), limit) {
|
||||
Some(r) => Some(r),
|
||||
None => return,
|
||||
},
|
||||
None => limit,
|
||||
};
|
||||
rest.iter().for_each(|c| outline_within(c, inner, out));
|
||||
let Some(inner) = limit_within(first, limit, outline) else { return };
|
||||
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, out));
|
||||
children.iter().for_each(|c| outline_within(c, limit, outline, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
@@ -1248,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
/// the selection tools' clicks.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false)
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
}
|
||||
|
||||
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
|
||||
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
|
||||
/// the clicks of [`HitOptions::outline`] do.
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true)
|
||||
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline)
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
fn previews_off(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { preview: false, .. })
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let mut out = Vec::new();
|
||||
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
|
||||
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
Some(c) => c
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None))
|
||||
.collect(),
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
@@ -1281,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, r))
|
||||
.flat_map(|l| layer_objects(l, r, outline))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
/// the sublayers it is in leave.
|
||||
fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc<Node>, Rect)> {
|
||||
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
|
||||
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
|
||||
/// shapes ([`mask_marquee`]).
|
||||
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
|
||||
let mut out = vec![];
|
||||
let Some(r) = marquee_in(l, r) else { return out };
|
||||
for c in l.children().into_iter().flatten() {
|
||||
let outline = outline || previews_off(l);
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
if c.visible && !c.locked && !c.is_template() {
|
||||
out.extend(layer_objects(c, r));
|
||||
if let Some(inner) = inner
|
||||
&& c.visible
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, inner, outline));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.push((c, r));
|
||||
if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r)));
|
||||
} else if inner.is_some() {
|
||||
out.push((c, inner, outline, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
|
||||
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
|
||||
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
|
||||
fn mask_marquee(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
/// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a
|
||||
/// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where
|
||||
/// the clip shows? Never in outline, nor without live effects: its own geometry counts then.
|
||||
fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool {
|
||||
if outline {
|
||||
return false;
|
||||
}
|
||||
clip_region(clip).is_some_and(|region| {
|
||||
region.as_ref().as_ref().is_some_and(|(bp, _)| {
|
||||
// The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let mut edge = PathData::from_bezpath(bp);
|
||||
edge.subpaths.iter_mut().for_each(|sp| sp.closed = true);
|
||||
vectorcraft_geom::hit::intersects_rect(&edge, r)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Is `n` collected whole by [`collect_leaves`], not by its members?
|
||||
fn is_leaf(n: &Node) -> bool {
|
||||
!matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. })
|
||||
}
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box.
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
marquee_in(n, r).is_some_and(|r| {
|
||||
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
}
|
||||
})
|
||||
}
|
||||
NodeKind::Compound { children, .. } if whole_compounds => {
|
||||
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A box with no width or no height (an instance of a symbol that draws a straight
|
||||
// line) is touched where the marquee crosses it.
|
||||
_ => n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
@@ -1325,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let Some(r) = marquee_in(n, r) else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, out);
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
continue;
|
||||
}
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else if let Some(r) = inner {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds) {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -1344,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r) in tops {
|
||||
for (t, r, outline, edge) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
}
|
||||
if leaves {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
|
||||
} else if touches(t, &symbols, r, scope, whole_compounds) {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
}
|
||||
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|
||||
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
|
||||
{
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
|
||||
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
|
||||
/// when the marquee misses it); otherwise it is all of `r`.
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
|
||||
/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`.
|
||||
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its
|
||||
/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline`
|
||||
/// ([`marquee_in_view`]).
|
||||
fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
match parent.children().and_then(|c| c.first()) {
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline),
|
||||
_ => Some(r),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of
|
||||
/// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip`
|
||||
/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those
|
||||
/// bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
|
||||
/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of
|
||||
/// those regions. Within those bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let regions = clip_regions(clip);
|
||||
let regions = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
// The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| {
|
||||
let mut edge = vectorcraft_geom::PathData::from_bezpath(bp);
|
||||
|
||||
@@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) {
|
||||
(mask, art)
|
||||
}
|
||||
|
||||
/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping
|
||||
/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip
|
||||
/// by; without either, no geometry effect.
|
||||
fn moved_clip_region(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
let (mut moves, mut empty) = (false, false);
|
||||
clip.walk(&mut |n| {
|
||||
moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move");
|
||||
empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty");
|
||||
});
|
||||
if empty {
|
||||
return Some(None);
|
||||
}
|
||||
if !moves {
|
||||
return None;
|
||||
}
|
||||
Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
|
||||
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
|
||||
(bp, rule)
|
||||
}))
|
||||
}
|
||||
|
||||
/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region.
|
||||
fn test_move() -> crate::Effect {
|
||||
crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// Clicks inside a clip group whose clipping path has a live effect fall in the region the
|
||||
/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and
|
||||
/// again after the clipping path changes; a clipping path without effects is not evaluated.
|
||||
#[test]
|
||||
fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
|
||||
for x in [148.0, 150.0, 152.0] {
|
||||
assert_eq!(leaf(&d, x), Some(art_id), "in the moved region");
|
||||
}
|
||||
assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place");
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Outline mode draws no effects: the art's edge shows within the clipping path's own shape.
|
||||
let outline = HitOptions { outline: true, ..HitOptions::default() };
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode");
|
||||
// So with a marquee across the art's left edge: in the view, only in Outline view. The
|
||||
// clipping path's own left edge lies there too, and counts in both.
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
|
||||
// `marquee_in` measures by the plain shapes, as its callers clip by them.
|
||||
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
|
||||
// Hidden, the effect no longer moves the region.
|
||||
d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false;
|
||||
assert_eq!(leaf(&d, 50.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 150.0), None);
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Shown again and widened, the region is evaluated again.
|
||||
let mask = d.node_mut(mask_id).unwrap();
|
||||
mask.appearance.effects[0].visible = true;
|
||||
if let NodeKind::Path { path, .. } = &mut mask.kind {
|
||||
*path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0));
|
||||
}
|
||||
assert_eq!(leaf(&d, 180.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 195.0), None);
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A marquee around a clipping path that an effect moved into the middle of large art touches the
|
||||
/// clipping path on the edge of its moved region, in a clip group and in a clipping layer.
|
||||
#[test]
|
||||
fn a_marquee_touches_a_moved_clipping_path_on_its_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let parts = |d: &mut Document| {
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art());
|
||||
(mask, art)
|
||||
};
|
||||
// Around the moved region (120..160) and the clipping path's own place, inside the art.
|
||||
let around = Rect::new(10.0, 10.0, 170.0, 70.0);
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let (g, mask_id) = (d.alloc_id(), mask.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [g]);
|
||||
assert_eq!(marquee(&d, around, None, true), [mask_id]);
|
||||
// Only over the clipping path's own place, the marquee misses the region but touches the
|
||||
// clipping path's anchors, which a click on its outline also finds.
|
||||
let own = Rect::new(10.0, 10.0, 70.0, 70.0);
|
||||
assert_eq!(marquee(&d, own, None, false), [g]);
|
||||
assert_eq!(marquee(&d, own, None, true), [mask_id]);
|
||||
// Away from both, nothing.
|
||||
assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty());
|
||||
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let mask_id = mask.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [mask_id]);
|
||||
}
|
||||
|
||||
/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point
|
||||
/// and marquees count its clipping path by its plain shape, without the effect that moves it.
|
||||
#[test]
|
||||
fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
// The art's top edge, within the clipping path's own shape.
|
||||
let p = Point::new(50.0, 0.5);
|
||||
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id));
|
||||
assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id));
|
||||
}
|
||||
|
||||
/// The pointer moving over empty canvas past more clip groups with live effects than the regions
|
||||
/// kept measures each group's box once: the boxes are kept for every clip group.
|
||||
#[test]
|
||||
fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..(2 * CLIPS_KEPT) {
|
||||
let x = 20.0 * i as f64;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(500.0, 500.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
for _ in 0..3 {
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
}
|
||||
assert_eq!(evaluated(), first);
|
||||
}
|
||||
|
||||
/// With more clip groups with live effects than the boxes kept, a new box replaces only as many
|
||||
/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions.
|
||||
#[test]
|
||||
fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let groups = CLIP_BOXES_KEPT + 64;
|
||||
let mut members = Vec::with_capacity(groups);
|
||||
for i in 0..groups {
|
||||
let x = (i % 100) as f64 * 5.0;
|
||||
let y = (i / 100) as f64 * 5.0;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default());
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
members.push(Arc::new(clip));
|
||||
}
|
||||
if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) {
|
||||
*children = members;
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(900.0, 900.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let again = evaluated() - first;
|
||||
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
|
||||
}
|
||||
|
||||
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
|
||||
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
|
||||
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
|
||||
/// whose Preview is off, which is clicked in outline while the layer above clips by its region.
|
||||
#[test]
|
||||
fn every_clip_test_follows_the_moved_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0));
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.insert(Some(l), 0, outer.clone()).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place");
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region");
|
||||
let symbols = d.symbol_boxes();
|
||||
assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill));
|
||||
assert_eq!(hit_any(&outer, own, opt, &symbols), None);
|
||||
d.node_mut(art_id).unwrap().locked = true;
|
||||
assert_eq!(locked_objects_at(&d, moved, opt), [art_id]);
|
||||
assert!(locked_objects_at(&d, own, opt).is_empty());
|
||||
|
||||
// A clipping layer holding the mask and a sublayer whose Preview is off, with the art.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *preview) = (vec![Arc::new(art)], false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
d.insert(Some(top), 0, mask).unwrap();
|
||||
d.node_mut(top).unwrap().set_clips(true);
|
||||
// The art's top edge, at the clipping path's own place and in the moved region.
|
||||
let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5));
|
||||
assert!(hit_test(&d, own, opt).is_none());
|
||||
assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None);
|
||||
}
|
||||
|
||||
/// The art a mask hides counts only for a selected object: there a click hits nothing, and the
|
||||
/// selection tools grab the selection by that art. Not where the art shows (the click hits it),
|
||||
/// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked,
|
||||
@@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect
|
||||
/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and
|
||||
/// when Preview is off for the layer in the art or for the layer the instance is on, the plain
|
||||
/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline.
|
||||
#[test]
|
||||
fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that
|
||||
// layer and of the document layer the instance is on.
|
||||
let instance = |effect: &str, preview: [bool; 2]| {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
|
||||
*p = preview[1];
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind {
|
||||
(*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]);
|
||||
}
|
||||
layer.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
(d, inst)
|
||||
};
|
||||
let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| {
|
||||
let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap();
|
||||
vectorcraft_geom::kurbo::Shape::bounding_box(&o)
|
||||
};
|
||||
let opt = HitOptions::default();
|
||||
let (d, inst) = instance("test.move", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}");
|
||||
let b = outline_box(&d, inst, HitOptions { outline: true, ..opt });
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}");
|
||||
// With Preview off, the art's top edge counts within the plain clipping path.
|
||||
for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] {
|
||||
let (d, inst) = instance("test.move", preview);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}");
|
||||
}
|
||||
// An effect that leaves the clipping path no region hides the art: no pick and no outline.
|
||||
let (d, inst) = instance("test.empty", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None);
|
||||
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
@@ -55,6 +55,7 @@ mod pixels;
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
|
||||
pub mod placed_document;
|
||||
pub mod plugin_data;
|
||||
pub mod ppi;
|
||||
pub mod profiles;
|
||||
pub mod puppet;
|
||||
pub mod range;
|
||||
|
||||
@@ -211,7 +211,9 @@ impl Node {
|
||||
|
||||
/// A quick box round everything the object can paint, for culling clicks: paths and compound
|
||||
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
|
||||
/// clipping layer's box takes in the region that the live geometry effects of its clipping
|
||||
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
|
||||
@@ -261,6 +263,11 @@ impl Node {
|
||||
NodeKind::Blend { children, spec } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
|
||||
}
|
||||
// The live geometry effects of a clipping path can move or grow the region it clips to
|
||||
// past its plain shape ([`crate::hit::set_clip_region`]).
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`,
|
||||
//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image
|
||||
//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]).
|
||||
|
||||
const INCH_M: f64 = 0.0254;
|
||||
const INCH_CM: f64 = 2.54;
|
||||
|
||||
/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads?
|
||||
pub fn reads(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|
||||
|| bytes.starts_with(&[0xff, 0xd8])
|
||||
|| bytes.starts_with(b"II*\0")
|
||||
|| bytes.starts_with(b"MM\0*")
|
||||
|| (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP")
|
||||
|| bytes.starts_with(b"BM")
|
||||
}
|
||||
|
||||
/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each
|
||||
/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files.
|
||||
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
png(bytes)
|
||||
} else if bytes.starts_with(&[0xff, 0xd8]) {
|
||||
jpeg(bytes)
|
||||
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
|
||||
tiff(bytes)
|
||||
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||
webp(bytes)
|
||||
} else if bytes.starts_with(b"BM") {
|
||||
bmp(bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
|
||||
}
|
||||
|
||||
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
|
||||
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
|
||||
b.get(at..at.checked_add(n)?)
|
||||
}
|
||||
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
|
||||
slice(b, at, N)?.try_into().ok()
|
||||
}
|
||||
fn be16(b: &[u8], at: usize) -> Option<u16> {
|
||||
bytes(b, at).map(u16::from_be_bytes)
|
||||
}
|
||||
fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
bytes(b, at).map(u32::from_be_bytes)
|
||||
}
|
||||
fn le32(b: &[u8], at: usize) -> Option<u32> {
|
||||
bytes(b, at).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
|
||||
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
|
||||
fn per_metre(ppm: u32) -> f64 {
|
||||
let v = ppm as f64 * INCH_M;
|
||||
let whole = v.round();
|
||||
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
|
||||
}
|
||||
|
||||
/// PNG chunks after the signature: (type, data).
|
||||
pub fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
|
||||
let mut at = 8;
|
||||
std::iter::from_fn(move || {
|
||||
let len = be32(b, at)? as usize;
|
||||
let ty = slice(b, at + 4, 4)?;
|
||||
let data = slice(b, at + 8, len)?;
|
||||
at = at.checked_add(12 + len)?;
|
||||
Some((ty, data))
|
||||
})
|
||||
}
|
||||
|
||||
fn png(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
|
||||
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
|
||||
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
|
||||
}
|
||||
|
||||
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let (mut jfif, mut exif) = (None, None);
|
||||
let mut at = 2;
|
||||
while at + 4 <= b.len() && b[at] == 0xff {
|
||||
let marker = b[at + 1];
|
||||
// 0xff fill bytes pad between segments.
|
||||
if marker == 0xff {
|
||||
at += 1;
|
||||
continue;
|
||||
}
|
||||
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
// Start of scan or end of image: no more metadata.
|
||||
if marker == 0xda || marker == 0xd9 {
|
||||
break;
|
||||
}
|
||||
let len = be16(b, at + 2)? as usize;
|
||||
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
|
||||
match marker {
|
||||
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
|
||||
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
|
||||
jfif = match seg[7] {
|
||||
1 => Some((x, y)),
|
||||
2 => Some((x * INCH_CM, y * INCH_CM)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
|
||||
_ => {}
|
||||
}
|
||||
at += 2 + len;
|
||||
}
|
||||
jfif.or(exif)
|
||||
}
|
||||
|
||||
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi
|
||||
/// in the stored pixels' axes, unchecked; `None` without an absolute unit.
|
||||
pub fn tiff(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let le = b.starts_with(b"II");
|
||||
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
|
||||
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
|
||||
let ifd = u32_at(4)? as usize;
|
||||
let (mut x, mut y, mut unit) = (None, None, 2);
|
||||
for i in 0..u16_at(ifd)? as usize {
|
||||
let e = ifd.checked_add(2 + i * 12)?;
|
||||
let rational = || -> Option<f64> {
|
||||
let at = u32_at(e + 8)? as usize;
|
||||
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
|
||||
(d != 0).then(|| n as f64 / d as f64)
|
||||
};
|
||||
match u16_at(e)? {
|
||||
282 => x = rational(),
|
||||
283 => y = rational(),
|
||||
296 => unit = u16_at(e + 8)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let k = match unit {
|
||||
2 => 1.0,
|
||||
3 => INCH_CM,
|
||||
_ => return None,
|
||||
};
|
||||
let x = x?;
|
||||
Some((x * k, y.unwrap_or(x) * k))
|
||||
}
|
||||
|
||||
fn webp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut at = 12;
|
||||
while at + 8 <= b.len() {
|
||||
let len = le32(b, at + 4)? as usize;
|
||||
let data = slice(b, at + 8, len)?;
|
||||
if &b[at..at + 4] == b"EXIF" {
|
||||
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
|
||||
}
|
||||
at += 8 + len + (len & 1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
|
||||
if le32(b, 14)? < 40 {
|
||||
return None;
|
||||
}
|
||||
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
|
||||
Some((ppm(38)?, ppm(42)?))
|
||||
}
|
||||
|
||||
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
|
||||
pub fn pixels_per_metre(ppi: f64) -> u32 {
|
||||
(ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32
|
||||
}
|
||||
|
||||
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
|
||||
fn crc32(parts: &[&[u8]]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in parts.iter().flat_map(|p| p.iter()) {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
|
||||
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
|
||||
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
|
||||
// x, y, unit 1 = metre.
|
||||
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
|
||||
let mut out = Vec::with_capacity(21);
|
||||
out.extend_from_slice(&9u32.to_be_bytes());
|
||||
out.extend_from_slice(b"pHYs");
|
||||
out.extend_from_slice(&data);
|
||||
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
|
||||
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
|
||||
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
|
||||
let chunk = phys_chunk(x, y);
|
||||
let mut out = Vec::with_capacity(png.len() + chunk.len());
|
||||
out.extend_from_slice(head);
|
||||
out.extend_from_slice(&chunk);
|
||||
let mut at = head.len();
|
||||
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
|
||||
if chunk.get(4..8) != Some(b"pHYs") {
|
||||
out.extend_from_slice(chunk);
|
||||
}
|
||||
at += chunk.len();
|
||||
}
|
||||
out.extend_from_slice(png.get(at..).unwrap_or_default());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn png_of(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there.
|
||||
#[test]
|
||||
fn a_png_takes_its_resolution_and_still_decodes() {
|
||||
let png = png_of(4, 3);
|
||||
assert_eq!(resolution(&png), None);
|
||||
let tagged = with_png_resolution(&png, (300.0, 150.0));
|
||||
assert_eq!(resolution(&tagged), Some((300.0, 150.0)));
|
||||
let again = with_png_resolution(&tagged, (72.0, 72.0));
|
||||
assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated");
|
||||
assert_eq!(again.len(), tagged.len());
|
||||
let img = image::load_from_memory(&again).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (4, 3));
|
||||
// Every PNG ends with this IEND chunk CRC.
|
||||
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
|
||||
}
|
||||
|
||||
/// RIFF chunk `ty` holding `data`, padded to an even length.
|
||||
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
|
||||
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
|
||||
if data.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn webp_of(chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
let body = chunks.concat();
|
||||
let size = u32::try_from(body.len() + 4).unwrap();
|
||||
[b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat()
|
||||
}
|
||||
|
||||
/// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose
|
||||
/// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to
|
||||
/// an offset) gives no resolution.
|
||||
#[test]
|
||||
fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() {
|
||||
// Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch.
|
||||
let mut tiff = b"II*\0".to_vec();
|
||||
tiff.extend_from_slice(&8u32.to_le_bytes());
|
||||
tiff.extend_from_slice(&2u16.to_le_bytes());
|
||||
for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] {
|
||||
tiff.extend_from_slice(&tag.to_le_bytes());
|
||||
tiff.extend_from_slice(&ty.to_le_bytes());
|
||||
tiff.extend_from_slice(&1u32.to_le_bytes());
|
||||
tiff.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
tiff.extend_from_slice(&0u32.to_le_bytes());
|
||||
tiff.extend_from_slice(&300u32.to_le_bytes());
|
||||
tiff.extend_from_slice(&1u32.to_le_bytes());
|
||||
let exif = [b"Exif\0\0".as_slice(), &tiff].concat();
|
||||
let exif_len = u32::try_from(exif.len()).unwrap();
|
||||
let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]);
|
||||
assert_eq!(resolution(&ok), Some((300.0, 300.0)));
|
||||
|
||||
for len in [u32::MAX, u32::MAX - 7, 1_000] {
|
||||
let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]);
|
||||
assert_eq!(resolution(&bad), None, "chunk length {len}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -476,14 +476,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
|
||||
/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the
|
||||
/// pieces copied from the source keep the source's ids until then). The pieces are baked with the
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id.
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When
|
||||
/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the
|
||||
/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]).
|
||||
fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
|
||||
let mut seen = std::collections::HashSet::from([m.id]);
|
||||
let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_))));
|
||||
let children = m.children().cloned().unwrap_or_default();
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let c = Arc::unwrap_or_clone(c);
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c));
|
||||
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
|
||||
fresh_ids(d, &mut c, &mut seen);
|
||||
Arc::new(c)
|
||||
|
||||
@@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData};
|
||||
/// fills and strokes: the region is then the union of the paths they give, as an export bakes them.
|
||||
/// `None` when there is nothing to clip by (the clipped art is then hidden).
|
||||
pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
|
||||
match clip_effects_applied(clip, true, || true) {
|
||||
Some(m) => m.clip_outline(Some(&outline_text), &unite),
|
||||
None => clip.clip_outline(Some(&outline_text), &unite),
|
||||
}
|
||||
reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing
|
||||
/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a
|
||||
/// group or layer does not clip, so its effects are not counted.
|
||||
pub fn reshaped_clip_outline(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by
|
||||
|
||||
@@ -72,7 +72,7 @@ pub use bake::{
|
||||
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
|
||||
fresh_ids, needs_bake,
|
||||
};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -6,7 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::WireFace;
|
||||
use crate::solids::{
|
||||
@@ -338,34 +338,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
|
||||
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
|
||||
/// the surface it is cast from is past the limits.
|
||||
fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> {
|
||||
///
|
||||
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
|
||||
/// surface is swept again for its shadow alone.
|
||||
fn shadow_of(
|
||||
id: NodeId,
|
||||
fx: &Effect,
|
||||
path: &PathData,
|
||||
item: &AppearanceItem,
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Option<SolidFaces>,
|
||||
) -> Result<Option<Node>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
|
||||
let (_, opacity, blend) = paint_of(item);
|
||||
if opacity <= 0.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?;
|
||||
cast_surface(&mut caster, path, b, options, kept)?;
|
||||
Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend }))
|
||||
}
|
||||
|
||||
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
|
||||
/// its shadow is cast from ([`surface`])?
|
||||
fn casts(fx: &Effect, opacity: f32) -> bool {
|
||||
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
}
|
||||
|
||||
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
|
||||
/// drawn, or without them, the surface swept for its shadow alone.
|
||||
fn cast_surface(
|
||||
caster: &mut vectorcraft_three_d::ShadowCaster,
|
||||
path: &PathData,
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Option<SolidFaces>,
|
||||
) -> Result<std::ops::Range<usize>, String> {
|
||||
match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one,
|
||||
/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque,
|
||||
/// in its paint's blending mode, and its opacity mask and blending mode apply to that part
|
||||
/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the
|
||||
/// limits.
|
||||
fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> {
|
||||
/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow
|
||||
/// ([`surface`]); a member without them is swept again for its shadow alone.
|
||||
fn group_shadow(
|
||||
id: NodeId,
|
||||
fx: &Effect,
|
||||
shapes: &[Profile],
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Vec<Option<SolidFaces>>,
|
||||
) -> Result<Vec<Arc<Node>>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) };
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast = vec![];
|
||||
let mut kept = kept.into_iter();
|
||||
for s in shapes {
|
||||
let kept = kept.next().flatten();
|
||||
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
|
||||
// A member whose surface is fully transparent casts nothing.
|
||||
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?;
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
|
||||
@@ -377,7 +423,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
|
||||
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part.
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
@@ -391,11 +438,18 @@ fn surface(
|
||||
blend: vectorcraft_doc::color::BlendMode,
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
) -> Option<(Vec<Drawn>, Node)> {
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
// of crashing the frame. Commands validate the same evaluator and report its errors.
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
|
||||
let (facets, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
@@ -405,10 +459,14 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p)));
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
|
||||
let (faces, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
@@ -532,7 +590,7 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group))
|
||||
Some((keys, group, kept))
|
||||
}
|
||||
|
||||
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
|
||||
@@ -549,8 +607,9 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
|
||||
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
|
||||
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
|
||||
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
|
||||
/// [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
@@ -559,10 +618,11 @@ fn object_surface(
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
) -> Option<Node> {
|
||||
) -> Option<(Node, Option<SolidFaces>)> {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
@@ -692,7 +752,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
}
|
||||
return Ok((out, group_shadow(n.id, fx, &shapes, b, options)?));
|
||||
return Ok((out, group_shadow(n.id, fx, &shapes, b, options, vec![])?));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -703,7 +763,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx))?;
|
||||
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)?;
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -764,9 +824,9 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
@@ -790,10 +850,10 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
shadows.push(Arc::new(shadow));
|
||||
@@ -942,21 +1002,28 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = Copies::default();
|
||||
let mut surfaces = vec![];
|
||||
// The faces each member's surface kept for the shadow, member by member.
|
||||
let mut kept = vec![];
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
|
||||
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let Some(item) = surface_item(&s.items) else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
}
|
||||
if surfaces.is_empty() {
|
||||
return None;
|
||||
@@ -1057,7 +1124,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
};
|
||||
// One shadow for every member's surface, behind them all.
|
||||
let mut children = children;
|
||||
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
|
||||
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?);
|
||||
let remaining = past_effect(&n.appearance.effects, index);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children, clip: false };
|
||||
@@ -1682,6 +1749,67 @@ mod tests {
|
||||
}
|
||||
assert_eq!(expand_revolve_art(&sample), revolve_art(&sample));
|
||||
}
|
||||
|
||||
/// The settings the shadows are compared with: the defaults, a partial sweep turned with
|
||||
/// perspective, and an open surface away from its axis under a colored light.
|
||||
fn shadow_settings() -> [Value; 3] {
|
||||
[
|
||||
json!({"shadow": true}),
|
||||
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}),
|
||||
json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}),
|
||||
]
|
||||
}
|
||||
|
||||
/// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces,
|
||||
/// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an
|
||||
/// object whose fill is half transparent, and for a group of two members, one at half opacity.
|
||||
#[test]
|
||||
fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() {
|
||||
for id in [REVOLVE, CLASSIC_REVOLVE] {
|
||||
for params in shadow_settings() {
|
||||
// Revolve (Classic) takes no shadow settings from commands, but a file can carry them.
|
||||
let mut fx = crate::new_effect(id, &json!({})).unwrap();
|
||||
fx.params = params.clone();
|
||||
let n = profile_node();
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let mut half = n.clone();
|
||||
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
for n in [n, half] {
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
|
||||
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
let mut other = profile_node();
|
||||
other.id = NodeId(2);
|
||||
other.transform(Affine::translate((120.0, 0.0)), false);
|
||||
other.opacity = 0.5;
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
let shapes = members(&g, "").unwrap();
|
||||
let b = union_bounds(&shapes).unwrap();
|
||||
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
|
||||
let kept: Vec<Option<SolidFaces>> = shapes
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
assert!(kept.iter().all(Option::is_some), "{id} {params}");
|
||||
let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap();
|
||||
let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap();
|
||||
assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+197
-67
@@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View};
|
||||
use vectorcraft_three_d::{
|
||||
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
|
||||
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
|
||||
/// classic effects cast no shadow: they keep no faces.
|
||||
fn facets_and_faces(
|
||||
id: &str,
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
bounds: Rect,
|
||||
p: &Value,
|
||||
cast: bool,
|
||||
) -> Result<(Vec<Facet>, Option<SolidFaces>), String> {
|
||||
let view = view_options(p);
|
||||
#[cfg(test)]
|
||||
if cast && id == EXTRUDE {
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
let built = match id {
|
||||
EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view),
|
||||
ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view),
|
||||
_ => return facets(id, path, rule, bounds, p).map(|f| (f, None)),
|
||||
};
|
||||
built.map(|(f, faces)| (f, Some(faces)))
|
||||
}
|
||||
|
||||
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
|
||||
/// need the object.
|
||||
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
@@ -693,7 +719,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests.
|
||||
static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
@@ -712,10 +740,35 @@ fn built_solids<'a>(
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
|
||||
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
|
||||
}
|
||||
|
||||
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
|
||||
type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
|
||||
|
||||
/// The surfaces of an object's solids, and the faces each solid kept for its shadow
|
||||
/// ([`surfaces_for`]).
|
||||
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
|
||||
|
||||
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
|
||||
/// is cast from, from the same build ([`SolidFaces`]).
|
||||
fn built_solids_cast<'a>(
|
||||
id: &'a str,
|
||||
p: &'a Value,
|
||||
parts: &'a [Part<'a>],
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
cast: bool,
|
||||
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
|
||||
// Inflate's eye is placed for every puff together, as far away as the highest needs.
|
||||
let mut inflated = (id == INFLATE).then(|| {
|
||||
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p))
|
||||
let (o, view) = (inflate_options(p), view_options(p));
|
||||
if cast {
|
||||
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
|
||||
} else {
|
||||
Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None))))
|
||||
}
|
||||
});
|
||||
let mut kept = 0usize;
|
||||
let mut ended = false;
|
||||
@@ -729,13 +782,13 @@ fn built_solids<'a>(
|
||||
Some(each) => {
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
each.next().unwrap_or_else(|| Ok(vec![]))
|
||||
each.next().unwrap_or_else(|| Ok((vec![], None)))
|
||||
}
|
||||
None => facets(id, area, *rule, bounds, p),
|
||||
None => facets_and_faces(id, area, *rule, bounds, p, cast),
|
||||
};
|
||||
let result = match built {
|
||||
Ok(f) => {
|
||||
kept = kept.saturating_add(f.len());
|
||||
kept = kept.saturating_add(f.0.len());
|
||||
if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) }
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None),
|
||||
@@ -1364,12 +1417,19 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
|
||||
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
|
||||
/// off), to be drawn behind every surface of the object, and the surfaces.
|
||||
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
|
||||
/// surface of the object, and the surfaces.
|
||||
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
let art = surfaces_for(doc, n, fx, shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
let shadow = shadow_for(n.id, fx, shapes).ok()?;
|
||||
let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) };
|
||||
let shadow = match shadow.ok()? {
|
||||
Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)),
|
||||
None => vec![],
|
||||
};
|
||||
Some((shadow, art))
|
||||
}
|
||||
|
||||
@@ -1408,6 +1468,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
for s in shapes {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let faces = caster.plane(&area, rule, b, view)?;
|
||||
cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces));
|
||||
}
|
||||
@@ -1419,10 +1481,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
|
||||
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
@@ -1444,6 +1510,76 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
Ok(Some((caster, settings, cast)))
|
||||
}
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
let (_, opacity, blend) = paint_of(item, member);
|
||||
shadow::Ink { opacity, blend }
|
||||
};
|
||||
if id == ROTATE {
|
||||
let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect();
|
||||
if items.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for ((s, item), kept) in items.into_iter().zip(built) {
|
||||
let ink = ink(item, s.opacity);
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
cast.push((*scopes, ink, faces));
|
||||
}
|
||||
Ok(Some((caster, settings, cast)))
|
||||
}
|
||||
|
||||
/// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with
|
||||
/// its member's scopes and ink ([`cast_shadow`]).
|
||||
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
|
||||
@@ -1502,31 +1638,31 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool {
|
||||
colored && crate::lighting::opaque_paint(paint).1.is_some()
|
||||
}
|
||||
|
||||
/// A graphic of [`placed_graphics`]: the index of the first surface of the solids that share it,
|
||||
/// the index of the surface it is drawn right after, its face and its art.
|
||||
type Placement = (usize, usize, PlanarFace, Arc<Node>);
|
||||
|
||||
/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is
|
||||
/// drawn right after (the last of those solids holding its face) and its face. Solids in a run
|
||||
/// with the same opacity and blending mode share their graphics. With `per_member`
|
||||
/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get
|
||||
/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes.
|
||||
/// All the groups share one limit on the path elements drawn: once it is reached, later groups
|
||||
/// draw no graphics.
|
||||
fn placed_graphics(
|
||||
doc: Option<&Document>,
|
||||
id: NodeId,
|
||||
effect: (&str, &Value),
|
||||
bounds: Rect,
|
||||
filled: &[Filled],
|
||||
per_member: bool,
|
||||
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
|
||||
/// with the same opacity and blending mode share their graphics, one on each face. With
|
||||
/// `per_member` (a member's opacity mask or blending mode applies to its surfaces) each member's
|
||||
/// solids get graphics of their own, clipped to that member's caps, so they stay in that member's
|
||||
/// scopes. All the groups share one limit on the path elements drawn: once it is reached, later
|
||||
/// groups draw no graphics.
|
||||
fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), bounds: Rect, filled: &[Filled], per_member: bool) -> Vec<Placement> {
|
||||
let mut groups: Vec<Vec<&Filled>> = vec![];
|
||||
for f in filled {
|
||||
// Solids whose fills or strokes differ in opacity or blending mode get graphics of their
|
||||
// own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask
|
||||
// gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the
|
||||
// group of the solid before it, so a graphic is never drawn past a solid painted between.
|
||||
let joins = |first: &Filled| {
|
||||
(!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked
|
||||
// own, each drawn as its fill or stroke is. One member's solids share their graphics
|
||||
// whether or not their surfaces carry an opacity mask, and each graphic takes the mask of
|
||||
// the surface it is drawn after ([`with_graphics`]). Solids of different members share
|
||||
// them only when neither surface carries a mask. A solid joins only the group of the solid
|
||||
// before it, so a graphic is never drawn past a solid painted between.
|
||||
let joins = |g: &&Filled| {
|
||||
let member = g.member == f.member;
|
||||
(member || !per_member && !g.masked && !f.masked) && g.opacity == f.opacity && g.blend == f.blend
|
||||
};
|
||||
match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) {
|
||||
match groups.last_mut().filter(|g| g.iter().all(joins)) {
|
||||
Some(g) => g.push(f),
|
||||
None => groups.push(vec![f]),
|
||||
}
|
||||
@@ -1535,12 +1671,13 @@ fn placed_graphics(
|
||||
let mut elements = 0usize;
|
||||
for group in groups {
|
||||
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
|
||||
let first = group.first().map_or(0, |f| f.at);
|
||||
let opacity = group.first().map_or(1.0, |f| f.opacity);
|
||||
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
|
||||
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
|
||||
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
|
||||
Arc::make_mut(&mut art).blend = blend;
|
||||
out.push((f.at, face, art));
|
||||
out.push((first, f.at, face, art));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1552,23 +1689,19 @@ fn placed_graphics(
|
||||
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
|
||||
|
||||
/// [`with_graphics`] of built surfaces, each drawn whole.
|
||||
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[Placement]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts)
|
||||
}
|
||||
|
||||
/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts`
|
||||
/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes
|
||||
/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is.
|
||||
fn with_graphics<'s>(
|
||||
surfaces: Vec<(&'s [Scope], Arc<Node>)>,
|
||||
first: usize,
|
||||
arts: &[(usize, PlanarFace, Arc<Node>)],
|
||||
) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, first: usize, arts: &[Placement]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
|
||||
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
|
||||
let mask = s.extras().mask.clone();
|
||||
out.push((scopes, s));
|
||||
out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| {
|
||||
out.extend(arts.iter().filter(|(_, at, ..)| *at == first + k).map(|(.., art)| {
|
||||
let mut art = art.clone();
|
||||
if let Some(mask) = &mask {
|
||||
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
|
||||
@@ -1585,8 +1718,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
|
||||
}
|
||||
|
||||
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
|
||||
/// faces drawn right after the last of the solids' surfaces that holds that face.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each
|
||||
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
|
||||
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
|
||||
@@ -1601,11 +1736,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
// the centre of theirs), so they stay together.
|
||||
let mut out = vec![];
|
||||
let mut filled = vec![];
|
||||
let mut built = vec![];
|
||||
for (member, s) in shapes.iter().enumerate() {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, blend) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?;
|
||||
built.push(faces);
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
@@ -1622,19 +1761,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
}
|
||||
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
|
||||
let out = with_graphics(out, 0, &arts);
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let mut solids = vec![];
|
||||
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) {
|
||||
let mut built = vec![];
|
||||
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
|
||||
let item: &AppearanceItem = item;
|
||||
match f {
|
||||
Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
return None;
|
||||
}
|
||||
Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)),
|
||||
Ok(Some((f, faces))) => {
|
||||
solids.push((item, *opacity, *scopes, f, *member));
|
||||
built.push(faces);
|
||||
}
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws.
|
||||
Ok(None) => {}
|
||||
Ok(None) => built.push(None),
|
||||
// A loaded file or a shape edited past the limits (its own, or those of the object's
|
||||
// solids together) keeps drawing its source path instead of failing the frame;
|
||||
// commands validate the same evaluator and report its errors.
|
||||
@@ -1763,14 +1906,14 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
out.extend(with_graphics(run.collect(), first, &arts));
|
||||
}
|
||||
}
|
||||
return Some(masked(n.id, out));
|
||||
return Some((masked(n.id, out), built));
|
||||
}
|
||||
if !opaque || !surfaces.iter().all(plain) {
|
||||
let surfaces =
|
||||
surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect();
|
||||
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
|
||||
return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built));
|
||||
}
|
||||
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))])
|
||||
Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built))
|
||||
}
|
||||
|
||||
/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when
|
||||
@@ -1793,16 +1936,9 @@ fn underlaid_surface(id: NodeId, surface: Node, seal: bool) -> Node {
|
||||
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
|
||||
/// The faces of the surfaces that `seals` marks lie over underlays of themselves
|
||||
/// ([`underlaid_runs`], [`underlaid_surface`]).
|
||||
fn in_one_order(
|
||||
id: NodeId,
|
||||
surfaces: Vec<BuiltSurface<'_>>,
|
||||
first: usize,
|
||||
arts: &[(usize, PlanarFace, Arc<Node>)],
|
||||
sealed: bool,
|
||||
seals: &[bool],
|
||||
) -> Vec<Arc<Node>> {
|
||||
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[Placement], sealed: bool, seals: &[bool]) -> Vec<Arc<Node>> {
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
|
||||
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect();
|
||||
let arts: Vec<&Placement> = arts.iter().filter(|(_, at, ..)| (first..first + surfaces.len()).contains(at)).collect();
|
||||
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
|
||||
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
@@ -1813,24 +1949,18 @@ fn in_one_order(
|
||||
}
|
||||
let order = draw_order(&placed, sealed);
|
||||
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
|
||||
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
|
||||
// mask that ends at its surface.
|
||||
// share it ([`placed_graphics`]): those from the first of them to its own.
|
||||
let last: Vec<Option<usize>> = arts
|
||||
.iter()
|
||||
.map(|(at, face, _)| {
|
||||
let at = at - first;
|
||||
let from = if masks.get(at).is_some_and(Option::is_some) {
|
||||
at
|
||||
} else {
|
||||
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
|
||||
};
|
||||
.map(|(from, at, face, _)| {
|
||||
let (from, at) = (from.saturating_sub(first), at - first);
|
||||
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
|
||||
})
|
||||
.collect();
|
||||
let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len());
|
||||
for (at, k) in order.into_iter().enumerate() {
|
||||
drawn.extend(faces.get_mut(k).and_then(Option::take));
|
||||
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
|
||||
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| {
|
||||
let mut art = art.clone();
|
||||
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
|
||||
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
|
||||
|
||||
@@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
|
||||
};
|
||||
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
|
||||
assert_eq!(masks(&art), vec![true]);
|
||||
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
|
||||
// and the stroke's outline gets an unmasked one.
|
||||
// With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn
|
||||
// after the stroke's cap as for a fill without a mask, and it takes the stroke's surface,
|
||||
// which carries no mask.
|
||||
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
|
||||
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
|
||||
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]);
|
||||
}
|
||||
|
||||
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
|
||||
@@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many
|
||||
/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and
|
||||
/// its blending mode.
|
||||
fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> {
|
||||
fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
|
||||
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
|
||||
p.path_data().is_some()
|
||||
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
|
||||
}),
|
||||
_ => false,
|
||||
});
|
||||
if graphic {
|
||||
out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend));
|
||||
} else if children.first().and_then(|c| c.path_data()).is_some() {
|
||||
*faces += 1;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)),
|
||||
_ => *faces += usize::from(n.path_data().is_some()),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(art, &mut 0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
|
||||
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
|
||||
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
|
||||
/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops:
|
||||
/// after the stroke's cap, without a mask.
|
||||
#[test]
|
||||
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
|
||||
let solid = |graphics: Value| {
|
||||
// A red gradient whose last stop has opacity `last`.
|
||||
let gradient = |last: f32| {
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = last;
|
||||
GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))
|
||||
};
|
||||
let solid = |fill: &GradientPaint, graphics: Value| {
|
||||
let mut n = object(
|
||||
EXTRUDE,
|
||||
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
|
||||
);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient.clone()));
|
||||
f.paint = Paint::Gradient(Box::new(fill.clone()));
|
||||
}
|
||||
// A gradient stroke: a solid color under the colored light would be one composite.
|
||||
let blues = Gradient::new(
|
||||
@@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
|
||||
n.appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
solid_art_in(Some(&d), &n).unwrap()
|
||||
};
|
||||
let with = solid(json!([{"symbol": "Mark"}]));
|
||||
let without = solid(json!([]));
|
||||
let masked = gradient(0.25);
|
||||
let with = solid(&masked, json!([{"symbol": "Mark"}]));
|
||||
let without = solid(&masked, json!([]));
|
||||
assert!(face_paths(&without).len() > 20, "the faces are found");
|
||||
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
|
||||
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
|
||||
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
|
||||
let mut masked = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& let [_, inner] = children.as_slice()
|
||||
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
|
||||
&& paths.iter().any(|p| {
|
||||
p.appearance.items.iter().any(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
|
||||
AppearanceItem::Stroke(_) => false,
|
||||
})
|
||||
})
|
||||
{
|
||||
masked.push(c.extras().mask.is_some());
|
||||
}
|
||||
});
|
||||
masked.sort_unstable();
|
||||
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
|
||||
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
|
||||
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
|
||||
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
|
||||
let mut drawn: Vec<(&str, Rect)> = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& c.extras().mask.is_some()
|
||||
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
|
||||
{
|
||||
drawn.push(("graphic", bounds));
|
||||
}
|
||||
let first_stop = c.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => match &f.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
|
||||
_ => None,
|
||||
},
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
|
||||
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
|
||||
}
|
||||
});
|
||||
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
|
||||
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
|
||||
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
|
||||
let mut mask = false;
|
||||
with.walk(&mut |c| mask |= c.extras().mask.is_some());
|
||||
assert!(mask, "the fill's faces carry the gradient's mask");
|
||||
let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}]));
|
||||
assert_eq!(face_paths(&opaque), face_paths(&with));
|
||||
let places = graphic_places(&with);
|
||||
assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::<Vec<_>>(), [(false, 1.0, BlendMode::Normal)]);
|
||||
assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it");
|
||||
}
|
||||
|
||||
/// A plane in a gradient with transparent stops under a colored light draws its graphic with the
|
||||
/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask.
|
||||
#[test]
|
||||
fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
|
||||
let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient));
|
||||
}
|
||||
let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap());
|
||||
assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::<Vec<_>>(), [true]);
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
|
||||
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
n.appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
let art = solid_art_in(Some(&d), &n).unwrap();
|
||||
let places = graphic_places(&art);
|
||||
assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face");
|
||||
}
|
||||
|
||||
/// Members of a group share a graphic only when neither surface carries an opacity mask, while
|
||||
/// one member's fill and stroke share theirs.
|
||||
#[test]
|
||||
fn members_in_transparent_gradients_keep_graphics_of_their_own() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]))));
|
||||
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
|
||||
let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0));
|
||||
// Whether each graphic drawn on the group of `members` carries an opacity mask, in order.
|
||||
let masks = |members: Vec<Node>| {
|
||||
let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect());
|
||||
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
|
||||
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
|
||||
let mut masks: Vec<bool> = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect();
|
||||
masks.sort_unstable();
|
||||
masks
|
||||
};
|
||||
assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]);
|
||||
// With a dashed stroke, the first member's fill and stroke share one graphic, without a mask.
|
||||
let mut stroked = square(1, left, gradient.clone());
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0);
|
||||
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
stroked.appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]);
|
||||
// A member with a gray stroke listed before its fill in the gradient does not share its
|
||||
// graphic with the gray member after it.
|
||||
let mut layered = square(1, left, gradient);
|
||||
layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0)));
|
||||
assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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, ¶ms).into_iter().zip(shadowed(id, ¶ms)) {
|
||||
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, ¶ms) {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() {
|
||||
assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() {
|
||||
// A clip group with a fill or a stroke of its own and no effects: the export turns its paint
|
||||
// into art and still clips by the outline the canvas clips by, Transform copies included.
|
||||
let items = [
|
||||
vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)),
|
||||
];
|
||||
let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1}));
|
||||
let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}));
|
||||
// A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`.
|
||||
let ring = |hole_fx: Vec<Effect>, own: Vec<Effect>| {
|
||||
let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default());
|
||||
let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default());
|
||||
hole.appearance.effects = hole_fx;
|
||||
let mut c =
|
||||
Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd });
|
||||
c.appearance.effects = own;
|
||||
c
|
||||
};
|
||||
let clips = [
|
||||
("copies", clipping_path(2, vec![copies()])),
|
||||
("roughen", clipping_path(2, vec![roughen])),
|
||||
("a compound path's copies", ring(vec![], vec![copies()])),
|
||||
("a compound path member's copies", ring(vec![copies()], vec![])),
|
||||
];
|
||||
for item in &items {
|
||||
for (what, clip) in &clips {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
let live = clip_outline(clip).unwrap();
|
||||
let mut group = clip_group(1, clip.clone());
|
||||
group.appearance.items.push(item.clone());
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
let exported = clip_outline(&baked_clip(&d)).unwrap();
|
||||
assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes");
|
||||
}
|
||||
}
|
||||
let b = bounds(&clips[0].1);
|
||||
assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_effects_apply_before_the_clip_groups() {
|
||||
// The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
|
||||
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
|
||||
//! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner
|
||||
//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
|
||||
//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]).
|
||||
//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's.
|
||||
|
||||
mod banner;
|
||||
mod nest;
|
||||
mod stencil;
|
||||
mod weed;
|
||||
|
||||
@@ -14,5 +16,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = stencil::specs();
|
||||
v.extend(weed::specs());
|
||||
v.extend(banner::specs());
|
||||
v.extend(nest::specs());
|
||||
v
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs
|
||||
//! the selected objects onto a sheet or a roll of material by their bounding boxes
|
||||
//! (<https://en.wikipedia.org/wiki/Packing_problems>). The sheet is an
|
||||
//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet
|
||||
//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places
|
||||
//! them better; they are never scaled or changed otherwise.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::super::edit::selected_roots_to_transform;
|
||||
use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns};
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Nest Shapes' command.
|
||||
pub const NEST: &str = "addon.cutting.nest";
|
||||
/// The largest sheet width or height, in points.
|
||||
const MAX_SIZE: f64 = 1_000_000.0;
|
||||
/// The largest margin or spacing, in points.
|
||||
const MAX_GAP: f64 = 100_000.0;
|
||||
/// The most objects one run nests.
|
||||
const MAX_SHAPES: usize = 10_000;
|
||||
/// How far a box may reach past the sheet's edge and still fit (rounding).
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.cutting.nest",
|
||||
"Nest Shapes…",
|
||||
["Object", "Plug-ins", "Cutting Tools"],
|
||||
None,
|
||||
"{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}",
|
||||
has_selection,
|
||||
nest
|
||||
)]
|
||||
}
|
||||
|
||||
/// The length `p` gives for `key`, from 0 to `max`, or `default`.
|
||||
fn length(p: &Value, key: &str, default: f64, max: f64) -> Result<f64> {
|
||||
match length_given(p, key, NEST)? {
|
||||
None => Ok(default),
|
||||
Some(v) if (0.0..=max).contains(&v) => Ok(v),
|
||||
Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Span {
|
||||
x: f64,
|
||||
w: f64,
|
||||
y: f64,
|
||||
}
|
||||
|
||||
/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep
|
||||
/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top.
|
||||
struct Skyline {
|
||||
spans: Vec<Span>,
|
||||
width: f64,
|
||||
height: f64,
|
||||
}
|
||||
|
||||
impl Skyline {
|
||||
fn new(width: f64, height: f64) -> Self {
|
||||
Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height }
|
||||
}
|
||||
|
||||
/// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it
|
||||
/// allow, choosing the place where its bottom edge is highest and then furthest left. `None`
|
||||
/// when it fits nowhere. The spans under the box at each span are a window whose two ends only
|
||||
/// move right, and `window` holds the indices in it whose depth no later span in it reaches, so
|
||||
/// its front is the deepest: one call takes time in proportion to the number of spans.
|
||||
fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> {
|
||||
let mut best: Option<(f64, f64)> = None;
|
||||
let mut window: VecDeque<usize> = VecDeque::new();
|
||||
let mut end = 0;
|
||||
for (i, s) in self.spans.iter().enumerate() {
|
||||
if s.x + w > self.width + EPS {
|
||||
break;
|
||||
}
|
||||
while window.front().is_some_and(|&j| j < i) {
|
||||
window.pop_front();
|
||||
}
|
||||
end = end.max(i);
|
||||
while let Some(t) = self.spans.get(end)
|
||||
&& (end == i || t.x < s.x + w - EPS)
|
||||
{
|
||||
while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) {
|
||||
window.pop_back();
|
||||
}
|
||||
window.push_back(end);
|
||||
end += 1;
|
||||
}
|
||||
let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0));
|
||||
if y + h > self.height + EPS {
|
||||
continue;
|
||||
}
|
||||
// The box is `h` tall at every place, so the place with the highest bottom edge is the
|
||||
// place with the highest top edge.
|
||||
if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) {
|
||||
best = Some((s.x, y));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Fills the skyline down to `y + h` from `x` across `w`.
|
||||
fn place(&mut self, x: f64, y: f64, w: f64, h: f64) {
|
||||
if w <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let end = x + w;
|
||||
let mut out = Vec::with_capacity(self.spans.len() + 2);
|
||||
let mut added = false;
|
||||
for s in &self.spans {
|
||||
let s_end = s.x + s.w;
|
||||
if s_end <= x || s.x >= end {
|
||||
out.push(*s);
|
||||
continue;
|
||||
}
|
||||
if s.x < x {
|
||||
out.push(Span { x: s.x, w: x - s.x, y: s.y });
|
||||
}
|
||||
if !added {
|
||||
out.push(Span { x, w, y: y + h });
|
||||
added = true;
|
||||
}
|
||||
if s_end > end {
|
||||
out.push(Span { x: end, w: s_end - end, y: s.y });
|
||||
}
|
||||
}
|
||||
// Neighbors filled to the same depth are one span.
|
||||
let mut merged: Vec<Span> = Vec::with_capacity(out.len());
|
||||
for s in out {
|
||||
match merged.last_mut() {
|
||||
Some(l) if l.y == s.y => l.w = s.x + s.w - l.x,
|
||||
_ => merged.push(s),
|
||||
}
|
||||
}
|
||||
self.spans = merged;
|
||||
}
|
||||
}
|
||||
|
||||
/// One box to pack: its width and height as it stands, and when it may turn, as it is turned.
|
||||
type Sizes = ((f64, f64), Option<(f64, f64)>);
|
||||
|
||||
/// The side a box is ordered by: its height, or its longest side when it may turn.
|
||||
fn lead(b: &Sizes) -> (f64, f64) {
|
||||
let ((w, h), turned) = *b;
|
||||
if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) }
|
||||
}
|
||||
|
||||
/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may
|
||||
/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`]
|
||||
/// puts it, turned when that puts its bottom edge higher (then further left), or when only the
|
||||
/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box
|
||||
/// that does not fit.
|
||||
fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec<Option<(f64, f64, bool)>> {
|
||||
let mut order: Vec<usize> = (0..boxes.len()).collect();
|
||||
order.sort_by(|&a, &b| {
|
||||
let (la, lb) = (lead(&boxes[a]), lead(&boxes[b]));
|
||||
lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1))
|
||||
});
|
||||
let mut sky = Skyline::new(width, height);
|
||||
let mut at = vec![None; boxes.len()];
|
||||
for i in order {
|
||||
let Some(&((w, h), turned)) = boxes.get(i) else { continue };
|
||||
let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h));
|
||||
if let Some((tw, th)) = turned
|
||||
&& let Some((x, y)) = sky.find(tw, th)
|
||||
{
|
||||
let better = best.is_none_or(|(bx, by, _, _, bh)| {
|
||||
let (was, now) = (by + bh, y + th);
|
||||
now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS)
|
||||
});
|
||||
if better {
|
||||
best = Some((x, y, true, tw, th));
|
||||
}
|
||||
}
|
||||
if let Some((x, y, t, bw, bh)) = best {
|
||||
sky.place(x, y, bw, bh);
|
||||
if let Some(slot) = at.get_mut(i) {
|
||||
*slot = Some((x, y, t));
|
||||
}
|
||||
}
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// A quarter turn clockwise on the page about `c`.
|
||||
fn quarter_turn(c: Point) -> Affine {
|
||||
Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2())
|
||||
}
|
||||
|
||||
fn finite(r: &Rect) -> bool {
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects
|
||||
/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows
|
||||
/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds.
|
||||
fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option<Rect> {
|
||||
let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?;
|
||||
if !preview {
|
||||
return Some(b);
|
||||
}
|
||||
match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) {
|
||||
Some(r) => Some(b.union(r)),
|
||||
None => Some(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` is a path of a pixel-aligned compound path.
|
||||
fn in_aligned_compound(d: &Document, id: NodeId) -> bool {
|
||||
d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned)
|
||||
}
|
||||
|
||||
/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or
|
||||
/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned
|
||||
/// compound path.
|
||||
fn snaps(d: &Document, id: NodeId) -> bool {
|
||||
if in_aligned_compound(d, id) {
|
||||
return true;
|
||||
}
|
||||
let mut stack: Vec<&Node> = d.node(id).into_iter().collect();
|
||||
while let Some(n) = stack.pop() {
|
||||
if n.extras().pixel_aligned {
|
||||
return true;
|
||||
}
|
||||
stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c));
|
||||
if let Some(m) = n.extras().mask.as_ref()
|
||||
&& m.linked
|
||||
{
|
||||
stack.push(&*m.art);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn nest(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["patterns"], NEST)?;
|
||||
let roll = switch_or(p, "roll", false, NEST)?;
|
||||
let width = length(p, "width", 0.0, MAX_SIZE)?;
|
||||
let height = length(p, "height", 0.0, MAX_SIZE)?;
|
||||
let margin = length(p, "margin", 18.0, MAX_GAP)?;
|
||||
let spacing = length(p, "spacing", 9.0, MAX_GAP)?;
|
||||
let turn = switch_or(p, "rotate", false, NEST)?;
|
||||
let preview = switch_or(p, "usePreviewBounds", true, NEST)?;
|
||||
let named = match p.get("artboard") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?),
|
||||
};
|
||||
// A path of a compound path selected on its own moves without the rest of the compound path.
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
if ids.len() > MAX_SHAPES {
|
||||
return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest")));
|
||||
}
|
||||
// Objects without a finite box (an empty group, empty type) are left where they are and
|
||||
// listed as `skipped`.
|
||||
let mut skipped = vec![];
|
||||
let (items, board): (Vec<(NodeId, Rect)>, Rect) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len());
|
||||
for id in &ids {
|
||||
match measure(d, *id, preview) {
|
||||
Some(r) => items.push((*id, r)),
|
||||
None => skipped.push(id.0),
|
||||
}
|
||||
}
|
||||
let board = match named {
|
||||
Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect,
|
||||
None => {
|
||||
let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b));
|
||||
let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0);
|
||||
d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect
|
||||
}
|
||||
};
|
||||
(items, board)
|
||||
};
|
||||
if items.is_empty() {
|
||||
return Err(bad(NEST, "the selection has nothing to nest"));
|
||||
}
|
||||
let sheet_w = if width > 0.0 { width } else { board.width() };
|
||||
let sheet_h = if roll {
|
||||
f64::INFINITY
|
||||
} else if height > 0.0 {
|
||||
height
|
||||
} else {
|
||||
board.height()
|
||||
};
|
||||
// Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than
|
||||
// the room inside the margins, so the spacing falls between boxes and not at the far edges.
|
||||
let room_w = sheet_w - 2.0 * margin;
|
||||
let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin };
|
||||
if room_w <= 0.0 || room_h <= 0.0 {
|
||||
return Err(bad(NEST, "the margin leaves no room on the sheet"));
|
||||
}
|
||||
let all: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
|
||||
let grid: Vec<bool> = {
|
||||
let d = &s.doc()?.doc;
|
||||
all.iter().map(|id| snaps(d, *id)).collect()
|
||||
};
|
||||
let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() };
|
||||
// With `rotate`, each object is turned in a copy of the document and measured there, so the
|
||||
// box packed for a turned object is the box its turned strokes and effects take. A path of a
|
||||
// pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path
|
||||
// again, which would move the compound's other paths away from where they were measured.
|
||||
let turned: Vec<Option<(Affine, Rect)>> = if turn {
|
||||
let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc);
|
||||
let xfs: Vec<Option<Affine>> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect();
|
||||
for ((id, _), xf) in items.iter().zip(&xfs) {
|
||||
if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect()
|
||||
} else {
|
||||
vec![None; items.len()]
|
||||
};
|
||||
// An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the
|
||||
// snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding.
|
||||
let slack = |g: bool| if g { 1.0 } else { 0.0 };
|
||||
let boxes: Vec<Sizes> = items
|
||||
.iter()
|
||||
.zip(&turned)
|
||||
.zip(&grid)
|
||||
.map(|(((_, r), t), g)| {
|
||||
let pad = spacing + slack(*g);
|
||||
((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad)))
|
||||
})
|
||||
.collect();
|
||||
let at = pack(&boxes, room_w + spacing, room_h + spacing);
|
||||
let origin = Vec2::new(board.x0 + margin, board.y0 + margin);
|
||||
// The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an
|
||||
// object on the pixel grid, so it moves at most 1 pt further right and down, into its slack.
|
||||
let shift = |b: &Rect, to: Vec2, g: bool| {
|
||||
let v = Vec2::new(to.x - b.x0, to.y - b.y0);
|
||||
if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v }
|
||||
};
|
||||
// Each move: the quarter turn first, when the object turns, then the shift.
|
||||
let mut moves: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
|
||||
let mut aside: Vec<(NodeId, Option<Affine>, Vec2)> = vec![];
|
||||
let mut unplaced = vec![];
|
||||
let mut rotated = vec![];
|
||||
let mut bottom = 0.0_f64;
|
||||
// Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge
|
||||
// and from each other, so that no object placed on the sheet covers them.
|
||||
let aside_x = board.x0 + sheet_w + spacing;
|
||||
let mut aside_y = board.y0;
|
||||
for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) {
|
||||
match (spot, t) {
|
||||
(Some((x, y, true)), Some((xf, q))) => {
|
||||
let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g);
|
||||
moves.push((*id, Some(*xf), dv));
|
||||
rotated.push(id.0);
|
||||
bottom = bottom.max(q.y1 + dv.y - origin.y);
|
||||
}
|
||||
(Some((x, y, _)), _) => {
|
||||
let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g);
|
||||
moves.push((*id, None, dv));
|
||||
bottom = bottom.max(r.y1 + dv.y - origin.y);
|
||||
}
|
||||
(None, _) => {
|
||||
aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g)));
|
||||
aside_y += r.height() + spacing + slack(*g);
|
||||
unplaced.push(id.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if moves.is_empty() {
|
||||
return Err(bad(NEST, "no selected object fits on the sheet"));
|
||||
}
|
||||
moves.extend(aside);
|
||||
let length = 2.0 * margin + bottom;
|
||||
let placed = moves.len() - unplaced.len();
|
||||
let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length });
|
||||
if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) {
|
||||
return Ok(result);
|
||||
}
|
||||
s.edit("Nest Shapes", |d, _| {
|
||||
for (id, xf, dv) in &moves {
|
||||
// The turn is the one the object was measured with in the copy, and the shift after it
|
||||
// is whole points for an object on the pixel grid.
|
||||
for step in xf.iter().copied().chain([Affine::translate(*dv)]) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, step, sc, true);
|
||||
}
|
||||
keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(result)
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{Skyline, pack};
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn overlap(a: Rect, b: Rect) -> bool {
|
||||
a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boxes_pack_tallest_first_from_the_top_left() {
|
||||
// 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20
|
||||
// one is too wide for the 40 pt beside the first box, so it goes below the first box.
|
||||
let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY);
|
||||
assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_that_does_not_fit_is_left_out() {
|
||||
let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0);
|
||||
assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]);
|
||||
}
|
||||
|
||||
/// Boxes that keep their orientation.
|
||||
fn fixed(b: &[(f64, f64)]) -> Vec<super::Sizes> {
|
||||
b.iter().map(|&s| (s, None)).collect()
|
||||
}
|
||||
|
||||
/// Boxes that may turn a quarter.
|
||||
fn turning(b: &[(f64, f64)]) -> Vec<super::Sizes> {
|
||||
b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() {
|
||||
// A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip
|
||||
// turned, as 10 × 120.
|
||||
let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
|
||||
assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]);
|
||||
// Without turning, the 120 pt wide box is left out and the other stands up.
|
||||
let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY);
|
||||
assert_eq!(at, vec![Some((0.0, 0.0, false)), None]);
|
||||
// A square box is never turned: turned, it is no better.
|
||||
let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0);
|
||||
assert_eq!(at, vec![Some((0.0, 0.0, false))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_skyline_fills_and_merges_spans() {
|
||||
let mut sky = Skyline::new(100.0, f64::INFINITY);
|
||||
sky.place(0.0, 0.0, 30.0, 10.0);
|
||||
sky.place(30.0, 0.0, 30.0, 10.0);
|
||||
assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans);
|
||||
assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top");
|
||||
assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect();
|
||||
select(&mut s, &ids);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(r["placed"], json!(6));
|
||||
assert_eq!(r["unplaced"], json!([]));
|
||||
let boxes: Vec<Rect> = ids.iter().map(|id| bounds(&s, *id)).collect();
|
||||
for (i, a) in boxes.iter().enumerate() {
|
||||
assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins");
|
||||
assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized");
|
||||
for b in &boxes[i + 1..] {
|
||||
assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart");
|
||||
}
|
||||
}
|
||||
// The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide
|
||||
// boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below
|
||||
// the 110 pt tall box at the right, where its bottom edge is highest.
|
||||
assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0));
|
||||
assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5);
|
||||
assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0));
|
||||
assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_that_do_not_fit_go_beside_the_sheet() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0);
|
||||
let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0);
|
||||
let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0);
|
||||
select(&mut s, &[a, b, big]);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(r["placed"], json!(1));
|
||||
assert_eq!(r["unplaced"], json!([b.0, big.0]));
|
||||
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0));
|
||||
// A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart.
|
||||
assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0));
|
||||
assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_beside_the_sheet_is_in_stacking_order() {
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0);
|
||||
let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0);
|
||||
let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0);
|
||||
// Selected front first: the column still starts with the object at the back.
|
||||
select(&mut s, &[front, small, back]);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(r["unplaced"], json!([back.0, front.0]));
|
||||
assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0));
|
||||
assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_without_bounds_are_skipped_and_listed() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
|
||||
let layer = s.doc().unwrap().doc.parent_of(a);
|
||||
let empty = s
|
||||
.edit("empty group", |d, _| {
|
||||
let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false });
|
||||
Ok(d.insert(layer, usize::MAX, g).unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a, empty]);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0])));
|
||||
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sheet_is_the_artboard_under_the_center_of_the_selection() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0);
|
||||
let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first");
|
||||
assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_turns_clockwise() {
|
||||
let mut s = session();
|
||||
// A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the
|
||||
// top-left corner goes to the top-right.
|
||||
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
|
||||
let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[long, mark]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let r = s
|
||||
.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}))
|
||||
.unwrap();
|
||||
assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0));
|
||||
assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() {
|
||||
let mut s = session();
|
||||
let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0);
|
||||
let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0);
|
||||
select(&mut s, &[outer, hole]);
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("object.setPixelAligned", &json!({})).unwrap();
|
||||
select(&mut s, &[hole]);
|
||||
// The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation.
|
||||
let r =
|
||||
s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false}));
|
||||
let e = r.unwrap_err().to_string();
|
||||
assert!(e.contains("no selected object fits"), "{e}");
|
||||
}
|
||||
|
||||
/// [`Skyline::find`] as a search of every span and every span under the box.
|
||||
fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> {
|
||||
let mut best: Option<(f64, f64)> = None;
|
||||
for (i, s) in sky.spans.iter().enumerate() {
|
||||
if s.x + w > sky.width + 1e-9 {
|
||||
break;
|
||||
}
|
||||
let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y));
|
||||
if y + h > sky.height + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) {
|
||||
best = Some((s.x, y));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_matches_a_search_of_every_span() {
|
||||
// A fixed pseudo-random sequence of boxes, each placed where `find` puts it.
|
||||
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
|
||||
let mut next = |n: u64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % n) as f64 + 1.0
|
||||
};
|
||||
let mut sky = Skyline::new(200.0, 400.0);
|
||||
for _ in 0..400 {
|
||||
let (w, h) = (next(60), next(30));
|
||||
let got = sky.find(w, h);
|
||||
assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans);
|
||||
if let Some((x, y)) = got {
|
||||
sky.place(x, y, w, h);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_that_does_not_fit_is_not_covered_by_the_others() {
|
||||
let mut s = session();
|
||||
// The wide object sits on the sheet and does not fit; the small one must not land on it.
|
||||
let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0);
|
||||
let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
|
||||
select(&mut s, &[wide, small]);
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.setPixelAligned", &json!({})).unwrap();
|
||||
let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0);
|
||||
assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b)));
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap();
|
||||
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
|
||||
assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}");
|
||||
assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}");
|
||||
assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}");
|
||||
assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_bounds_take_in_a_drop_shadow() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
|
||||
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
|
||||
let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap();
|
||||
assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}");
|
||||
let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb);
|
||||
assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_roll_has_no_end() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect();
|
||||
select(&mut s, &ids);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([])));
|
||||
let mut tops: Vec<f64> = ids.iter().map(|id| bounds(&s, *id).y0).collect();
|
||||
tops.sort_by(f64::total_cmp);
|
||||
assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll");
|
||||
assert_eq!(r["length"], json!(2040.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn width_and_height_set_the_sheet_from_the_artboard_corner() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect();
|
||||
select(&mut s, &ids);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(r["placed"], json!(3));
|
||||
for id in &ids {
|
||||
let b = bounds(&s, *id);
|
||||
assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_bounds_keep_strokes_apart() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap();
|
||||
let (ba, bb) = (bounds(&s, a), bounds(&s, b));
|
||||
assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet");
|
||||
assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_already_nested_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(r["placed"], json!(1));
|
||||
assert_eq!(steps(&s), n, "nothing moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_change_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
let n = steps(&s);
|
||||
let bad: [(Value, &str); 10] = [
|
||||
(json!({"rotate": 1}), "`rotate` must be true or false"),
|
||||
(json!({"width": -1}), "`width` must be from 0"),
|
||||
(json!({"height": 2e6}), "`height` must be from 0"),
|
||||
(json!({"margin": "x"}), "`margin` must be a number"),
|
||||
(json!({"spacing": 1e6}), "`spacing` must be from 0"),
|
||||
(json!({"roll": "yes"}), "`roll` must be true or false"),
|
||||
(json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"),
|
||||
(json!({"artboard": 3}), "there is no artboard 3"),
|
||||
(json!({"artboard": -1}), "`artboard` must be"),
|
||||
(json!({"margin": 400}), "the margin leaves no room"),
|
||||
];
|
||||
for (p, want) in bad {
|
||||
let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("no selected object fits"), "{e}");
|
||||
let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`patterns` must be true or false"), "{e}");
|
||||
assert_eq!(steps(&s), n, "a refused run changes nothing");
|
||||
assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_named_artboard_is_the_sheet() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_turns_objects_a_quarter_to_fit_the_sheet() {
|
||||
let mut s = session();
|
||||
// On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up.
|
||||
let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
|
||||
let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0);
|
||||
select(&mut s, &[long, small]);
|
||||
let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false});
|
||||
let r = s.execute("addon.cutting.nest", &p).unwrap();
|
||||
assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut p = p;
|
||||
p["rotate"] = json!(true);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.cutting.nest", &p).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0])));
|
||||
assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner");
|
||||
// The 50 × 40 object stays as it is: turned, its bottom edge would be lower.
|
||||
assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_measures_the_turned_preview_bounds() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap();
|
||||
assert_eq!(r["rotated"], json!([a.0]));
|
||||
assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_paths_path_selected_alone_moves_alone() {
|
||||
let mut s = session();
|
||||
let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0);
|
||||
let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0);
|
||||
select(&mut s, &[outer, hole]);
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
select(&mut s, &[hole]);
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved");
|
||||
assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_is_nested_as_one_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0);
|
||||
let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap();
|
||||
assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0)));
|
||||
}
|
||||
@@ -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 }))
|
||||
|
||||
@@ -89,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Asset Export Settings",
|
||||
[],
|
||||
None,
|
||||
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
|
||||
"{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step",
|
||||
has_doc,
|
||||
settings_set
|
||||
),
|
||||
@@ -435,19 +435,35 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn settings_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.settings.set";
|
||||
let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") {
|
||||
return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", "))));
|
||||
if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) {
|
||||
return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", "))));
|
||||
}
|
||||
for k in ["subfolders", "openLocation"] {
|
||||
if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) {
|
||||
return Err(bad(C, format!("`{k}` is true or false")));
|
||||
}
|
||||
}
|
||||
let mut settings = s.doc()?.doc.export_settings.clone();
|
||||
let mut given = o.clone();
|
||||
// Create Sub-folders is on for a document without settings (Export for Screens opens so), and
|
||||
// Open Location after Export set on its own leaves it on.
|
||||
if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) {
|
||||
given.insert("subfolders".into(), json!(true));
|
||||
}
|
||||
if let Some(name) = given.remove("exportPreset") {
|
||||
let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?;
|
||||
with_screen_export_preset(s, C, &mut settings, name)?;
|
||||
}
|
||||
// Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice.
|
||||
// Turned off on its own (the panel menu), it also ends a remembered folder per format or item;
|
||||
// with an export preset, that preset's folder per format or item stays.
|
||||
let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string);
|
||||
let sorted = folders.as_deref().is_some_and(|f| f != "none");
|
||||
match given.get("subfolders").and_then(Value::as_bool) {
|
||||
Some(true) => _ = settings.insert("folders".into(), json!("rows")),
|
||||
Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")),
|
||||
Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => {
|
||||
_ = settings.insert("folders".into(), json!("none"))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
overlay(&mut settings, &given);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<V
|
||||
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
|
||||
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
|
||||
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
|
||||
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
|
||||
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at Limited 64 colors,
|
||||
/// Paths 90, Corners 25 and Noise 4 makes about 1.9 million, and even at Paths 100, Noise 1 and
|
||||
/// every tone about 7.9 million. On the web, where a page has at most 4 GB of memory, the limit
|
||||
/// stays at 2,000,000.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
|
||||
|
||||
@@ -1139,7 +1140,7 @@ mod trace_limit_tests {
|
||||
assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]);
|
||||
}
|
||||
|
||||
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
|
||||
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
// A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about
|
||||
// 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
|
||||
}
|
||||
@@ -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() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwor
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds), in a row, and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
//! (unknown keys are ignored, so one params object can carry the options of several formats).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -450,31 +450,85 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
|
||||
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
|
||||
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
|
||||
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
|
||||
/// an instance can paint its objects, and finds them by their places in the art.
|
||||
/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that
|
||||
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
|
||||
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
|
||||
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
|
||||
/// they change.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name) that aren't dynamic.
|
||||
// The symbols instances show (the first of each name).
|
||||
let mut names = HashSet::new();
|
||||
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
|
||||
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
|
||||
let shown: Vec<usize> = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect();
|
||||
// The sets of appearance changes the drawn instances of each dynamic symbol make to its art;
|
||||
// `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole.
|
||||
let mut sets: HashMap<&str, Option<Vec<Vec<&SymbolOverride>>>> =
|
||||
shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect();
|
||||
if !sets.is_empty() {
|
||||
let mut walked = HashSet::new();
|
||||
for l in &doc.layers {
|
||||
drawn_changes(doc, l, left_out, true, &mut walked, &mut sets);
|
||||
}
|
||||
}
|
||||
// Each set of changes gets a copy of its symbol, appended after the symbols, which the instances
|
||||
// that make those changes show instead.
|
||||
let variant = |symbol: &str, n: &Node| -> Option<String> {
|
||||
let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?;
|
||||
Some(format!("{symbol}\u{0}{k}"))
|
||||
};
|
||||
let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new();
|
||||
let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| {
|
||||
let mut d = doc.clone();
|
||||
for l in &mut d.layers {
|
||||
if let Some(n) = remapped(l, &variant) {
|
||||
*l = n;
|
||||
}
|
||||
}
|
||||
for s in &mut d.symbols {
|
||||
if let Some(n) = remapped(&s.art, &variant) {
|
||||
s.art = n;
|
||||
}
|
||||
}
|
||||
for i in &shown {
|
||||
let Some(s) = d.symbols.get(*i).cloned() else { continue };
|
||||
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
|
||||
copies.push((d.symbols.len(), c.as_slice()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
|
||||
}
|
||||
}
|
||||
d
|
||||
});
|
||||
let src = remapped_doc.as_ref().unwrap_or(doc);
|
||||
// The symbols to measure with the changes their instances make (`None` for a static symbol),
|
||||
// without the dynamic symbols measured whole.
|
||||
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
|
||||
.iter()
|
||||
.filter_map(|i| src.symbols.get(*i).map(|s| (*i, s)))
|
||||
.filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some))
|
||||
.map(|(i, s)| (i, s.dynamic.then_some(&[][..])))
|
||||
.chain(copies.iter().map(|(i, c)| (*i, Some(*c))))
|
||||
.collect();
|
||||
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
|
||||
// symbols included.
|
||||
let mut empty: HashSet<&str> = HashSet::new();
|
||||
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
|
||||
while let Some(s) = entries.iter().find_map(|(i, c)| {
|
||||
src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new()))
|
||||
}) {
|
||||
empty.insert(&s.name);
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
let layers = hidden_nodes(&doc.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = shown
|
||||
let layers = hidden_nodes(&src.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = entries
|
||||
.iter()
|
||||
.filter(|(_, s)| !empty.contains(s.name.as_str()))
|
||||
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
|
||||
.filter_map(|(i, c)| {
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
|
||||
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
|
||||
})
|
||||
.collect();
|
||||
if layers.is_none() && symbols.is_empty() {
|
||||
return vectorcraft_render::encode::art_bounds(doc);
|
||||
return vectorcraft_render::encode::art_bounds(src);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let mut d = remapped_doc.unwrap_or_else(|| doc.clone());
|
||||
if let Some(layers) = layers {
|
||||
d.layers = layers;
|
||||
}
|
||||
@@ -486,22 +540,126 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
|
||||
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
|
||||
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's
|
||||
/// symbol and the instance) made an instance of that symbol; `None` when none is.
|
||||
fn remapped(n: &Arc<Node>, variant: &dyn Fn(&str, &Node) -> Option<String>) -> Option<Arc<Node>> {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let name = variant(symbol, n)?;
|
||||
let mut m = (**n).clone();
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind {
|
||||
*symbol = name;
|
||||
}
|
||||
return Some(Arc::new(m));
|
||||
}
|
||||
let children = n.children()?;
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = remapped(c, variant)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
|
||||
/// layer or a group holding only such objects (its clipping path among them when it clips). A
|
||||
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
|
||||
/// of these unless it is hidden or picked.
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
|
||||
/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes
|
||||
/// an instance makes to it; `n` is at place `at`), each object is judged with those changes
|
||||
/// ([`as_drawn`]).
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> bool {
|
||||
let m = as_drawn(n, changed, at);
|
||||
!n.visible
|
||||
|| left_out(n)
|
||||
|| !has_effects(n)
|
||||
|| left_out(&m)
|
||||
|| !has_effects(&m)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| {
|
||||
at.push(i as u32);
|
||||
let out = all_left_out(c, left_out, empty, changed, at);
|
||||
at.pop();
|
||||
out
|
||||
}),
|
||||
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
|
||||
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
|
||||
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
|
||||
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
|
||||
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
fn drawn_changes<'a>(
|
||||
doc: &'a Document,
|
||||
n: &'a Node,
|
||||
left_out: &dyn Fn(&Node) -> bool,
|
||||
hidden: bool,
|
||||
walked: &mut HashSet<&'a str>,
|
||||
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
|
||||
) {
|
||||
if hidden && !n.visible || left_out(n) {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let changes = own_changes(n);
|
||||
if let Some(entry) = sets.get_mut(symbol.as_str())
|
||||
&& !changes.is_empty()
|
||||
{
|
||||
let full = match entry {
|
||||
Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => {
|
||||
list.push(changes);
|
||||
false
|
||||
}
|
||||
Some(list) => !list.contains(&changes),
|
||||
None => false,
|
||||
};
|
||||
if full {
|
||||
*entry = None;
|
||||
}
|
||||
}
|
||||
if walked.insert(symbol.as_str())
|
||||
&& let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol)
|
||||
{
|
||||
drawn_changes(doc, &s.art, left_out, false, walked, sets);
|
||||
}
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
drawn_changes(doc, c, left_out, hidden, walked, sets);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of
|
||||
/// appearance changes its instances make; a symbol whose instances make more sets is measured whole.
|
||||
const MAX_ART_COPIES: usize = 64;
|
||||
|
||||
/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an
|
||||
/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not
|
||||
/// dynamic (`changed` is `None`) and when no change names `at`.
|
||||
fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> {
|
||||
let here: Vec<SymbolOverride> =
|
||||
changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect();
|
||||
if here.is_empty() {
|
||||
return Cow::Borrowed(n);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
vectorcraft_doc::symbol_overrides::apply(&mut m, &here);
|
||||
Cow::Owned(m)
|
||||
}
|
||||
|
||||
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
|
||||
/// take part in.
|
||||
fn has_effects(n: &Node) -> bool {
|
||||
@@ -511,25 +669,32 @@ fn has_effects(n: &Node) -> bool {
|
||||
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
|
||||
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
|
||||
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
|
||||
/// effects, fills or strokes of its own keep all they hold.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
|
||||
/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol
|
||||
/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place
|
||||
/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves
|
||||
/// an empty group in its place.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> Option<Arc<Node>> {
|
||||
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
|
||||
if has_effects(n) || n.extras().shaper.is_some() {
|
||||
if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut taken = false;
|
||||
let kept: Vec<Arc<Node>> = children
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| {
|
||||
if left_out(c) && !(*clip && i == 0) {
|
||||
changed = true;
|
||||
return None;
|
||||
}
|
||||
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
|
||||
at.push(i as u32);
|
||||
let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) {
|
||||
taken = true;
|
||||
changed.map(|_| Arc::new(Node::group(c.id, Vec::new())))
|
||||
} else {
|
||||
Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone()))
|
||||
};
|
||||
at.pop();
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
changed.then(|| {
|
||||
taken.then(|| {
|
||||
let mut new = (**n).clone();
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
|
||||
*children = kept;
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -3,26 +3,22 @@
|
||||
//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF
|
||||
//! resolution tags. Place
|
||||
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
|
||||
//! as a `pHYs` chunk.
|
||||
//! as a `pHYs` chunk. The formats the image decoder reads are read by [`vectorcraft_doc::ppi`].
|
||||
|
||||
pub(super) use vectorcraft_doc::ppi::png_chunks;
|
||||
use vectorcraft_doc::ppi::tiff;
|
||||
pub use vectorcraft_doc::ppi::with_png_resolution;
|
||||
|
||||
const INCH_M: f64 = 0.0254;
|
||||
const INCH_CM: f64 = 2.54;
|
||||
|
||||
/// The resolution a file declares as (horizontal, vertical) ppi; `None` when it declares none (or
|
||||
/// only an aspect ratio).
|
||||
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
png(bytes)
|
||||
} else if bytes.starts_with(&[0xff, 0xd8]) {
|
||||
jpeg(bytes)
|
||||
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
|
||||
tiff(bytes)
|
||||
} else if super::jxlread::is_jxl(bytes) {
|
||||
if vectorcraft_doc::ppi::reads(bytes) {
|
||||
return vectorcraft_doc::ppi::resolution(bytes);
|
||||
}
|
||||
let r = if super::jxlread::is_jxl(bytes) {
|
||||
jxl(bytes)
|
||||
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||
webp(bytes)
|
||||
} else if bytes.starts_with(b"BM") {
|
||||
bmp(bytes)
|
||||
} else if super::psdread::is_psd(bytes) {
|
||||
super::psdread::resolution(bytes)
|
||||
} else if super::pcxread::is_pcx(bytes) {
|
||||
@@ -82,121 +78,9 @@ fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
|
||||
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
|
||||
slice(b, at, N)?.try_into().ok()
|
||||
}
|
||||
fn be16(b: &[u8], at: usize) -> Option<u16> {
|
||||
bytes(b, at).map(u16::from_be_bytes)
|
||||
}
|
||||
fn be32(b: &[u8], at: usize) -> Option<u32> {
|
||||
bytes(b, at).map(u32::from_be_bytes)
|
||||
}
|
||||
fn le32(b: &[u8], at: usize) -> Option<u32> {
|
||||
bytes(b, at).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
|
||||
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
|
||||
fn per_metre(ppm: u32) -> f64 {
|
||||
let v = ppm as f64 * INCH_M;
|
||||
let whole = v.round();
|
||||
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
|
||||
}
|
||||
|
||||
/// PNG chunks after the signature: (type, data).
|
||||
pub(super) fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
|
||||
let mut at = 8;
|
||||
std::iter::from_fn(move || {
|
||||
let len = be32(b, at)? as usize;
|
||||
let ty = slice(b, at + 4, 4)?;
|
||||
let data = slice(b, at + 8, len)?;
|
||||
at = at.checked_add(12 + len)?;
|
||||
Some((ty, data))
|
||||
})
|
||||
}
|
||||
|
||||
fn png(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
|
||||
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
|
||||
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
|
||||
}
|
||||
|
||||
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let (mut jfif, mut exif) = (None, None);
|
||||
let mut at = 2;
|
||||
while at + 4 <= b.len() && b[at] == 0xff {
|
||||
let marker = b[at + 1];
|
||||
// 0xff fill bytes pad between segments.
|
||||
if marker == 0xff {
|
||||
at += 1;
|
||||
continue;
|
||||
}
|
||||
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
// Start of scan or end of image: no more metadata.
|
||||
if marker == 0xda || marker == 0xd9 {
|
||||
break;
|
||||
}
|
||||
let len = be16(b, at + 2)? as usize;
|
||||
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
|
||||
match marker {
|
||||
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
|
||||
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
|
||||
jfif = match seg[7] {
|
||||
1 => Some((x, y)),
|
||||
2 => Some((x * INCH_CM, y * INCH_CM)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
|
||||
_ => {}
|
||||
}
|
||||
at += 2 + len;
|
||||
}
|
||||
jfif.or(exif)
|
||||
}
|
||||
|
||||
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit.
|
||||
fn tiff(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let le = b.starts_with(b"II");
|
||||
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
|
||||
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
|
||||
let ifd = u32_at(4)? as usize;
|
||||
let (mut x, mut y, mut unit) = (None, None, 2);
|
||||
for i in 0..u16_at(ifd)? as usize {
|
||||
let e = ifd.checked_add(2 + i * 12)?;
|
||||
let rational = || -> Option<f64> {
|
||||
let at = u32_at(e + 8)? as usize;
|
||||
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
|
||||
(d != 0).then(|| n as f64 / d as f64)
|
||||
};
|
||||
match u16_at(e)? {
|
||||
282 => x = rational(),
|
||||
283 => y = rational(),
|
||||
296 => unit = u16_at(e + 8)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let k = match unit {
|
||||
2 => 1.0,
|
||||
3 => INCH_CM,
|
||||
_ => return None,
|
||||
};
|
||||
let x = x?;
|
||||
Some((x * k, y.unwrap_or(x) * k))
|
||||
}
|
||||
|
||||
fn webp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut at = 12;
|
||||
while at + 8 <= b.len() {
|
||||
let len = le32(b, at + 4)? as usize;
|
||||
let data = b.get(at + 8..at + 8 + len)?;
|
||||
if &b[at..at + 4] == b"EXIF" {
|
||||
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
|
||||
}
|
||||
at += 8 + len + (len & 1);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn jxl(b: &[u8]) -> Option<(f64, f64)> {
|
||||
if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) {
|
||||
@@ -224,33 +108,6 @@ fn jxl(b: &[u8]) -> Option<(f64, f64)> {
|
||||
None
|
||||
}
|
||||
|
||||
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
|
||||
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
|
||||
if le32(b, 14)? < 40 {
|
||||
return None;
|
||||
}
|
||||
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
|
||||
Some((ppm(38)?, ppm(42)?))
|
||||
}
|
||||
|
||||
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
|
||||
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
|
||||
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
|
||||
let chunk = vectorcraft_render::encode::png::phys_chunk(x, y);
|
||||
let mut out = Vec::with_capacity(png.len() + chunk.len());
|
||||
out.extend_from_slice(head);
|
||||
out.extend_from_slice(&chunk);
|
||||
let mut at = head.len();
|
||||
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
|
||||
if chunk.get(4..8) != Some(b"pHYs") {
|
||||
out.extend_from_slice(chunk);
|
||||
}
|
||||
at += chunk.len();
|
||||
}
|
||||
out.extend_from_slice(png.get(at..).unwrap_or_default());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -254,6 +254,90 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as
|
||||
/// well, until an instance paints the path, and a document whose only other visible art is an
|
||||
/// instance of a dynamic symbol of an image is refused.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
|
||||
let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6)
|
||||
};
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
|
||||
let before = bounds(&s);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let after = bounds(&s);
|
||||
assert!(same(before, after), "{before:?} {after:?}");
|
||||
|
||||
// A change of the path's blending mode leaves it painting nothing; once the instance paints the
|
||||
// path, the path is measured.
|
||||
let art = s.doc().unwrap().doc.symbols[0].art.clone();
|
||||
let x0 = |c: &std::sync::Arc<vectorcraft_doc::Node>| c.visual_bounds().map_or(f64::MIN, |b| b.x0);
|
||||
let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap();
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap();
|
||||
let blended = bounds(&s);
|
||||
assert!(same(before, blended), "{before:?} {blended:?}");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap();
|
||||
let painted = bounds(&s);
|
||||
assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}");
|
||||
// A later change to the same object, as a file can hold, takes the paint off again.
|
||||
{
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() });
|
||||
n.extras_mut().symbol_overrides = overrides.clone();
|
||||
let taken_off = bounds(&s);
|
||||
assert!(same(before, taken_off), "{before:?} {taken_off:?}");
|
||||
overrides.pop();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides;
|
||||
}
|
||||
// Another instance, far above, that doesn't paint the path is measured without it, whether or
|
||||
// not the first one paints it.
|
||||
let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone();
|
||||
let with_paint = bounds(&s);
|
||||
s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap();
|
||||
let without_paint = bounds(&s);
|
||||
assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let undone = bounds(&s);
|
||||
assert!(same(undone, with_paint), "{undone:?} {with_paint:?}");
|
||||
s.execute("select.set", &json!({"ids": [other]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
|
||||
s.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
|
||||
// An instance that brings a group at 0% opacity back to full opacity still draws nothing when
|
||||
// the group holds only an image.
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone();
|
||||
s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides =
|
||||
[vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
|
||||
/// out when it would take more cells than the effect makes.
|
||||
#[test]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -40,6 +40,7 @@ pub use commands::specs;
|
||||
pub(crate) use data::apply_csv;
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, parse_csv, to_csv};
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
#[cfg(test)]
|
||||
use generate::generate;
|
||||
#[cfg(test)]
|
||||
@@ -47,7 +48,7 @@ use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in,
|
||||
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use vectorcraft_doc::graph::art_bounds;
|
||||
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
use super::generate::{children_bounds, generate};
|
||||
@@ -17,11 +19,62 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
|
||||
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
|
||||
/// bounds with a width and a height, or has no art without type now.
|
||||
fn measured(n: &Node) -> Option<(Rect, Rect)> {
|
||||
let kept = n.extras().graph.as_deref()?;
|
||||
let c = n.children()?;
|
||||
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
|
||||
art.or_else(|| kept.placed.zip(children_bounds(c)))
|
||||
}
|
||||
|
||||
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
|
||||
/// `None` when `from` has no width or no height.
|
||||
fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
|
||||
if from.width() <= 1e-9 || from.height() <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let (sx, sy) = (to.width() / from.width(), to.height() / from.height());
|
||||
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
|
||||
}
|
||||
|
||||
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
|
||||
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
|
||||
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
|
||||
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
|
||||
for id in ids {
|
||||
let Some(chain) = d.ancestry(*id) else { continue };
|
||||
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
|
||||
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
|
||||
let children = d.node(gid).and_then(Node::children);
|
||||
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// After an edit that changed the art of `graphs` (from [`graphs_holding`]) without moving them, set the bounds each
|
||||
/// keeps so that its next redraw measures the same move or scale as it would have before the edit.
|
||||
pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option<Rect>, Option<Rect>)]) {
|
||||
for &(gid, art_was, whole_was) in graphs {
|
||||
let Some(n) = d.node(gid) else { continue };
|
||||
let children = n.children();
|
||||
let (art_now, whole_now) = (children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)));
|
||||
let Some(spec) = d.node_mut(gid).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
if let (Some(placed), Some(was), Some(now)) = (spec.placed_art, art_was, art_now) {
|
||||
spec.placed_art = carried(now, was, placed).or(spec.placed_art);
|
||||
}
|
||||
if let (Some(placed), Some(was), Some(now)) = (spec.placed, whole_was, whole_now) {
|
||||
spec.placed = carried(now, was, placed).or(spec.placed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
|
||||
/// generation, which is recorded in the spec's `placed` bounds).
|
||||
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let (Some(placed), Some(now)) = (n.extras().graph.as_ref().and_then(|g| g.placed), n.children().and_then(|c| children_bounds(c)))
|
||||
if let Some((placed, now)) = measured(n)
|
||||
&& placed.width() > 1e-9
|
||||
&& placed.height() > 1e-9
|
||||
&& (placed.x0 - now.x0).abs() + (placed.y0 - now.y0).abs() + (placed.x1 - now.x1).abs() + (placed.y1 - now.y1).abs() > 1e-6
|
||||
@@ -33,6 +86,7 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
|
||||
}
|
||||
let children = generate(d, &spec);
|
||||
spec.placed = children_bounds(&children);
|
||||
spec.placed_art = art_bounds(&children);
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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, ¶ms).unwrap();
|
||||
assert_eq!(kept(&s, id), (None, None), "{cmd}");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal), "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kept(&s, id), faded, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Redefining a graphic style a series group is linked to clears the group's own opacity and blend mode, and removes
|
||||
/// what the graph keeps for them.
|
||||
#[test]
|
||||
fn redefining_a_style_linked_to_a_series_group_forgets_its_kept_opacity() {
|
||||
let (mut s, id, _, _) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
|
||||
s.edit("Link", |d, _| {
|
||||
let i = d.graphic_style_index("Blue").unwrap();
|
||||
(d.graphic_styles[i].opacity, d.graphic_styles[i].blend) = (0.5, BlendMode::Screen);
|
||||
let g = d.node_mut(group).unwrap();
|
||||
g.appearance = style.appearance.clone().into();
|
||||
(g.opacity, g.blend) = (0.5, BlendMode::Screen);
|
||||
g.extras_mut().graphic_style = Some(style.id);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap();
|
||||
let slot = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((slot.group_opacity, slot.group_blend), (Some(0.5), Some(BlendMode::Screen)));
|
||||
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, Some(style.id), "still linked");
|
||||
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00"})).unwrap();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
|
||||
let slot = spec(&s, id).series_paints.first().cloned().unwrap_or_default();
|
||||
assert_eq!((slot.group_opacity, slot.group_blend), (None, None));
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal));
|
||||
}
|
||||
|
||||
/// Isolate Blending, a knockout state and Knockout Shape set on a selected series group are kept by the graph for the
|
||||
/// group, through the graph being drawn again; the other series' group stays as the graph draws it, and turning them off
|
||||
/// forgets them.
|
||||
#[test]
|
||||
fn isolation_and_knockout_on_a_series_group_survive_regeneration() {
|
||||
let (mut s, id, _, _) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"isolate": true, "knockout": "off", "knockoutShape": true})).unwrap();
|
||||
let slot = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((slot.group_isolate, slot.group_knockout, slot.group_knockout_shape), (true, Some(vectorcraft_doc::Knockout::Off), true));
|
||||
assert_eq!((slot.group_opacity, slot.group_blend, slot.opacity, slot.blend), (None, None, None, None));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.setProps", &json!({"id": group.0, "isolate": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already");
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let (g, other) = (series(&n, 0), series(&n, 1));
|
||||
assert_eq!((g.isolate, g.knockout, g.knockout_shape), (true, vectorcraft_doc::Knockout::Off, true));
|
||||
assert_eq!((other.isolate, other.knockout, other.knockout_shape), (false, vectorcraft_doc::Knockout::Neutral, false));
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("object.setProps", &json!({"id": group.0, "isolate": false, "knockout": "neutral", "knockoutShape": false})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "nothing is kept");
|
||||
}
|
||||
|
||||
/// Randomize Opacity and Sort Objects given a series group keep the opacity they give it for the group.
|
||||
#[test]
|
||||
fn randomize_and_sort_opacity_on_a_series_group_are_kept() {
|
||||
let (mut s, id, _, _) = column_marks();
|
||||
let (group, _) = series_0_group(&s, id);
|
||||
s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [group.0], "min": 30, "max": 60, "seed": 7})).unwrap();
|
||||
let given = s.doc().unwrap().doc.node(group).unwrap().opacity;
|
||||
assert!(given < 1.0);
|
||||
assert_eq!(spec(&s, id).series_paints[0].group_opacity, Some(given));
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert_eq!(group_transparency(&s, id, 0).0, (given, BlendMode::Normal));
|
||||
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let (first, second) = (series(&n, 0).id, series(&n, 1).id);
|
||||
s.execute("object.setProps", &json!({"id": second.0, "opacity": 80})).unwrap();
|
||||
s.execute("addon.arrange.sort", &json!({"ids": [first.0, second.0], "by": "x", "apply": "opacity", "order": "descending"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (a, b) = (d.node(first).unwrap().opacity, d.node(second).unwrap().opacity);
|
||||
assert_eq!((a, b), (0.8, given), "the opacities trade places");
|
||||
let kept = &spec(&s, id).series_paints;
|
||||
assert_eq!((kept[0].group_opacity, kept.get(1).and_then(|k| k.group_opacity)), ((a < 1.0).then_some(a), (b < 1.0).then_some(b)));
|
||||
}
|
||||
|
||||
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
|
||||
#[test]
|
||||
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
|
||||
@@ -5691,6 +5872,151 @@ fn formatting_one_label_keeps_that_kind_of_label() {
|
||||
assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none());
|
||||
}
|
||||
|
||||
/// Character and paragraph edits that resize a graph's labels leave the plot where it is when the graph is drawn
|
||||
/// again, and a move or scale of the graph made after them is still followed.
|
||||
#[test]
|
||||
fn restyling_a_graphs_labels_leaves_the_plot_in_place() {
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let redraw = |s: &mut Session, id: NodeId| s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": 14})).unwrap();
|
||||
redraw(&mut s, id);
|
||||
assert_eq!(spec(&s, id).rect, rect, "after a size change to every label");
|
||||
let c = text_id(&s, id, "Axes", "Q2");
|
||||
s.execute("text.setFormat", &json!({"ids": [c.0], "leftIndent": 20})).unwrap();
|
||||
redraw(&mut s, id);
|
||||
assert_eq!(spec(&s, id).rect, rect, "after an indent on the category labels");
|
||||
let l = text_id(&s, id, "Legend", "2025");
|
||||
s.execute("text.setStyle", &json!({"ids": [l.0], "size": 4})).unwrap();
|
||||
redraw(&mut s, id);
|
||||
assert_eq!(spec(&s, id).rect, rect, "after a smaller size on the legend labels");
|
||||
// A move and a scale of the whole graph still carry the plot with them.
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
|
||||
redraw(&mut s, id);
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [moved.x0, moved.y0]})).unwrap();
|
||||
redraw(&mut s, id);
|
||||
let scaled = spec(&s, id).rect;
|
||||
assert!((scaled.width() - 2.0 * rect.width()).abs() < 1e-6 && (scaled.height() - rect.height()).abs() < 1e-6, "{scaled:?}");
|
||||
assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}");
|
||||
}
|
||||
|
||||
/// Moving one label of a graph on its own leaves the plot where it is when the graph is drawn again.
|
||||
#[test]
|
||||
fn moving_one_label_leaves_the_plot_in_place() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
for (grp, text) in [("Legend", "2025"), ("Axes", "Q2")] {
|
||||
let l = text_id(&s, id, grp, text);
|
||||
s.execute("select.set", &json!({"ids": [l.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 120, "dy": 60})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, rect, "after moving {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Label edits leave the plot in place in graphs whose legend swatches follow the size of the labels at the next
|
||||
/// drawing: a legend across the top, a legend after a right value axis, and legend labels of several lines. A move of
|
||||
/// the graph made after them is still followed.
|
||||
#[test]
|
||||
fn restyling_the_labels_of_a_graph_whose_legend_follows_them_leaves_the_plot_in_place() {
|
||||
let csv = ",North|East|Coast,South|West,Inland|Hills|Lakes|Plains\nQ1,3,2,4\nQ2,5,4,1\nQ3,-1,6,2";
|
||||
for options in [json!({"legendAcrossTop": true}), json!({"valueAxis": "right"}), json!({"valueAxis": "both"}), json!({})] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("graph.setType", &options).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let rect = spec(&s, id).rect;
|
||||
for size in [16, 5] {
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"size": size})).unwrap();
|
||||
for _ in 0..2 {
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, rect, "{options}: labels at {size} pt");
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 30, "dy": 20})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 20.0)).abs() < 1e-6, "{options}: {moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{options}: {moved:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Outlining a graph's labels leaves the plot where it is when the graph is drawn again, and a move of the graph made
|
||||
/// before them is still followed.
|
||||
#[test]
|
||||
fn outlining_a_graphs_labels_leaves_the_plot_in_place() {
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q2").0, text_id(&s, id, "Legend", "2025").0]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, rect, "after outlining labels");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 30, "dy": 15})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0, text_id(&s, id, "Legend", "2024").0]})).unwrap();
|
||||
s.execute("type.createOutlines", &json!({})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}");
|
||||
}
|
||||
|
||||
/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art.
|
||||
#[test]
|
||||
fn a_graph_whose_art_without_type_kept_no_width_still_follows_a_move() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
let mut flat = spec(&s, id);
|
||||
let art = flat.placed_art.unwrap();
|
||||
flat.placed_art = Some(vectorcraft_geom::Rect::new(art.x0, art.y0, art.x0, art.y1));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(flat));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
|
||||
}
|
||||
|
||||
/// A graph saved before it kept the bounds of its art without type follows a move made since with its old bounds.
|
||||
#[test]
|
||||
fn a_graph_saved_with_only_its_whole_bounds_still_follows_a_move() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let rect = spec(&s, id).rect;
|
||||
let mut old = serde_json::to_value(spec(&s, id)).unwrap();
|
||||
old.as_object_mut().unwrap().remove("placedArt");
|
||||
let old: GraphSpec = serde_json::from_value(old).unwrap();
|
||||
assert_eq!(old.placed_art, None);
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
|
||||
let moved = spec(&s, id).rect;
|
||||
assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}");
|
||||
assert!(spec(&s, id).placed_art.is_some(), "the next drawing keeps the bounds of the art without type");
|
||||
}
|
||||
|
||||
/// Each Axes and Legend text after the graph is drawn again, with its object rows (fill or stroke, color, opacity, and
|
||||
/// for a stroke its weight) and its object opacity.
|
||||
type RowLooks = Vec<(bool, String, f32, f64)>;
|
||||
@@ -6935,3 +7261,42 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
|
||||
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own
|
||||
/// leaves the plot where it is at the first redraw.
|
||||
#[test]
|
||||
fn a_graph_opened_from_ai_measures_moves_without_its_labels() {
|
||||
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
|
||||
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
|
||||
%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
|
||||
u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\
|
||||
u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n\
|
||||
0 To\n1 0 0 1 100 220 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Sales) Tx\nTO\nU\n%_GS\n";
|
||||
let text = format!(
|
||||
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\
|
||||
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\
|
||||
%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n"
|
||||
);
|
||||
let dir = vectorcraft_testkit::temp_dir("graph-ai-label");
|
||||
let path = dir.join("graph.ai");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path})).unwrap();
|
||||
let (mut graphs, mut labels) = (vec![], vec![]);
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if n.extras().graph.is_some() {
|
||||
graphs.push(n.id);
|
||||
}
|
||||
if matches!(&n.kind, NodeKind::Text(t) if t.plain_text() == "Sales") {
|
||||
labels.push(n.id);
|
||||
}
|
||||
});
|
||||
assert_eq!((graphs.len(), labels.len()), (1, 1));
|
||||
let (id, label) = (graphs[0], labels[0]);
|
||||
let before = spec(&s, id);
|
||||
assert!(before.placed_art.is_some());
|
||||
s.execute("select.set", &json!({"ids": [label.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
|
||||
assert_eq!(spec(&s, id).rect, before.rect);
|
||||
}
|
||||
@@ -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") }))
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -101,12 +101,30 @@ const FILE_WORDS: &[&str] = &[
|
||||
"clipboard",
|
||||
];
|
||||
|
||||
/// Param keys that name a file or a folder.
|
||||
const FILE_KEYS: &[&str] =
|
||||
&["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"];
|
||||
/// Param keys that name a file or a folder, each by its whole name, the folder preferences
|
||||
/// `prefs.set {values}` takes included: a command that adds a key naming one adds it here. A key
|
||||
/// that only ends like one (`alignToPath`, `linksFolder`, `sortPaths`) names none, nor do `folders`
|
||||
/// (how an export groups its files) and `url` (a web link).
|
||||
const FILE_KEYS: &[&str] = &[
|
||||
"path",
|
||||
"paths",
|
||||
"file",
|
||||
"files",
|
||||
"folder",
|
||||
"dir",
|
||||
"directory",
|
||||
"destinationFolder",
|
||||
"sourceFolder",
|
||||
"diffPath",
|
||||
"fontsFolder",
|
||||
"pluginsFolder",
|
||||
"recoveryFolder",
|
||||
"templatesFolder",
|
||||
];
|
||||
|
||||
/// The keys in [`FILE_KEYS`] that name a folder.
|
||||
const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"];
|
||||
const FOLDER_KEYS: &[&str] =
|
||||
&["folder", "dir", "directory", "destinationFolder", "sourceFolder", "fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// What a param key that names a place on disk names there.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -132,7 +150,83 @@ pub fn key_location(key: &str) -> Option<Location> {
|
||||
/// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`]
|
||||
/// names it for `spec` (it names part of the document there).
|
||||
pub fn location_in(spec: &CommandSpec, key: &str) -> Option<Location> {
|
||||
if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) }
|
||||
ParamsPlace::top(Some(spec)).member(key, None).1
|
||||
}
|
||||
|
||||
/// A place in the params of a command. What a key names on disk depends on the command and on the
|
||||
/// keys above it: [`key_location`], less a key [`NOT_FILES`] names for the command at the top of its
|
||||
/// params and one at the end of a [`NESTED_NOT_FILES`] key list. A walk of params starts at
|
||||
/// [`ParamsPlace::top`] and goes down with [`ParamsPlace::member`] and [`ParamsPlace::item`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ParamsPlace {
|
||||
/// The command whose params these are; `None` for a command that isn't known.
|
||||
command: Option<&'static str>,
|
||||
/// Whether this is the top of the params.
|
||||
top: bool,
|
||||
/// The keys of a [`NESTED_NOT_FILES`] list still to follow below this place.
|
||||
trail: Option<&'static [&'static str]>,
|
||||
}
|
||||
|
||||
impl ParamsPlace {
|
||||
/// The top of the params of `spec`, or of a command that isn't known (`None`), where every key in
|
||||
/// [`FILE_KEYS`] names a file or a folder.
|
||||
pub fn top(spec: Option<&CommandSpec>) -> ParamsPlace {
|
||||
ParamsPlace { command: spec.map(|s| s.id), top: true, trail: None }
|
||||
}
|
||||
|
||||
/// The top of the params of the command with id `id` ([`ParamsPlace::top`]).
|
||||
pub fn of(id: &str) -> ParamsPlace {
|
||||
ParamsPlace::top(super::find_command(id))
|
||||
}
|
||||
|
||||
/// The top of the params of the command that object `fields` calls, when it is a call
|
||||
/// (`{command | id: <command id>, params}`, as a `command.batch` step or a control request is):
|
||||
/// the place of its `params` member ([`ParamsPlace::member`]).
|
||||
pub fn carried(fields: &serde_json::Map<String, Value>) -> Option<ParamsPlace> {
|
||||
if !fields.contains_key("params") {
|
||||
return None;
|
||||
}
|
||||
let id = fields.get("command").or_else(|| fields.get("id")).and_then(Value::as_str)?;
|
||||
super::find_command(id).map(|spec| ParamsPlace::top(Some(spec)))
|
||||
}
|
||||
|
||||
/// The top of the params of the command that array `items` records, when it is a recorded step
|
||||
/// (`[command id, params]`): the place of its item 1 ([`ParamsPlace::item`]).
|
||||
pub fn step(items: &[Value]) -> Option<ParamsPlace> {
|
||||
match items {
|
||||
[Value::String(id), Value::Object(_)] => super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The place of member `key` of an object here, with what `key` names on disk there. `carried` is
|
||||
/// [`ParamsPlace::carried`] of that object: its `params` member is then the top of that command's
|
||||
/// params, and names no file.
|
||||
pub fn member(self, key: &str, carried: Option<ParamsPlace>) -> (ParamsPlace, Option<Location>) {
|
||||
if key == "params"
|
||||
&& let Some(inner) = carried
|
||||
{
|
||||
return (inner, None);
|
||||
}
|
||||
let rest = if self.top {
|
||||
let id = self.command;
|
||||
NESTED_NOT_FILES.iter().find(|(c, keys)| Some(*c) == id && keys.first() == Some(&key)).map(|(_, keys)| keys.get(1..).unwrap_or_default())
|
||||
} else {
|
||||
self.trail.filter(|keys| keys.first() == Some(&key)).map(|keys| keys.get(1..).unwrap_or_default())
|
||||
};
|
||||
let document = (self.top && self.command.is_some_and(|id| NOT_FILES.contains(&(id, key)))) || rest.is_some_and(<[&str]>::is_empty);
|
||||
let place = ParamsPlace { command: self.command, top: false, trail: rest.filter(|keys| !keys.is_empty()) };
|
||||
(place, if document { None } else { key_location(key) })
|
||||
}
|
||||
|
||||
/// The place of item `index` of an array here. `step` is [`ParamsPlace::step`] of that array: its
|
||||
/// item 1 is then the top of that command's params.
|
||||
pub fn item(self, index: usize, step: Option<ParamsPlace>) -> ParamsPlace {
|
||||
match step {
|
||||
Some(inner) if index == 1 => inner,
|
||||
_ => ParamsPlace { command: self.command, top: false, trail: None },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The param keys of `spec` that name a file or a folder, with what they name: the keys in
|
||||
@@ -158,9 +252,6 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[
|
||||
("symbol.instance.setAppearance", "path"),
|
||||
("symbol.instance.selectPart", "path"),
|
||||
("object.objectsOnPath.attach", "path"),
|
||||
("attributes.set", "url"),
|
||||
("object.slice.options", "url"),
|
||||
("document.exportForScreens", "folders"),
|
||||
];
|
||||
|
||||
/// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there,
|
||||
@@ -251,34 +342,24 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth
|
||||
/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`]
|
||||
/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for
|
||||
/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the
|
||||
/// thread's.
|
||||
/// Does `args`, the arguments of a call of command `id`, carry a key that names a file or a folder at
|
||||
/// any depth (in objects and in arrays, [`ParamsPlace`]), such as an effect's `textureImage.path`?
|
||||
/// Only a key [`NOT_FILES`] names for `id`, at the top level, and one at the end of a
|
||||
/// [`NESTED_NOT_FILES`] key list for `id`, aren't counted. A call or a recorded step inside `args`
|
||||
/// is read as part of `id`'s arguments, not as the command it names. The walk keeps its own stack,
|
||||
/// so deep arguments can't overflow the thread's.
|
||||
fn names_file(id: &str, args: &Value) -> bool {
|
||||
// Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list
|
||||
// still to follow below it.
|
||||
let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)];
|
||||
while let Some((v, top, trail)) = stack.pop() {
|
||||
let mut stack: Vec<(&Value, ParamsPlace)> = vec![(args, ParamsPlace::of(id))];
|
||||
while let Some((v, place)) = stack.pop() {
|
||||
match v {
|
||||
Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))),
|
||||
Value::Array(a) => stack.extend(a.iter().enumerate().map(|(i, x)| (x, place.item(i, None)))),
|
||||
Value::Object(o) => {
|
||||
for (k, x) in o {
|
||||
let k = k.as_str();
|
||||
let rest = if top {
|
||||
NESTED_NOT_FILES
|
||||
.iter()
|
||||
.find(|(c, keys)| *c == id && keys.first() == Some(&k))
|
||||
.map(|(_, keys)| keys.get(1..).unwrap_or_default())
|
||||
} else {
|
||||
trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default())
|
||||
};
|
||||
let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty);
|
||||
if FILE_KEYS.contains(&k) && !document {
|
||||
let (below, location) = place.member(k, None);
|
||||
if location.is_some() {
|
||||
return true;
|
||||
}
|
||||
stack.push((x, false, rest.filter(|keys| !keys.is_empty())));
|
||||
stack.push((x, below));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -638,7 +719,13 @@ mod tests {
|
||||
assert!(names_file("effect.apply", &texture));
|
||||
assert!(names_file("effect.setParams", &texture));
|
||||
assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}})));
|
||||
assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]])));
|
||||
assert!(names_file("select.all", &json!([[[{"file": "file:///etc/hosts"}]]])));
|
||||
// A web link and an export's grouping name no file.
|
||||
assert!(!names_file("attributes.set", &json!({"url": "https://example.com/a"})));
|
||||
assert!(!names_file("object.move", &json!({"opts": {"folders": "rows", "alignToPath": "baseline"}})));
|
||||
// A call nested in the arguments doesn't vouch for its own keys.
|
||||
assert!(names_file("object.move", &json!({"opts": {"command": "object.setLiveShape", "params": {"path": "/tmp/x"}}})));
|
||||
assert!(names_file("object.move", &json!({"opts": ["object.setLiveShape", {"path": "/tmp/x"}]})));
|
||||
assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}})));
|
||||
assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}})));
|
||||
// `path` is the path text is set on in text.createInPath, but only as its own param.
|
||||
@@ -647,7 +734,13 @@ mod tests {
|
||||
assert!(names_file("object.move", &json!({"path": [[0, 0]]})));
|
||||
// object.setLiveShape takes no `path`; its description says "on any path:" in its prose.
|
||||
assert!(names_file("object.setLiveShape", &json!({"path": "/tmp/x"})));
|
||||
// Image Trace's path fidelity setting, only inside its tracing settings.
|
||||
}
|
||||
|
||||
/// Image Trace's path fidelity setting `paths` names no file, but only inside its tracing
|
||||
/// settings.
|
||||
#[test]
|
||||
fn image_trace_paths_name_no_file_only_in_its_settings() {
|
||||
use serde_json::json;
|
||||
for id in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
assert!(!names_file(id, &json!({"preset": "Default", "params": {"mode": "color", "paths": 50}})));
|
||||
assert!(!names_file(id, &json!({"savedPreset": {"paths": 50, "corners": 75}})));
|
||||
@@ -658,7 +751,12 @@ mod tests {
|
||||
assert!(names_file(id, &json!({"options": {"paths": 50}})));
|
||||
}
|
||||
assert!(names_file("object.move", &json!({"params": {"paths": 50}})));
|
||||
// A custom arrowhead's outline in stroke.set, only where stroke.set takes one.
|
||||
}
|
||||
|
||||
/// A custom arrowhead's outline `path` names no file, but only where stroke.set takes one.
|
||||
#[test]
|
||||
fn a_custom_arrowhead_outline_names_no_file_only_in_stroke_set() {
|
||||
use serde_json::json;
|
||||
let outline = json!({"subpaths": []});
|
||||
assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}})));
|
||||
assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"})));
|
||||
@@ -668,7 +766,12 @@ mod tests {
|
||||
assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}})));
|
||||
assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]})));
|
||||
assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}})));
|
||||
// Deep nesting is walked without recursion.
|
||||
}
|
||||
|
||||
/// A file key under deep nesting is found, and the walk doesn't recurse.
|
||||
#[test]
|
||||
fn a_file_key_is_found_under_deep_nesting() {
|
||||
use serde_json::json;
|
||||
let mut deep = json!({"file": "/tmp/x"});
|
||||
for _ in 0..10_000 {
|
||||
deep = Value::Array(vec![deep]);
|
||||
@@ -726,11 +829,48 @@ mod tests {
|
||||
assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id);
|
||||
assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id);
|
||||
}
|
||||
assert_eq!(key_location("url"), Some(Location::File));
|
||||
assert_eq!(key_location("url"), None);
|
||||
assert_eq!(key_location("folders"), None);
|
||||
assert_eq!(key_location("linksFolder"), None);
|
||||
assert_eq!(key_location("sourceFolder"), Some(Location::Folder));
|
||||
assert_eq!(key_location("pathData"), None);
|
||||
}
|
||||
|
||||
/// A key keeps the meaning its command gives it at every depth: a call (`{command, params}`) and a
|
||||
/// recorded step (`[command id, params]`) carry their command's exceptions down, and a custom
|
||||
/// arrowhead's outline is part of the document only at its own place in `stroke.set`.
|
||||
#[test]
|
||||
fn a_params_place_follows_its_command() {
|
||||
use serde_json::json;
|
||||
let at = |place: ParamsPlace, keys: &[&str]| {
|
||||
let mut place = place;
|
||||
let mut location = None;
|
||||
for k in keys {
|
||||
(place, location) = place.member(k, None);
|
||||
}
|
||||
location
|
||||
};
|
||||
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["path"]), None);
|
||||
assert_eq!(at(ParamsPlace::of("text.createInPath"), &["options", "path"]), Some(Location::File));
|
||||
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "path"]), None);
|
||||
assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "file"]), Some(Location::File));
|
||||
assert_eq!(at(ParamsPlace::of("no.such.command"), &["path"]), Some(Location::File));
|
||||
assert_eq!(at(ParamsPlace::top(None), &["destinationFolder"]), Some(Location::Folder));
|
||||
let call = json!({"command": "text.createInPath", "params": {"path": [[0, 0]]}});
|
||||
let carried = call.as_object().and_then(ParamsPlace::carried);
|
||||
let (inner, location) = ParamsPlace::of("command.batch").member("params", carried);
|
||||
assert_eq!(location, None);
|
||||
assert_eq!(inner.member("path", None).1, None);
|
||||
assert_eq!(ParamsPlace::carried(&serde_json::Map::new()).map(|_| ()), None);
|
||||
let unknown = json!({"command": "no.such.command", "params": {}});
|
||||
assert!(unknown.as_object().and_then(ParamsPlace::carried).is_none());
|
||||
let step = [json!("text.createInPath"), json!({"path": [[0, 0]]})];
|
||||
let place = ParamsPlace::top(None).item(1, ParamsPlace::step(&step));
|
||||
assert_eq!(place.member("path", None).1, None);
|
||||
assert_eq!(ParamsPlace::top(None).item(0, ParamsPlace::step(&step)).member("path", None).1, Some(Location::File));
|
||||
assert!(ParamsPlace::step(&[json!("text.createInPath")]).is_none());
|
||||
}
|
||||
|
||||
/// A file key counts as a command's param only where its description takes it: not a word in
|
||||
/// the prose after the params, in a nested object or in the result. A description that doesn't
|
||||
/// say which keys it takes counts any `key:` in its text.
|
||||
|
||||
@@ -34,6 +34,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.contour.set",
|
||||
"addon.cutting.banner",
|
||||
"addon.cutting.bridges",
|
||||
"addon.cutting.nest",
|
||||
"addon.cutting.weed",
|
||||
"addon.image.applyColorMask",
|
||||
"addon.image.colorMask",
|
||||
@@ -474,6 +475,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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -616,6 +616,21 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed }))
|
||||
}
|
||||
|
||||
/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as
|
||||
/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced
|
||||
/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's
|
||||
/// transform); `None` when the piece has no path.
|
||||
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> {
|
||||
let path = PathData::from_bezpath(outline);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
|
||||
let mut node = shape_node(d, path, None);
|
||||
vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
|
||||
Some(node)
|
||||
}
|
||||
|
||||
fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
let ids = s.edit("Create Outlines", |d, sel| {
|
||||
@@ -623,6 +638,8 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if texts.is_empty() {
|
||||
return Err(EngineError::Other("Create Outlines: select text objects".into()));
|
||||
}
|
||||
// Outlining a graph's labels does not move or scale its plot at the next redraw.
|
||||
let graphs = super::graph::graphs_holding(d, &texts);
|
||||
let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone());
|
||||
let ended = super::dimension::end_links(d, &roots);
|
||||
let mut new_sel: Vec<NodeId> = roots.iter().copied().filter(|r| !texts.contains(r)).collect();
|
||||
@@ -658,14 +675,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
children.push(Arc::new(d.reid(&art)));
|
||||
break 'glyph;
|
||||
}
|
||||
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
|
||||
if path.is_empty() {
|
||||
break 'glyph;
|
||||
if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) {
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
|
||||
let mut node = shape_node(d, path, None);
|
||||
node.appearance = st.appearance().into();
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
run_end.insert(g.run, children.len());
|
||||
}
|
||||
@@ -674,13 +686,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// nothing there either).
|
||||
let mut ruby: Vec<(usize, Arc<Node>)> = vec![];
|
||||
for g in &lay.ruby {
|
||||
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
|
||||
let mut node = shape_node(d, path, None);
|
||||
node.appearance = st.appearance().into();
|
||||
let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue };
|
||||
// After the glyphs of its run and of the runs before it.
|
||||
let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0);
|
||||
ruby.push((at, Arc::new(node)));
|
||||
@@ -705,10 +711,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// Underline and strikethrough bars become paths of their run's paint too (#847).
|
||||
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
|
||||
all.extend(bar.iter());
|
||||
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
|
||||
let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None);
|
||||
node.appearance = st.appearance().into();
|
||||
children.push(Arc::new(node));
|
||||
if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) {
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
// The object's own fills and strokes (not its characters') paint the whole outline:
|
||||
// those below the Characters row under the characters, the others over them, with
|
||||
@@ -750,6 +755,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
// Outlined frames of threaded text leave their threads with the text they show.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
super::graph::keep_placed(d, &graphs);
|
||||
sel.set(new_sel);
|
||||
Ok(out)
|
||||
})?;
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -277,24 +277,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
|
||||
}
|
||||
}
|
||||
@@ -302,12 +505,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| {
|
||||
@@ -319,8 +530,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 ----------
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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>>,
|
||||
|
||||
@@ -24,6 +24,8 @@ impl Session {
|
||||
});
|
||||
// Clicks find an image's own fills and strokes where their effects draw them.
|
||||
vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint);
|
||||
// Clicks inside a clip group fall in the region its clipping path's effects give it.
|
||||
vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline);
|
||||
// Clicks find a blend's steps and an envelope's distorted art where the canvas draws them,
|
||||
// evaluated again when the fonts, the hyphenation exceptions or the plug-ins change.
|
||||
vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || {
|
||||
@@ -329,6 +331,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 +361,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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() {
|
||||
assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_");
|
||||
}
|
||||
|
||||
/// `openLocation` (Open Location after Export) is remembered in the document's export settings,
|
||||
/// outside presets; null removes it, and only true or false is taken.
|
||||
#[test]
|
||||
fn open_location_is_remembered_in_the_export_settings() {
|
||||
let mut s = session();
|
||||
let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone();
|
||||
let r = run(&mut s, "assets.settings.set", json!({"openLocation": false}));
|
||||
assert_eq!(open(&mut s), false);
|
||||
assert!(r["settings"].get("openLocation").is_none(), "{r}");
|
||||
// Create Sub-folders, on for a document without settings, stays on.
|
||||
assert_eq!(r["settings"]["subfolders"], true, "{r}");
|
||||
run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}}));
|
||||
run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"}));
|
||||
assert_eq!(open(&mut s), false, "a preset leaves it as it is");
|
||||
run(&mut s, "assets.settings.set", json!({"openLocation": null}));
|
||||
assert_eq!(open(&mut s), Value::Null);
|
||||
for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] {
|
||||
assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export
|
||||
/// for Screens opens with it off too; given with an export preset, the preset's folders stay.
|
||||
#[test]
|
||||
fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() {
|
||||
let mut s = session();
|
||||
let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone();
|
||||
run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}}));
|
||||
for preset in ["Logo Package", "Items"] {
|
||||
run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false}));
|
||||
assert_ne!(folders(&mut s), "none", "{preset}");
|
||||
run(&mut s, "assets.settings.set", json!({"subfolders": false}));
|
||||
assert_eq!(folders(&mut s), "none", "{preset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on
|
||||
/// for a folder per row; with Create Sub-folders off every file goes into the folder itself,
|
||||
/// mobile and density rows too.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -119,12 +119,80 @@ fn text_on_top_clips_by_its_glyphs() {
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art));
|
||||
assert!(b.x1 < 95.0, "{b:?}");
|
||||
assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text");
|
||||
// An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame.
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap();
|
||||
assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow");
|
||||
// Release gives the text back.
|
||||
select(&mut s, &[g]);
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() {
|
||||
// The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The
|
||||
// hidden rectangle does not clip, so clicks inside the clip group still count the type by its
|
||||
// frame, the counter of the "O" included.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap());
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap());
|
||||
let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap();
|
||||
let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap();
|
||||
select(&mut s, &[art, t]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
// Make Clipping Mask takes no group on top, so the group goes in place of the type.
|
||||
let mut d = (*s.doc().unwrap().doc).clone();
|
||||
let mut rect = (*d.remove(r).unwrap()).clone();
|
||||
rect.visible = false;
|
||||
let text = d.remove(t).unwrap();
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]);
|
||||
d.insert(Some(g), 0, group).unwrap();
|
||||
let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf);
|
||||
let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
|
||||
assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame");
|
||||
assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_follow_the_region_a_clipping_paths_effects_give_it() {
|
||||
// Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves
|
||||
// 50 pt right: the art shows on the right half, as clicks find it.
|
||||
let mut s = session();
|
||||
let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap());
|
||||
let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap());
|
||||
select(&mut s, &[art, clip]);
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap();
|
||||
let r = render(&s);
|
||||
assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region");
|
||||
assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path");
|
||||
assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None);
|
||||
assert_eq!(at(75.0), [g]);
|
||||
assert!(at(25.0).is_empty());
|
||||
// A marquee across the art's edge reaches it within the moved region only.
|
||||
let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true);
|
||||
assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region");
|
||||
assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place");
|
||||
|
||||
// The same with a sublayer that clips by its first object.
|
||||
let mut d = (**d).clone();
|
||||
let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
|
||||
let top = d.layers[0].id;
|
||||
d.remove(g).unwrap();
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (members, true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf);
|
||||
assert_eq!(leaf(75.0), Some(art));
|
||||
assert_eq!(leaf(25.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_refuses_a_top_object_that_cannot_clip() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -2409,6 +2409,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")),
|
||||
@@ -3738,12 +3742,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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::{Location, ParamsPlace};
|
||||
use vectorcraft_engine::{Session, command_specs};
|
||||
use vectorcraft_testkit::catch_quiet;
|
||||
use vectorcraft_testkit::fixtures::Fixture;
|
||||
@@ -272,44 +273,46 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec<Value
|
||||
cases
|
||||
}
|
||||
|
||||
/// The strings in `v`, the value at `at` in a case of command `id`, that name a place on disk
|
||||
/// outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when `named` (it is
|
||||
/// under a key that names a file or folder), and in objects at any depth, the values under such
|
||||
/// keys ([`names_location`]).
|
||||
fn outside_locations(id: &str, at: &str, v: &Value, named: bool, dir: &std::path::Path, out: &mut std::collections::BTreeSet<String>) {
|
||||
/// The strings in `v`, the value at `at` (found at `place`) in a case of command `id`, that name a
|
||||
/// place on disk outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when
|
||||
/// `named` (it is under a key that names a file or folder), and in objects at any depth, the values
|
||||
/// under such keys as the command reads them (`vectorcraft_engine::cmd::ParamsPlace`).
|
||||
fn outside_locations(
|
||||
id: &str,
|
||||
at: &str,
|
||||
v: &Value,
|
||||
place: ParamsPlace,
|
||||
named: bool,
|
||||
dir: &std::path::Path,
|
||||
out: &mut std::collections::BTreeSet<String>,
|
||||
) {
|
||||
match v {
|
||||
Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => {
|
||||
out.insert(format!("{id} {at}: {v}"));
|
||||
}
|
||||
Value::Array(a) => {
|
||||
let step = ParamsPlace::step(a);
|
||||
for (i, x) in a.iter().enumerate() {
|
||||
outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out);
|
||||
outside_locations(id, &format!("{at}[{i}]"), x, place.item(i, step), named, dir, out);
|
||||
}
|
||||
}
|
||||
Value::Object(o) => {
|
||||
let carried = ParamsPlace::carried(o);
|
||||
for (k, x) in o {
|
||||
outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out);
|
||||
let (below, location) = place.member(k, carried);
|
||||
outside_locations(id, &format!("{at}.{k}"), x, below, location.is_some(), dir, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `key` name a file or folder, in command `spec` when given: a key in
|
||||
/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps
|
||||
/// for `spec`.
|
||||
fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool {
|
||||
match spec {
|
||||
Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(),
|
||||
None => vectorcraft_engine::cmd::key_location(key).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every string the sweeps send under a key that names a file or folder, in the command catalog
|
||||
/// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside
|
||||
/// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or
|
||||
/// writes in the working directory. `every_command_with_junk_params` sends every such key of every
|
||||
/// command alone in at least one case ([`junk_cases`]).
|
||||
/// command alone in at least one case ([`junk_cases`]). Which catalog keys name a file or folder is
|
||||
/// checked on its own by [`catalog_path_keys_match_location_policy`].
|
||||
#[test]
|
||||
fn sweep_cases_name_files_only_inside_the_temp_folder() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("sweep");
|
||||
@@ -330,7 +333,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() {
|
||||
for p in &cases {
|
||||
let Some(o) = p.as_object() else { continue };
|
||||
for (k, v) in o {
|
||||
outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside);
|
||||
let (below, location) = ParamsPlace::top(Some(c)).member(k, None);
|
||||
outside_locations(c.id, k, v, below, location.is_some(), &dir, &mut outside);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -339,6 +343,104 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() {
|
||||
assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n"));
|
||||
}
|
||||
|
||||
/// The param keys that name a file or a folder, and which.
|
||||
const LOCATION_KEYS: &[(&str, Location)] = &[
|
||||
("path", Location::File),
|
||||
("paths", Location::File),
|
||||
("file", Location::File),
|
||||
("files", Location::File),
|
||||
("diffPath", Location::File),
|
||||
("folder", Location::Folder),
|
||||
("dir", Location::Folder),
|
||||
("directory", Location::Folder),
|
||||
("destinationFolder", Location::Folder),
|
||||
("sourceFolder", Location::Folder),
|
||||
("fontsFolder", Location::Folder),
|
||||
("pluginsFolder", Location::Folder),
|
||||
("recoveryFolder", Location::Folder),
|
||||
("templatesFolder", Location::Folder),
|
||||
];
|
||||
|
||||
/// Param keys that read like a file or folder key ([`reads_like_a_location`]) and name neither:
|
||||
/// web links, an export's grouping of its files, and choices and switches.
|
||||
const NOT_LOCATIONS: &[&str] = &[
|
||||
"url",
|
||||
"copyrightUrl",
|
||||
"folders",
|
||||
"alignToPath",
|
||||
"wholePaths",
|
||||
"emptyTextPaths",
|
||||
"sortPaths",
|
||||
"alterPaths",
|
||||
"includeLinkedFiles",
|
||||
"linksFolder",
|
||||
];
|
||||
|
||||
/// Commands and the key in [`LOCATION_KEYS`] that, at the top of their params, names part of the
|
||||
/// document (a path of its art, a result field), not a file.
|
||||
const DOCUMENT_PARTS: &[(&str, &str)] = &[
|
||||
("object.setLiveShape", "path"),
|
||||
("path.reverse", "paths"),
|
||||
("object.pathfinder.options", "paths"),
|
||||
("object.maskImage", "path"),
|
||||
("text.createInPath", "path"),
|
||||
("symbol.instance.setAppearance", "path"),
|
||||
("symbol.instance.selectPart", "path"),
|
||||
("object.objectsOnPath.attach", "path"),
|
||||
("svgInteractivity.info", "files"),
|
||||
("addon.cleanup.rejoin", "paths"),
|
||||
];
|
||||
|
||||
/// Does param key `k` read like one that names a file, a folder or a link: a bare name for one, or a
|
||||
/// name that ends like one?
|
||||
fn reads_like_a_location(k: &str) -> bool {
|
||||
const ENDS: &[&str] = &["Path", "Paths", "File", "Files", "Folder", "Folders", "Dir", "Directory", "Url", "URL"];
|
||||
matches!(k, "path" | "paths" | "file" | "files" | "folder" | "folders" | "dir" | "directory" | "url") || ENDS.iter().any(|end| k.ends_with(end))
|
||||
}
|
||||
|
||||
/// Every key of every command that reads like a file or folder key (in its params description, the
|
||||
/// commands its `…` entries name and its schema) is in [`LOCATION_KEYS`] or [`NOT_LOCATIONS`], so a
|
||||
/// command that adds one fails here until it is sorted. The generic classifications
|
||||
/// (`vectorcraft_engine::cmd::key_location`, `vectorcraft_engine::file_access::is_path_key`) agree
|
||||
/// with those lists, and each command reads such a key as they say (`location_in`), less
|
||||
/// [`DOCUMENT_PARTS`].
|
||||
#[test]
|
||||
fn catalog_path_keys_match_location_policy() {
|
||||
use vectorcraft_engine::cmd::{key_location, location_in, params::takes_key};
|
||||
let catalog: Vec<(&vectorcraft_engine::CommandSpec, Vec<String>)> = command_specs().iter().map(|c| (c, command_param_keys(c))).collect();
|
||||
let mut keys: std::collections::BTreeSet<String> =
|
||||
catalog.iter().flat_map(|(_, keys)| keys.iter().filter(|k| reads_like_a_location(k)).cloned()).collect();
|
||||
keys.extend(LOCATION_KEYS.iter().map(|(k, _)| k.to_string()).chain(NOT_LOCATIONS.iter().map(|k| k.to_string())));
|
||||
let mut wrong = vec![];
|
||||
for k in &keys {
|
||||
let want = LOCATION_KEYS.iter().find(|(l, _)| l == k).map(|(_, l)| *l);
|
||||
if want.is_none() && !NOT_LOCATIONS.contains(&k.as_str()) {
|
||||
wrong.push(format!("`{k}` is in neither LOCATION_KEYS nor NOT_LOCATIONS"));
|
||||
continue;
|
||||
}
|
||||
if key_location(k) != want {
|
||||
wrong.push(format!("key_location(`{k}`) is {:?}, not {want:?}", key_location(k)));
|
||||
}
|
||||
if vectorcraft_engine::file_access::is_path_key(k) != want.is_some() {
|
||||
wrong.push(format!("is_path_key(`{k}`) is {}", want.is_none()));
|
||||
}
|
||||
for (c, named) in &catalog {
|
||||
if !named.contains(k) && !(c.params.contains('…') && takes_key(c.params, k)) {
|
||||
continue;
|
||||
}
|
||||
let here = if DOCUMENT_PARTS.contains(&(c.id, k.as_str())) { None } else { want };
|
||||
if location_in(c, k) != here {
|
||||
wrong.push(format!("{}: location_in(`{k}`) is {:?}, not {here:?}", c.id, location_in(c, k)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, key) in DOCUMENT_PARTS {
|
||||
let named = catalog.iter().any(|(c, _)| c.id == *id && c.params.contains(key));
|
||||
assert!(named, "{id} doesn't name `{key}`");
|
||||
}
|
||||
assert!(wrong.is_empty(), "{} keys are classified unlike the reviewed lists:\n{}", wrong.len(), wrong.join("\n"));
|
||||
}
|
||||
|
||||
/// The cases sweep keys the command catalog names as files and folders: `document.open`'s
|
||||
/// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s
|
||||
/// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s
|
||||
@@ -914,6 +1016,12 @@ fn structured_junk() {
|
||||
("addon.cutting.banner", json!({"hem": 0, "grommetInset": 0, "spacing": 0.01, "allArtboards": true})),
|
||||
("addon.cutting.banner", json!({"spacing": "1 mm", "grommets": false, "swatch": 5, "left": null})),
|
||||
("addon.cutting.banner", json!({"top": false, "right": false, "bottom": false, "left": false, "allArtboards": false})),
|
||||
("addon.cutting.nest", json!({"width": 1e6, "height": 1e6, "margin": 1e5, "spacing": 1e5, "roll": true})),
|
||||
("addon.cutting.nest", json!({"width": 1e-300, "height": f64::MAX, "margin": -1, "spacing": "1 mm", "artboard": u64::MAX})),
|
||||
("addon.cutting.nest", json!({"width": 0, "height": 0, "margin": 0, "spacing": 0, "usePreviewBounds": "no", "patterns": 1})),
|
||||
("addon.cutting.nest", json!({"roll": null, "artboard": -1, "width": "1 in", "height": [1]})),
|
||||
("addon.cutting.nest", json!({"rotate": true, "roll": true, "width": 1e-6, "margin": 0, "spacing": 0, "usePreviewBounds": true})),
|
||||
("addon.cutting.nest", json!({"rotate": "yes", "width": f64::NAN, "spacing": -0.0})),
|
||||
// Type Tools add-on.
|
||||
("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})),
|
||||
("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})),
|
||||
|
||||
@@ -2904,9 +2904,9 @@ fn arb_body() -> impl Strategy<Value = Vec<u8>> {
|
||||
}
|
||||
|
||||
/// WMF record functions VectorCraft reads, and one it doesn't.
|
||||
const WMF_FUNCTIONS: [u16; 33] = [
|
||||
const WMF_FUNCTIONS: [u16; 35] = [
|
||||
0x0324, 0x0325, 0x0538, 0x041B, 0x0418, 0x061C, 0x0817, 0x081A, 0x0830, 0x0416, 0x0415, 0x02FA, 0x02FC, 0x02FB, 0x012D, 0x01F0, 0x0521, 0x0A32,
|
||||
0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0999,
|
||||
0x0F43, 0x0B41, 0x0940, 0x061D, 0x0213, 0x0214, 0x001E, 0x0127, 0x0106, 0x0209, 0x012E, 0x00F7, 0x01F9, 0x0142, 0x0103, 0x0104, 0x0999,
|
||||
];
|
||||
|
||||
proptest! {
|
||||
@@ -2933,6 +2933,30 @@ proptest! {
|
||||
survive_metafile("WMF records", "x.wmf", &wmf_of(&records))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_headerless_wmf_records_never_panic(records in prop::collection::vec((prop::sample::select(WMF_FUNCTIONS.to_vec()), arb_body()), 0..32)) {
|
||||
// Without the placeable header, the map and mix modes the records set decide the scale.
|
||||
survive_metafile("headerless WMF records", "x.wmf", &wmf_of(&records)[22..])?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_emf_plus_records_never_panic(records in prop::collection::vec((0x4001u16..0x403B, any::<u16>(), arb_body()), 0..32)) {
|
||||
// One comment of EMF+ records (type, flags, data) after an EmfPlusHeader.
|
||||
let mut plus = vec![];
|
||||
let header = (0x4001u16, 0u16, [0xDBC0_1002u32, 0, 96, 96].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>());
|
||||
for (kind, flags, data) in std::iter::once(&header).chain(&records) {
|
||||
plus.extend(kind.to_le_bytes());
|
||||
plus.extend(flags.to_le_bytes());
|
||||
plus.extend((12 + data.len() as u32).to_le_bytes());
|
||||
plus.extend((data.len() as u32).to_le_bytes());
|
||||
plus.extend(data);
|
||||
}
|
||||
let mut comment = (4 + plus.len() as u32).to_le_bytes().to_vec();
|
||||
comment.extend(b"EMF+");
|
||||
comment.extend(plus);
|
||||
survive_metafile("EMF+ records", "x.emf", &emf_of(&[(70, comment)]))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_metafiles_never_panic(which in 0usize..2, cut in 0usize..200_000, edits in prop::collection::vec((0usize..200_000, any::<u8>()), 0..12)) {
|
||||
paste_from_elsewhere("clipboard.importEmf", json!({"dataBase64": mutated_b64(metafile_samples()[which].clone(), cut, &edits)}))?;
|
||||
|
||||
@@ -1187,6 +1187,32 @@ fn a_symbol_definition_is_written_only_with_room_for_its_instance() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A live instance inside a stained instance's art, whose definition has no room left, is left out
|
||||
/// without upsetting the art around it: with room for any number of objects the export finishes,
|
||||
/// within that room.
|
||||
#[test]
|
||||
fn a_definition_without_room_inside_drawn_art_is_left_out() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let leaf = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaf) });
|
||||
let inner = instance(&mut doc, "Leaf", Affine::translate((5.0, 5.0)));
|
||||
let side = square(&mut doc, Rect::new(20.0, 0.0, 30.0, 10.0), Color::gray(0.5));
|
||||
let art = group(&mut doc, vec![inner, side], false);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Branch".into(), art: Arc::new(art) });
|
||||
let mut stained = instance(&mut doc, "Branch", Affine::translate((50.0, 10.0)));
|
||||
stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
doc.insert(Some(layer), usize::MAX, stained).unwrap();
|
||||
add_rect(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0));
|
||||
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
for max in 0..read {
|
||||
let out = export_within(&doc, &opts(), max).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "art is left out with room for {max} of {read} objects");
|
||||
let objects = crate::import::objects_read(&out.program).unwrap();
|
||||
assert!(objects <= max, "{objects} objects read with room for {max}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol definition without room for its group, asked for by an instance in art drawn for an
|
||||
/// object (a stained instance's art), is left out and leaves the writing of that art as it was.
|
||||
#[test]
|
||||
@@ -10168,6 +10194,119 @@ fn envelopes_past_the_readers_checks_are_written_as_their_art() {
|
||||
assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
|
||||
}
|
||||
|
||||
/// A document of `envelopes` envelopes and `images` embedded images with one Warp, the images first
|
||||
/// when `images_first`, saved and opened again: the live envelopes, the images with their Warp live
|
||||
/// and all the objects it opens with, the save's warnings and the open's notes.
|
||||
fn envelopes_and_warped_images(envelopes: usize, images: usize, images_first: bool) -> (usize, usize, usize, Vec<String>, Vec<String>) {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let add_images = |doc: &mut Document| {
|
||||
for _ in 0..images {
|
||||
let photo = warped_photo(doc, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]);
|
||||
doc.insert(Some(layer), usize::MAX, photo).unwrap();
|
||||
}
|
||||
};
|
||||
if images_first {
|
||||
add_images(&mut doc);
|
||||
}
|
||||
for _ in 0..envelopes {
|
||||
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
|
||||
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
|
||||
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
}
|
||||
if !images_first {
|
||||
add_images(&mut doc);
|
||||
}
|
||||
let (p, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let a = back.layers[0].children().unwrap();
|
||||
let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count();
|
||||
let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count();
|
||||
(live, warped, a.len(), warnings, notes)
|
||||
}
|
||||
|
||||
/// Images with a Warp take the reader's checks as envelopes do: past them, an image is written as
|
||||
/// its drawn look, with a warning, and the file opens with every object written live still live.
|
||||
#[test]
|
||||
fn warped_images_past_the_readers_checks_are_written_as_their_drawn_look() {
|
||||
// GUARDS: images with a Warp were written live past the checks the envelopes left, and the
|
||||
// file opened with the last one as its drawn look and no warning on saving.
|
||||
let limit = crate::import::ENVELOPE_CHECKS;
|
||||
let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, false);
|
||||
assert_eq!((live, warped, all), (limit - 1, 1, limit + 1), "{warnings:?} {notes:?}");
|
||||
assert!(warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
|
||||
}
|
||||
|
||||
/// An image with a Warp whose pixels can't be read is written as its gray outline, which the reader
|
||||
/// doesn't check: it leaves its check to the objects after it.
|
||||
#[test]
|
||||
fn a_warped_image_written_as_its_outline_takes_no_check() {
|
||||
// GUARDS: an image written as its gray outline took a check, and the image after it lost its Warp.
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let limit = crate::import::ENVELOPE_CHECKS;
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
for _ in 0..limit - 1 {
|
||||
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
|
||||
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
|
||||
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
}
|
||||
let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0}));
|
||||
let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None);
|
||||
broken.appearance = Appearance { effects: vec![arc()], ..Appearance::default() }.into();
|
||||
doc.insert(Some(layer), usize::MAX, broken).unwrap();
|
||||
let photo = warped_photo(&mut doc, vec![arc()]);
|
||||
doc.insert(Some(layer), usize::MAX, photo).unwrap();
|
||||
let (p, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let a = back.layers[0].children().unwrap();
|
||||
let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count();
|
||||
assert_eq!(warped, 1, "{notes:?}");
|
||||
}
|
||||
|
||||
/// Past the reader's checks, an image with a Warp whose pixels can't be read is still written as its
|
||||
/// gray outline, with the warning for its pixels and not the one for the checks.
|
||||
#[test]
|
||||
fn an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels() {
|
||||
// GUARDS: an image whose pixels can't be read was warned about as past the checks.
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let limit = crate::import::ENVELOPE_CHECKS;
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
for _ in 0..limit {
|
||||
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
|
||||
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
|
||||
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
}
|
||||
let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None);
|
||||
broken.appearance = Appearance { effects: vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))], ..Appearance::default() }.into();
|
||||
doc.insert(Some(layer), usize::MAX, broken).unwrap();
|
||||
let (_, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Envelopes after images with a Warp get the checks the images left: past them, an envelope is
|
||||
/// written as its art, with a warning.
|
||||
#[test]
|
||||
fn envelopes_get_the_checks_warped_images_left() {
|
||||
// GUARDS: envelopes were written live past the checks the images with a Warp before them left.
|
||||
let limit = crate::import::ENVELOPE_CHECKS;
|
||||
let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, true);
|
||||
assert_eq!((live, warped, all), (limit - 2, 2, limit + 1), "{warnings:?} {notes:?}");
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}");
|
||||
assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
|
||||
}
|
||||
|
||||
/// Every Envelope Options switch and the ends of Fidelity come back as saved.
|
||||
#[test]
|
||||
fn envelope_options_and_fidelity_are_read_back() {
|
||||
@@ -10695,4 +10834,25 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}");
|
||||
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
|
||||
}
|
||||
|
||||
// The outer clipping object ends at x = 100 and the clipping path's fill starts at x = 101: the
|
||||
// fill is cut away and writes nothing, and its 4 pt stroke, which reaches x = 99, keeps the
|
||||
// options, whether or not the fill's lock state is written before it.
|
||||
for locked in [false, true] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(101.0, 20.0, 150.0, 80.0)));
|
||||
cutter.appearance = Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 4.0).into();
|
||||
cutter.locked = locked;
|
||||
let cutter = wrapped(cutter, 5.0, true);
|
||||
let member = square(&mut doc, Rect::new(110.0, 30.0, 140.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let inner = group(&mut doc, vec![cutter, member], true);
|
||||
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
|
||||
let frame = group(&mut doc, vec![frame], false);
|
||||
let outer = group(&mut doc, vec![frame, inner], true);
|
||||
doc.insert(Some(layer), usize::MAX, outer).unwrap();
|
||||
let text = program(&doc);
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "locked {locked}: {text}");
|
||||
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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:`,
|
||||
|
||||
@@ -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, .. } => {
|
||||
|
||||
@@ -631,6 +631,7 @@ impl<'a> Reader<'a> {
|
||||
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
|
||||
spec.series_paints = paints;
|
||||
spec.placed = Some(placed);
|
||||
spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c));
|
||||
tag_series(art, &tags);
|
||||
art.extras_mut().graph = Some(Box::new(spec));
|
||||
true
|
||||
|
||||
@@ -98,7 +98,7 @@ pub(crate) struct Interp<'a> {
|
||||
/// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in
|
||||
/// a font of its own (see `text`).
|
||||
pub kshow_font: Option<DictRef>,
|
||||
/// The `cshow` procedure running over type in a CIDFont only named, with the font it sees as
|
||||
/// The `cshow` procedure running over a composite font's type, with the font it sees as
|
||||
/// current (see `text`).
|
||||
pub cshow: Option<super::text::CShowFont>,
|
||||
pub g: GState,
|
||||
|
||||
@@ -136,6 +136,31 @@ fn codes_map_by_their_codespace_with_notdef_fallbacks() {
|
||||
width("<01>", 30.0);
|
||||
}
|
||||
|
||||
/// `cshow` over a CMap runs its procedure once for each code, whatever its length, with the
|
||||
/// code's last byte and its width (PLRM 3rd ed., `cshow`).
|
||||
#[test]
|
||||
fn cshow_runs_once_for_each_cmap_code() {
|
||||
let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP;
|
||||
let check = |cond: &str| check(&format!("{fonts} /TestFont 50 selectfont {cond}"));
|
||||
check("[ {pop pop} <418001> cshow ] dup length 2 eq exch aload pop 1 eq exch 65 eq and and");
|
||||
check("0 {pop exch pop add} <418001> cshow 55 sub abs 0.01 lt");
|
||||
check(
|
||||
"{pop pop pop currentfont /CIDFontName get /seen exch def rootfont /FontName get /root exch def} <41> cshow seen /TestCID eq root /TestFont eq and",
|
||||
);
|
||||
// With the CIDFont current, the byte the procedure was given shows the glyph of its code's
|
||||
// CID: <8001>'s last byte draws CID 2, not code 01's CID 1. Another string is an error.
|
||||
let shown = "{pop pop ( ) dup 0 4 -1 roll put show} <418001> cshow";
|
||||
check(&format!("gsave nulldevice 10 20 moveto {shown} currentpoint grestore pop 65 sub abs 0.01 lt"));
|
||||
check("gsave nulldevice 10 20 moveto {{pop pop pop (B) show} <41> cshow} stopped grestore");
|
||||
let r = import(&program(true, &format!("/TestFont 50 selectfont 10 20 moveto {shown}"))).unwrap();
|
||||
let want = import(&program(true, "/TestFont 50 selectfont 10 20 moveto <418001> show")).unwrap();
|
||||
let (p, q) = (paths(&r), paths(&want));
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
for (a, b) in p.iter().zip(&q) {
|
||||
assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01 && (a.height() - b.height()).abs() < 0.01, "{p:?} {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `kshow` over a CMap runs its procedure between each two codes with their values, whatever
|
||||
/// their length, and the next character follows where it moves the point (PLRM 3rd ed., `kshow`).
|
||||
#[test]
|
||||
@@ -188,6 +213,22 @@ fn type2_cidfonts_draw_their_truetype_glyphs_through_cidmap() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `cshow` procedure over a Type 2 CIDFont without a `FontMatrix` sees the CIDFont current at
|
||||
/// the scale its glyphs are drawn at: an em of the composite font's size, as with the identity.
|
||||
#[test]
|
||||
fn cshow_over_a_type2_cidfont_without_a_matrix_sees_it_at_its_drawn_scale() {
|
||||
let (h, i) = (glyph('H').0, glyph('I').0);
|
||||
let with = cid2_font(&format!("<0000{h:04x}{i:04x}>"));
|
||||
let without = with.replace("/FontMatrix [1 0 0 1 0 0] def", "");
|
||||
assert_ne!(with, without);
|
||||
for fonts in [with, without] {
|
||||
check(&format!(
|
||||
"{fonts}/T2 /Identity-H [/TestCID2] composefont 50 scalefont setfont \
|
||||
{{pop pop pop currentfont /FontMatrix get 0 get /m exch def}} <0001> cshow m 50 sub abs 0.01 lt"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// `Identity-V`: each glyph an em below the one before (writing mode 1).
|
||||
#[test]
|
||||
fn identity_v_sets_glyphs_downwards() {
|
||||
@@ -385,6 +426,30 @@ fn cmaps_map_codes_to_base_fonts_codes_and_glyph_names() {
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(text, "ABC");
|
||||
// A `cshow` procedure that shows the byte it was given, in the base font current while it
|
||||
// runs, shows the character the code maps to, as `show` does.
|
||||
let body = format!(
|
||||
"{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 20 scalefont setfont 10 20 moveto \
|
||||
{{pop pop ( ) dup 0 4 -1 roll put show}} <001000110012> cshow"
|
||||
);
|
||||
let r = super::tests::read(&body);
|
||||
let text: String = all(&r.document)
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.plain_text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(text, "ABC");
|
||||
let body = format!(
|
||||
"{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto \
|
||||
{{pop pop ( ) dup 0 4 -1 roll put show}} <000100020003> cshow"
|
||||
);
|
||||
let q = paths(&super::tests::read(&body));
|
||||
assert_eq!(q.len(), 3, "{q:?}");
|
||||
for (a, b) in p.iter().zip(&q) {
|
||||
assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01, "{p:?} {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A CID-keyed font over a predefined Unicode CMap the file doesn't define, its CIDFont only
|
||||
|
||||
@@ -119,6 +119,45 @@ fn widthshow_matches_a_composite_character_by_font_number_and_code() {
|
||||
check(format!("{} {} sub abs 0.01 lt", end(2), 10.0 + 100.0 * wh));
|
||||
}
|
||||
|
||||
/// `cshow` runs its procedure once for each character of a composite font, not for each byte,
|
||||
/// with the last byte of its code and its width, and with the descendant that draws it as the
|
||||
/// current font while `rootfont` gives the composite font (PLRM 3rd ed., `cshow` and `rootfont`).
|
||||
#[test]
|
||||
fn cshow_runs_once_for_each_composite_character_in_its_descendant() {
|
||||
let (_, wh) = glyph('H');
|
||||
let (_, wi) = glyph('I');
|
||||
let check = |cond: String| super::tests::check(&format!("{} /Comp findfont 50 scalefont setfont {cond}", fonts()));
|
||||
check("[ {pop pop} (\\000\\001\\000\\002) cshow ] dup length 2 eq exch aload pop 2 eq exch 1 eq and and".into());
|
||||
check(format!("0 {{pop exch pop add}} (\\000\\001\\000\\002) cshow {} sub abs 0.01 lt", 50.0 * (wh + wi)));
|
||||
check("{pop pop pop currentfont /FontName get /seen exch def rootfont /FontName get /root exch def} (\\000\\001) cshow seen /T42 eq root /Comp eq and".into());
|
||||
check("{pop pop pop} (\\000\\001) cshow currentfont /FontName get /Comp eq".into());
|
||||
// A character the procedure shows in the descendant is as wide as the composite font sets it.
|
||||
check(format!(
|
||||
"gsave nulldevice 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} (\\000\\001\\000\\002) cshow currentpoint grestore pop {} sub abs 0.01 lt",
|
||||
10.0 + 50.0 * (wh + wi)
|
||||
));
|
||||
// A character in font number 1 still gives only the last byte of its code, not 258.
|
||||
let two = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def");
|
||||
super::tests::check(&format!("{two} /Comp findfont 50 scalefont setfont [ {{pop pop}} (\\001\\002) cshow ] dup length 1 eq exch 0 get 2 eq and"));
|
||||
}
|
||||
|
||||
/// A `cshow` procedure over a Type 42 descendant without a `FontMatrix` sees it current at the
|
||||
/// scale its characters are drawn at: another character it measures there is as wide as the
|
||||
/// composite font sets it, as with the identity.
|
||||
#[test]
|
||||
fn cshow_over_a_type42_descendant_without_a_matrix_sees_it_at_its_drawn_scale() {
|
||||
let (_, wi) = glyph('I');
|
||||
let with = fonts();
|
||||
let without = with.replacen("/FontType 42 def /FontMatrix [1 0 0 1 0 0] def", "/FontType 42 def", 1);
|
||||
assert_ne!(with, without);
|
||||
for fonts in [with, without] {
|
||||
super::tests::check(&format!(
|
||||
"{fonts} /Comp findfont 50 scalefont setfont {{pop pop pop (\\002) stringwidth pop /w exch def}} (\\000\\001) cshow w {} sub abs 0.01 lt",
|
||||
50.0 * wi
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// `kshow` runs its procedure between each two characters of a composite font, with the values of
|
||||
/// their codes (font number times 256 plus code), and the next character follows where it moves
|
||||
/// the current point (PLRM 3rd ed., `kshow`).
|
||||
|
||||
@@ -251,6 +251,15 @@ impl Interp<'_> {
|
||||
self.g.font = root;
|
||||
return r;
|
||||
}
|
||||
// In a composite font the file carries, once for each character it maps.
|
||||
if let Some(glyphs) = self.composite_glyphs(&s)? {
|
||||
let root = self.g.font.clone();
|
||||
let before = self.cshow.take();
|
||||
let r = self.composite_cshow(&glyphs, &proc, root.clone());
|
||||
self.cshow = before;
|
||||
self.g.font = root;
|
||||
return r;
|
||||
}
|
||||
for b in s {
|
||||
let v = self.width_of(&[b])?;
|
||||
self.push(Obj::Int(i64::from(b)))?;
|
||||
@@ -992,6 +1001,7 @@ impl Spacing {
|
||||
/// A character of a composite font: the descendant font that draws it, its code there (its last
|
||||
/// byte for a CID), its CID and the notdef mapping's (`FMapType` 9), the composite font's matrix
|
||||
/// (over the descendant's own) and whether it is set vertically (`WMode` 1).
|
||||
#[derive(Clone)]
|
||||
struct Mapped {
|
||||
font: DictRef,
|
||||
/// The byte that picked the descendant (the font number).
|
||||
@@ -1006,6 +1016,13 @@ struct Mapped {
|
||||
value: u32,
|
||||
}
|
||||
|
||||
impl Mapped {
|
||||
/// The last byte of the character's code in the shown string (what `cshow` gives its procedure).
|
||||
fn last(&self) -> u8 {
|
||||
(self.value & 0xff) as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes
|
||||
/// with their characters, the font it is set in, whether it runs down a column, and whether each
|
||||
/// code moves the point one em (down a column, or in a CMap VectorCraft can't read).
|
||||
@@ -1016,13 +1033,15 @@ struct NamedCid {
|
||||
ems: bool,
|
||||
}
|
||||
|
||||
/// A `cshow` procedure running over type in a CIDFont only named ([`Interp::named_cshow`]): the
|
||||
/// CIDFont it sees as current, the composite font `rootfont` gives while that CIDFont is current,
|
||||
/// and the type of the code it was given.
|
||||
/// A `cshow` procedure running over a composite font's type ([`Interp::named_cshow`],
|
||||
/// [`Interp::composite_cshow`]): the descendant it sees as current, the composite font `rootfont`
|
||||
/// gives while that descendant is current, and the code it was given: over a CIDFont only named,
|
||||
/// its type; over a composite font the file carries, the character it maps to.
|
||||
pub(super) struct CShowFont {
|
||||
selected: DictRef,
|
||||
root: DictRef,
|
||||
code: NamedCid,
|
||||
code: Option<NamedCid>,
|
||||
mapped: Option<Mapped>,
|
||||
}
|
||||
|
||||
/// What drawing a glyph does with it.
|
||||
@@ -1069,6 +1088,22 @@ impl Interp<'_> {
|
||||
/// codes mapped to a descendant and a CID, §5.11.5); `None` for other fonts and mappings,
|
||||
/// which are set as type in the font of the composite font's name.
|
||||
fn composite_glyphs(&mut self, s: &[u8]) -> Res<Option<Vec<Mapped>>> {
|
||||
// Inside a `cshow` procedure over a composite font the file carries, with the descendant
|
||||
// it selected current, the one byte the procedure was given stands for the character its
|
||||
// code maps to: a CMap's CID, base-font code or glyph name. In a CIDFont any other string
|
||||
// is a `rangecheck` error (PLRM 3rd ed., `cshow`: the glyph of the selected CID); in a
|
||||
// base font it is shown as it is.
|
||||
if let Some(c) = self.cshow.as_ref()
|
||||
&& let Some(mapped) = c.mapped.as_ref()
|
||||
&& self.g.font.as_ref().is_some_and(|f| f.same(&c.selected))
|
||||
{
|
||||
if s == [mapped.last()] {
|
||||
return Ok(Some(vec![mapped.clone()]));
|
||||
}
|
||||
if mapped.cid.is_some() {
|
||||
return ps_err("rangecheck", "a string shown in cshow");
|
||||
}
|
||||
}
|
||||
let Some(font) = self.g.font.clone() else { return Ok(None) };
|
||||
let map = {
|
||||
let f = font.borrow();
|
||||
@@ -1220,17 +1255,18 @@ impl Interp<'_> {
|
||||
/// that code when `code` and with none otherwise, while the CIDFont it selected is current.
|
||||
fn cshow_code(&self, code: bool) -> Option<NamedCid> {
|
||||
let c = self.cshow.as_ref()?;
|
||||
let given = c.code.as_ref()?;
|
||||
if !self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) {
|
||||
return None;
|
||||
}
|
||||
let mut codes = Decoded::default();
|
||||
if code {
|
||||
let mut chars = c.code.codes.text.chars();
|
||||
for &(value, n) in &c.code.codes.codes {
|
||||
let mut chars = given.codes.text.chars();
|
||||
for &(value, n) in &given.codes.codes {
|
||||
codes.push(value, chars.by_ref().take(n));
|
||||
}
|
||||
}
|
||||
Some(NamedCid { codes, font: c.code.font.clone(), vertical: c.code.vertical, ems: c.code.ems })
|
||||
Some(NamedCid { codes, font: given.font.clone(), vertical: given.vertical, ems: given.ems })
|
||||
}
|
||||
|
||||
/// The CMap's name, the composite font, the CIDFont's name and the writing mode of
|
||||
@@ -1318,7 +1354,7 @@ impl Interp<'_> {
|
||||
self.push(Obj::Int(i64::from(code & 0xff)))?;
|
||||
self.push_num(v.x)?;
|
||||
self.push_num(v.y)?;
|
||||
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: one });
|
||||
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: Some(one), mapped: None });
|
||||
self.g.font = Some(selected.clone());
|
||||
let go = self.body(proc);
|
||||
self.g.font = root.clone();
|
||||
@@ -1329,6 +1365,41 @@ impl Interp<'_> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `cshow`'s procedure `proc` run for each character `glyphs` of composite font `root` maps,
|
||||
/// with the last byte of its code and its width (PLRM 3rd ed., `cshow`). While it runs the
|
||||
/// descendant that draws the character, at the size the composite font sets it, is the current
|
||||
/// font and `rootfont` gives `root`. The current font is restored when the procedure completes.
|
||||
fn composite_cshow(&mut self, glyphs: &[Mapped], proc: &Obj, root: Option<DictRef>) -> Res {
|
||||
let Some(composite) = root.clone() else { return Ok(()) };
|
||||
for g in glyphs {
|
||||
let v = self.composite_glyph(g, Point::ZERO, Draw::No)?;
|
||||
self.push(Obj::Int(i64::from(g.last())))?;
|
||||
self.push_num(v.x)?;
|
||||
self.push_num(v.y)?;
|
||||
// Scaling the descendant copies its dictionary for every character: charged by its
|
||||
// size, so a huge font dictionary in a loop runs out of the budget.
|
||||
let entries = g.font.borrow().len();
|
||||
self.spend(entries as u64)?;
|
||||
// Without a matrix, a Type 42 font or a Type 2 CIDFont is in ems, as `composite_glyph`
|
||||
// and `cid_glyph_at` draw it.
|
||||
let selected = {
|
||||
let f = g.font.borrow();
|
||||
let default = if units(&f) == 1.0 { 1.0 } else { 0.001 };
|
||||
let mut d = f.clone();
|
||||
d.insert(Key::name("FontMatrix"), matrix_obj(g.outer * font_matrix(&f, default)));
|
||||
DictRef::new(d)
|
||||
};
|
||||
self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: None, mapped: Some(g.clone()) });
|
||||
self.g.font = Some(selected);
|
||||
let go = self.body(proc);
|
||||
self.g.font = root.clone();
|
||||
if !go? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How far codes `codes` of type `named` move the current point (user space) when
|
||||
/// [`Self::show_named_cid`] shows them with no extra spacing.
|
||||
fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res<Vec2> {
|
||||
|
||||
@@ -489,8 +489,11 @@ impl<'a> Scene<'a> {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
// Off the region, an object is still written when brush art painted along its brushed
|
||||
// strokes, or those of the objects in it, can reach the region.
|
||||
let off = |b: Rect, reach: f64| !overlaps(b.inflate(1.0 + reach, 1.0 + reach), self.o.region);
|
||||
match n.visual_bounds_with(&self.symbols) {
|
||||
Some(b) if !force && !overlaps(b.inflate(1.0, 1.0), self.o.region) => return,
|
||||
Some(b) if !force && off(b, 0.0) && off(b, vectorcraft_brush::reach_within(n)) => return,
|
||||
None if !n.is_container() => return,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -1654,6 +1654,59 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() {
|
||||
assert!(page.contains("1 0 0 rg"), "{page}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_whose_brush_art_reaches_the_region_is_written() {
|
||||
// A line from (-5, 40) to (-5, 60) with a 1 pt red stroke painted by a 20 pt round nib lies
|
||||
// left of the artboard, and the nib paints 10 pt either side of it, onto the artboard: alone, in
|
||||
// a group and as a compound path. Without its brush, or 100 pt left of the artboard, where the
|
||||
// nib does not reach it, the line is left out.
|
||||
let red = |x: f64, brushed: bool| {
|
||||
let mut n = Node::path(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
shapes::line((x, 40.0).into(), (x, 60.0).into()),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0),
|
||||
);
|
||||
if brushed {
|
||||
n.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
|
||||
}
|
||||
n
|
||||
};
|
||||
let cases: [(&str, f64, bool, bool); 5] = [
|
||||
("path", -5.0, true, true),
|
||||
("group", -5.0, true, true),
|
||||
("compound path", -5.0, true, true),
|
||||
("unbrushed path", -5.0, false, false),
|
||||
("far path", -100.0, true, false),
|
||||
];
|
||||
for (what, x, brushed, written) in cases {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
|
||||
panic!("the 3 pt. Round brush")
|
||||
};
|
||||
c.size = 20.0;
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let line = red(x, brushed);
|
||||
let mut n = match what {
|
||||
"group" => Node::group(vectorcraft_doc::NodeId(0), vec![Arc::new(line)]),
|
||||
"compound path" => {
|
||||
let mut c = Node::new(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
NodeKind::Compound { children: vec![Arc::new(red(x, false))], rule: vectorcraft_geom::FillRule::NonZero },
|
||||
);
|
||||
c.appearance = line.appearance;
|
||||
c
|
||||
}
|
||||
_ => line,
|
||||
};
|
||||
n.id = d.alloc_id();
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let page = page_of(&d, &opts(&d));
|
||||
assert_eq!(page.contains("1 0 0 rg") || page.contains("1 0 0 RG"), written, "{what}: {page}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_art_effects_are_written_where_they_draw() {
|
||||
// The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@@ -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"}},
|
||||
|
||||
@@ -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!({}))?),
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-metafile"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT) reader"
|
||||
description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-effects = { workspace = true }
|
||||
vectorcraft-brush = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
craft-metafile = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Little-endian values: the buffer both writers build records in, and a reader that never reads
|
||||
//! past its data (every read is an `Option`).
|
||||
//! Little-endian values: the buffer both writers build records in.
|
||||
|
||||
/// Bytes being written.
|
||||
#[derive(Default)]
|
||||
@@ -45,52 +44,3 @@ impl Out {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sequential little-endian reads from a slice.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Reader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, pos: 0 }
|
||||
}
|
||||
pub fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let b = self.data.get(self.pos..self.pos.checked_add(n)?)?;
|
||||
self.pos += n;
|
||||
Some(b)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
self.bytes(N)?.try_into().ok()
|
||||
}
|
||||
pub fn u16(&mut self) -> Option<u16> {
|
||||
self.array().map(u16::from_le_bytes)
|
||||
}
|
||||
pub fn i16(&mut self) -> Option<i16> {
|
||||
self.array().map(i16::from_le_bytes)
|
||||
}
|
||||
pub fn u32(&mut self) -> Option<u32> {
|
||||
self.array().map(u32::from_le_bytes)
|
||||
}
|
||||
pub fn i32(&mut self) -> Option<i32> {
|
||||
self.array().map(i32::from_le_bytes)
|
||||
}
|
||||
pub fn f32(&mut self) -> Option<f32> {
|
||||
self.array().map(f32::from_le_bytes)
|
||||
}
|
||||
pub fn skip(&mut self, n: usize) -> Option<()> {
|
||||
self.bytes(n).map(drop)
|
||||
}
|
||||
/// The bytes not read yet.
|
||||
pub fn rest(&self) -> &'a [u8] {
|
||||
self.data.get(self.pos..).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `len` bytes of `data` from `offset` (record-relative offsets read from untrusted files).
|
||||
pub(crate) fn slice(data: &[u8], offset: u32, len: u32) -> Option<&[u8]> {
|
||||
let start = usize::try_from(offset).ok()?;
|
||||
data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
|
||||
}
|
||||
+5
-283
@@ -1,30 +1,24 @@
|
||||
//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit
|
||||
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source); read from 1,
|
||||
//! 4, 8, 16, 24 and 32-bit uncompressed and bit-field bitmaps and from embedded JPEG and PNG.
|
||||
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source).
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use vectorcraft_doc::resample::{Resample, resized};
|
||||
|
||||
use crate::bytes::Reader;
|
||||
|
||||
/// Most pixels along a side of an image the writers store (larger ones are scaled down).
|
||||
const MAX_SIDE: u32 = 8192;
|
||||
/// Most pixels an image the writers store holds.
|
||||
const MAX_PIXELS: u64 = 1 << 24;
|
||||
/// Most pixels along a side, and in all, of a bitmap the reader decodes.
|
||||
/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes.
|
||||
pub(crate) const MAX_READ_SIDE: u32 = 1 << 15;
|
||||
pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26;
|
||||
/// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small
|
||||
/// file of many image records can't cost minutes of decoding (#3600).
|
||||
pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;
|
||||
/// What [`decode`] says of a bitmap past what is left of the file's budget.
|
||||
/// What [`charge`] says of a bitmap past what is left of the file's budget.
|
||||
pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may";
|
||||
|
||||
const BI_RGB: u32 = 0;
|
||||
const BI_BITFIELDS: u32 = 3;
|
||||
const BI_JPEG: u32 = 4;
|
||||
const BI_PNG: u32 = 5;
|
||||
|
||||
/// Pixels with straight (not premultiplied) alpha, row by row from the top.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -124,48 +118,6 @@ pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
|
||||
(header(img.width, img.height, 32, bits.len()), bits)
|
||||
}
|
||||
|
||||
/// How the fourth byte of 32-bit pixels reads.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Alpha {
|
||||
/// Unused (StretchDIBits and BitBlt ignore it): every pixel opaque.
|
||||
Ignore,
|
||||
/// Premultiplied alpha (AlphaBlend with per-pixel alpha).
|
||||
Premultiplied,
|
||||
}
|
||||
|
||||
/// A colour channel of `v` under `mask`, scaled to 0–255.
|
||||
fn channel(v: u32, mask: u32) -> u8 {
|
||||
if mask == 0 {
|
||||
return 0;
|
||||
}
|
||||
let shift = mask.trailing_zeros();
|
||||
let max = u64::from(mask >> shift);
|
||||
let x = u64::from((v & mask) >> shift);
|
||||
((x * 255 + max / 2) / max.max(1)).min(255) as u8
|
||||
}
|
||||
|
||||
/// PNG `bytes` without its compressed or text ancillary chunks (`iCCP`, `zTXt`, `iTXt`, `tEXt`),
|
||||
/// which the pixels don't need and which a decoder expands when it is made. Other bytes, and a PNG
|
||||
/// whose chunks don't read to the end, are returned as they are.
|
||||
fn png_without_metadata(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
|
||||
const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
|
||||
if !bytes.starts_with(SIGNATURE) {
|
||||
return bytes.into();
|
||||
}
|
||||
let mut out = SIGNATURE.to_vec();
|
||||
let mut at = SIGNATURE.len();
|
||||
while at < bytes.len() {
|
||||
let (Some(len), Some(kind)) = (bytes.get(at..at + 4), bytes.get(at + 4..at + 8)) else { return bytes.into() };
|
||||
let len = u32::from_be_bytes([len[0], len[1], len[2], len[3]]) as usize;
|
||||
let Some(end) = at.checked_add(12).and_then(|n| n.checked_add(len)).filter(|end| *end <= bytes.len()) else { return bytes.into() };
|
||||
if !matches!(kind, b"iCCP" | b"zTXt" | b"iTXt" | b"tEXt") {
|
||||
out.extend_from_slice(&bytes[at..end]);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded.
|
||||
pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
|
||||
let n = u64::from(w) * u64::from(h);
|
||||
@@ -173,215 +125,24 @@ pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a DIB from its BITMAPINFO (`bmi`: the header and colour table) and pixel `bits`, taking its
|
||||
/// pixels from what is `left` of the file's budget ([`MAX_FILE_PIXELS`]).
|
||||
pub(crate) fn decode(bmi: &[u8], bits: &[u8], alpha: Alpha, left: &mut u64) -> Result<Rgba, String> {
|
||||
let bad = || "a bitmap is damaged".to_string();
|
||||
let mut r = Reader::new(bmi);
|
||||
let size = r.u32().ok_or_else(bad)?;
|
||||
let (width, height, bpp, compression, colors, palette_entry, masks_at) = if size == 12 {
|
||||
// BITMAPCOREHEADER: 16-bit sizes, RGB triples.
|
||||
let w = i32::from(r.u16().ok_or_else(bad)?);
|
||||
let h = i32::from(r.u16().ok_or_else(bad)?);
|
||||
r.skip(2).ok_or_else(bad)?;
|
||||
let bpp = r.u16().ok_or_else(bad)?;
|
||||
(w, h, bpp, BI_RGB, 0, 3, 0)
|
||||
} else if size >= 40 {
|
||||
let w = r.i32().ok_or_else(bad)?;
|
||||
let h = r.i32().ok_or_else(bad)?;
|
||||
r.skip(2).ok_or_else(bad)?;
|
||||
let bpp = r.u16().ok_or_else(bad)?;
|
||||
let c = r.u32().ok_or_else(bad)?;
|
||||
r.skip(12).ok_or_else(bad)?;
|
||||
let used = r.u32().ok_or_else(bad)?;
|
||||
(w, h, bpp, c, used, 4, 40)
|
||||
} else {
|
||||
return Err(bad());
|
||||
};
|
||||
if compression == BI_JPEG || compression == BI_PNG {
|
||||
// The size comes from the image header, so an over-limit bitmap is refused before any pixels are decoded.
|
||||
// A PNG's compressed ICC profile and text chunks expand when its decoder is made, and
|
||||
// nothing here uses them: they are left out before the size is read and the pixels decoded.
|
||||
let bits = png_without_metadata(bits);
|
||||
let (w, h) = image::ImageReader::new(Cursor::new(&*bits)).with_guessed_format().map_err(|_| bad())?.into_dimensions().map_err(|_| bad())?;
|
||||
if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS {
|
||||
return Err("a bitmap is too large to read".into());
|
||||
}
|
||||
charge(w, h, left)?;
|
||||
let img = image::load_from_memory(&bits).map_err(|_| bad())?.to_rgba8();
|
||||
return Ok(Rgba { width: w, height: h, pixels: img.into_raw() });
|
||||
}
|
||||
if compression != BI_RGB && compression != BI_BITFIELDS {
|
||||
return Err("compressed (RLE) bitmaps can't be read yet".into());
|
||||
}
|
||||
let top_down = height < 0;
|
||||
let (w, h) = (width.unsigned_abs(), height.unsigned_abs());
|
||||
if w == 0 || h == 0 {
|
||||
return Err("a bitmap is empty".into());
|
||||
}
|
||||
if w > MAX_READ_SIDE || h > MAX_READ_SIDE || u64::from(w) * u64::from(h) > MAX_READ_PIXELS {
|
||||
return Err("a bitmap is too large to read".into());
|
||||
}
|
||||
let header_len = size as usize;
|
||||
// Bit-field masks follow a plain 40-byte header, or sit inside the larger ones.
|
||||
let fields = compression == BI_BITFIELDS;
|
||||
let masks: Option<[u32; 4]> = fields.then(|| {
|
||||
let mut m = Reader::new(bmi.get(masks_at..).unwrap_or_default());
|
||||
let rgb = [m.u32().unwrap_or(0), m.u32().unwrap_or(0), m.u32().unwrap_or(0)];
|
||||
// An alpha mask comes with BITMAPV3INFOHEADER and later.
|
||||
let a = if header_len >= 56 { m.u32().unwrap_or(0) } else { 0 };
|
||||
[rgb[0], rgb[1], rgb[2], a]
|
||||
});
|
||||
let palette_at = header_len + if fields && header_len == 40 { 12 } else { 0 };
|
||||
let bpp_u = u32::from(bpp);
|
||||
let palette: Vec<[u8; 3]> = if bpp_u <= 8 {
|
||||
let n = if colors == 0 { 1usize << bpp_u } else { (colors as usize).min(256) };
|
||||
bmi.get(palette_at..)
|
||||
.unwrap_or_default()
|
||||
.chunks_exact(palette_entry)
|
||||
.take(n)
|
||||
.map(|e| [e.get(2).copied().unwrap_or(0), e.get(1).copied().unwrap_or(0), e.first().copied().unwrap_or(0)])
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
if !matches!(bpp, 1 | 4 | 8 | 16 | 24 | 32) {
|
||||
return Err(format!("{bpp}-bit bitmaps can't be read"));
|
||||
}
|
||||
let row = stride(w, bpp_u).ok_or_else(bad)?;
|
||||
if bits.len() < row.checked_mul(h as usize).ok_or_else(bad)? {
|
||||
return Err(bad());
|
||||
}
|
||||
charge(w, h, left)?;
|
||||
let (mr, mg, mb, ma) = match (masks, bpp) {
|
||||
(Some([r, g, b, a]), _) => (r, g, b, a),
|
||||
(None, 16) => (0x7c00, 0x03e0, 0x001f, 0),
|
||||
_ => (0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0xff00_0000),
|
||||
};
|
||||
let mut pixels = Vec::with_capacity(w as usize * h as usize * 4);
|
||||
for y in 0..h as usize {
|
||||
let src_row = if top_down { y } else { h as usize - 1 - y };
|
||||
let line = bits.get(src_row * row..src_row * row + row).ok_or_else(bad)?;
|
||||
for x in 0..w as usize {
|
||||
let px: [u8; 4] = match bpp {
|
||||
1 | 4 | 8 => {
|
||||
let bit = x * bpp_u as usize;
|
||||
let byte = line.get(bit / 8).copied().unwrap_or(0);
|
||||
let idx = (byte >> (8 - bpp_u as usize - bit % 8)) & ((1u16 << bpp_u) - 1) as u8;
|
||||
let [r, g, b] = palette.get(idx as usize).copied().unwrap_or([0, 0, 0]);
|
||||
[r, g, b, 255]
|
||||
}
|
||||
16 => {
|
||||
let v = u32::from(u16::from_le_bytes([line.get(x * 2).copied().unwrap_or(0), line.get(x * 2 + 1).copied().unwrap_or(0)]));
|
||||
[channel(v, mr), channel(v, mg), channel(v, mb), 255]
|
||||
}
|
||||
24 => {
|
||||
let p = line.get(x * 3..x * 3 + 3).unwrap_or(&[0, 0, 0]);
|
||||
[p[2], p[1], p[0], 255]
|
||||
}
|
||||
_ => {
|
||||
let p = line.get(x * 4..x * 4 + 4).unwrap_or(&[0, 0, 0, 0]);
|
||||
let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]);
|
||||
let a = if alpha == Alpha::Premultiplied && ma != 0 { channel(v, ma) } else { 255 };
|
||||
let un =
|
||||
|c: u8| if alpha == Alpha::Premultiplied && a < 255 { (u32::from(c) * 255 / u32::from(a.max(1))).min(255) as u8 } else { c };
|
||||
[un(channel(v, mr)), un(channel(v, mg)), un(channel(v, mb)), if alpha == Alpha::Premultiplied { a } else { 255 }]
|
||||
}
|
||||
};
|
||||
pixels.extend_from_slice(&px);
|
||||
}
|
||||
}
|
||||
Ok(Rgba { width: w, height: h, pixels })
|
||||
}
|
||||
|
||||
/// A packed DIB (a BITMAPINFO and its bits, one after the other, as WMF records hold them) split
|
||||
/// into the two.
|
||||
pub(crate) fn split(packed: &[u8]) -> Option<(&[u8], &[u8])> {
|
||||
let mut r = Reader::new(packed);
|
||||
let size = r.u32()? as usize;
|
||||
let (bpp, compression, used, entry) = if size == 12 {
|
||||
r.skip(6)?;
|
||||
(r.u16()?, BI_RGB, 0, 3)
|
||||
} else {
|
||||
r.skip(10)?;
|
||||
let bpp = r.u16()?;
|
||||
let c = r.u32()?;
|
||||
r.skip(12)?;
|
||||
(bpp, c, r.u32()? as usize, 4)
|
||||
};
|
||||
let masks = if compression == BI_BITFIELDS && size == 40 { 12 } else { 0 };
|
||||
let colors = if used > 0 {
|
||||
used.min(256)
|
||||
} else if bpp <= 8 {
|
||||
1usize << bpp
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let len = size.checked_add(masks)?.checked_add(colors * entry)?;
|
||||
Some((packed.get(..len)?, packed.get(len..)?))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_pngs_compressed_metadata_is_left_out_before_it_is_decoded() {
|
||||
use image::ImageEncoder;
|
||||
let mut png = vec![];
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
encoder.set_icc_profile(vec![0; 1 << 20]).unwrap();
|
||||
encoder.write_image(&[10, 20, 30], 1, 1, image::ExtendedColorType::Rgb8).unwrap();
|
||||
assert!(png.windows(4).any(|w| w == b"iCCP"));
|
||||
let stripped = png_without_metadata(&png);
|
||||
assert!(!stripped.windows(4).any(|w| w == b"iCCP") && stripped.len() < png.len());
|
||||
let img = image::load_from_memory(&stripped).unwrap().to_rgba8();
|
||||
assert_eq!(img.get_pixel(0, 0).0, [10, 20, 30, 255]);
|
||||
// Not a PNG, or a PNG cut short: unchanged.
|
||||
assert_eq!(&*png_without_metadata(b"BM...."), b"BM....");
|
||||
assert_eq!(&*png_without_metadata(&png[..png.len() - 3]), &png[..png.len() - 3]);
|
||||
}
|
||||
|
||||
fn sample() -> Rgba {
|
||||
// 3 × 2: red, green, blue / half-transparent black, transparent, white.
|
||||
let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255];
|
||||
Rgba { width: 3, height: 2, pixels }
|
||||
}
|
||||
|
||||
/// A whole file's budget.
|
||||
fn budget() -> u64 {
|
||||
MAX_FILE_PIXELS
|
||||
}
|
||||
|
||||
/// A BITMAPINFOHEADER of an embedded PNG.
|
||||
fn png_header() -> Vec<u8> {
|
||||
let mut bmi = vec![0u8; 40];
|
||||
bmi[..4].copy_from_slice(&40u32.to_le_bytes());
|
||||
bmi[16..20].copy_from_slice(&BI_PNG.to_le_bytes());
|
||||
bmi
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_png_is_refused_from_its_header() {
|
||||
// A width over the limit in the IHDR chunk: decoding the pixels would fail with a different error.
|
||||
let png = crate::tests::png_claiming(MAX_READ_SIDE + 1, 1);
|
||||
let err = decode(&png_header(), &png, Alpha::Ignore, &mut budget()).unwrap_err();
|
||||
assert_eq!(err, "a bitmap is too large to read");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_share_the_file_budget() {
|
||||
// #3600: each bitmap is charged before it is decoded, and one past what is left is refused.
|
||||
let (bmi, bits) = rgb24(&sample(), 1.0);
|
||||
let mut left = 6 + 5;
|
||||
assert!(decode(&bmi, &bits, Alpha::Ignore, &mut left).is_ok());
|
||||
assert!(charge(3, 2, &mut left).is_ok());
|
||||
assert_eq!(left, 5);
|
||||
assert_eq!(decode(&bmi, &bits, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET);
|
||||
assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET);
|
||||
assert_eq!(left, 5, "a refused bitmap costs nothing");
|
||||
// An embedded PNG is charged from its header, so one past the budget is never decoded.
|
||||
let mut left = (1 << 20) - 1;
|
||||
let png = crate::tests::png_claiming(1 << 10, 1 << 10);
|
||||
assert_eq!(decode(&png_header(), &png, Alpha::Ignore, &mut left).unwrap_err(), OVER_BUDGET);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -405,45 +166,6 @@ mod tests {
|
||||
assert_eq!(&half[12..16], &[0, 0, 128, 128]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb24_round_trips_over_white() {
|
||||
let (bmi, bits) = rgb24(&sample(), 1.0);
|
||||
assert_eq!(bmi.len(), 40);
|
||||
// Rows of 9 bytes padded to 12.
|
||||
assert_eq!(bits.len(), 24);
|
||||
let back = decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap();
|
||||
assert_eq!((back.width, back.height), (3, 2));
|
||||
assert_eq!(&back.pixels[..12], &[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]);
|
||||
// Half-transparent black over white is mid grey; transparent is white.
|
||||
assert_eq!(&back.pixels[12..16], &[127, 127, 127, 255]);
|
||||
assert_eq!(&back.pixels[16..20], &[255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bgra32_round_trips_with_alpha() {
|
||||
let (bmi, bits) = bgra32(&sample(), 1.0);
|
||||
let back = decode(&bmi, &bits, Alpha::Premultiplied, &mut budget()).unwrap();
|
||||
assert_eq!(&back.pixels[..12], &sample().pixels[..12]);
|
||||
assert_eq!(back.pixels[15], 128);
|
||||
assert_eq!(back.pixels[19], 0);
|
||||
// Read as StretchDIBits does, alpha is ignored.
|
||||
assert!(decode(&bmi, &bits, Alpha::Ignore, &mut budget()).unwrap().opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_bitmaps_and_damage() {
|
||||
// A 1-bit 2 × 1 bitmap: black then white.
|
||||
let mut bmi = header(2, 1, 1, 4);
|
||||
bmi.extend_from_slice(&[0, 0, 0, 0, 255, 255, 255, 0]);
|
||||
let back = decode(&bmi, &[0b0100_0000, 0, 0, 0], Alpha::Ignore, &mut budget()).unwrap();
|
||||
assert_eq!(back.pixels, vec![0, 0, 0, 255, 255, 255, 255, 255]);
|
||||
// Too few bits, a silly size, an unknown depth: errors, no panic.
|
||||
assert!(decode(&bmi, &[0], Alpha::Ignore, &mut budget()).is_err());
|
||||
assert!(decode(&header(1 << 20, 1 << 20, 24, 0), &[], Alpha::Ignore, &mut budget()).is_err());
|
||||
assert!(decode(&header(1, 1, 7, 0), &[0; 4], Alpha::Ignore, &mut budget()).is_err());
|
||||
assert!(decode(&[1, 2], &[], Alpha::Ignore, &mut budget()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_images_are_scaled_to_fit() {
|
||||
let img = image::RgbaImage::new(MAX_SIDE * 2, 4);
|
||||
|
||||
+82
-558
@@ -1,16 +1,14 @@
|
||||
//! The metafile reader: the format parsers (`emf`, `wmf`, and `pict` for QuickDraw pictures) play
|
||||
//! their records on a [`Player`], a small model of the device context they draw into (objects,
|
||||
//! transforms, the current position, the path bracket, the clip), which turns what they draw into
|
||||
//! document objects.
|
||||
//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`,
|
||||
//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their
|
||||
//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which
|
||||
//! turns what they draw into document objects.
|
||||
//!
|
||||
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
|
||||
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
|
||||
//! their pixels (as PNG), text becomes point type in the font the file names. Records the reader
|
||||
//! doesn't know are counted and skipped, with one warning.
|
||||
//! their pixels (as PNG), text becomes point type in the font the file names.
|
||||
|
||||
mod emf;
|
||||
pub(crate) mod pict;
|
||||
mod wmf;
|
||||
mod picture;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -20,7 +18,7 @@ use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind,
|
||||
StrokeLayer, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, Vec2, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
|
||||
|
||||
use crate::dib::{self, Rgba};
|
||||
use crate::{Imported, Kind};
|
||||
@@ -30,24 +28,13 @@ const MAX_NODES: usize = 1 << 20;
|
||||
/// Objects and clips reaching further than this from the origin (points, well inside the canvas)
|
||||
/// are left out: they come from damaged or hostile coordinates.
|
||||
const LIMIT: f64 = 1e6;
|
||||
/// Most nested saved device contexts.
|
||||
const MAX_SAVED: usize = 1024;
|
||||
/// Width of a cosmetic pen (one pixel of a 96 ppi screen), points.
|
||||
const HAIRLINE: f64 = 0.75;
|
||||
/// Curves made for arcs and ellipses are this close to the true curve (logical units are
|
||||
/// transformed after, so it is relative).
|
||||
const ARC_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// Raster operations.
|
||||
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
|
||||
const PATCOPY: u32 = 0x00F0_0021;
|
||||
const WHITENESS: u32 = 0x00FF_0062;
|
||||
const BLACKNESS: u32 = 0x0000_0042;
|
||||
|
||||
const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out";
|
||||
const HATCHES: &str = "hatched brushes are filled with their colour";
|
||||
const PATTERN_BRUSHES: &str = "pattern brushes are filled grey";
|
||||
const EXCLUDED_CLIPS: &str = "clip areas cut out of the clip (excluded rectangles, differences) are ignored";
|
||||
const BAD_IMAGE: &str = "an image that couldn't be read was left out";
|
||||
const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out";
|
||||
const FAR_AWAY: &str = "objects far outside the picture were left out";
|
||||
@@ -57,6 +44,58 @@ fn sane(r: Rect) -> bool {
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= LIMIT)
|
||||
}
|
||||
|
||||
/// Is `path` one upright rectangle around the whole of `frame`? Writers clip to one first; it clips
|
||||
/// nothing in the picture. A path of more than one figure is not one rectangle, even when its
|
||||
/// figures run along the sides of a box. Nor is one figure that runs back over its own edges, so
|
||||
/// that it encloses less than the whole box.
|
||||
fn around(path: &BezPath, frame: Rect) -> bool {
|
||||
if path.elements().len() > 6 {
|
||||
return false;
|
||||
}
|
||||
let b = path.bounding_box();
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
|
||||
let near = |p: Point, q: Point| (p - q).hypot() <= 1e-6 * (1.0 + b.width().max(b.height()));
|
||||
// Each edge, the closing one included, runs along a side: from a corner to itself or to a
|
||||
// neighbor (corners are in order around the box), never across it.
|
||||
let along = |i: usize, j: usize| (i + 4 - j) % 4 != 2;
|
||||
let mut seen = [false; 4];
|
||||
let mut points = Vec::with_capacity(6);
|
||||
let (mut first, mut last) = (None, None);
|
||||
for e in path.elements() {
|
||||
let (p, start) = match e {
|
||||
PathEl::MoveTo(p) => (*p, true),
|
||||
PathEl::LineTo(p) => (*p, false),
|
||||
PathEl::ClosePath => continue,
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false,
|
||||
};
|
||||
let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false };
|
||||
if start {
|
||||
if first.is_some() {
|
||||
return false;
|
||||
}
|
||||
first = Some(i);
|
||||
} else if last.is_some_and(|l| !along(l, i)) {
|
||||
return false;
|
||||
}
|
||||
last = Some(i);
|
||||
seen[i] = true;
|
||||
points.push(corners[i]);
|
||||
}
|
||||
if let (Some(f), Some(l)) = (first, last)
|
||||
&& !along(f, l)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// Every edge runs along a side, so the figure winds the same number of times around every
|
||||
// point inside the box: once, when its area is the box's.
|
||||
let twice_area: f64 = points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| (*p - corners[0]).cross(*q - corners[0])).sum();
|
||||
if (twice_area.abs() - 2.0 * b.area()).abs() > 1e-6 * (1.0 + 2.0 * b.area()) {
|
||||
return false;
|
||||
}
|
||||
let b = b.inflate(0.5, 0.5);
|
||||
seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1))
|
||||
}
|
||||
|
||||
/// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct PenObj {
|
||||
@@ -68,7 +107,6 @@ pub(crate) struct PenObj {
|
||||
}
|
||||
|
||||
impl PenObj {
|
||||
pub const NULL: PenObj = PenObj { style: PS_NULL, width: 0.0, color: [0; 3], entries: vec![] };
|
||||
pub fn solid(color: [u8; 3]) -> Self {
|
||||
Self { style: 0, width: 0.0, color, entries: vec![] }
|
||||
}
|
||||
@@ -77,28 +115,6 @@ impl PenObj {
|
||||
pub(crate) const PS_NULL: u32 = 5;
|
||||
const PS_GEOMETRIC: u32 = 0x0001_0000;
|
||||
|
||||
/// A brush.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum BrushObj {
|
||||
Null,
|
||||
Solid([u8; 3]),
|
||||
Hatched([u8; 3]),
|
||||
/// A bitmap pattern (written grey).
|
||||
Pattern,
|
||||
}
|
||||
|
||||
impl BrushObj {
|
||||
/// From a LOGBRUSH's style and colour.
|
||||
pub fn from_log(style: u32, color: [u8; 3]) -> Self {
|
||||
match style {
|
||||
0 => Self::Solid(color),
|
||||
1 => Self::Null,
|
||||
2 => Self::Hatched(color),
|
||||
_ => Self::Pattern,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A font: its height in logical units (negative: the character height, positive: the cell
|
||||
/// height), escapement (tenths of a degree), weight, italics and face.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -110,35 +126,17 @@ pub(crate) struct FontObj {
|
||||
pub face: String,
|
||||
}
|
||||
|
||||
/// A GDI object.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Obj {
|
||||
Pen(PenObj),
|
||||
Brush(BrushObj),
|
||||
Font(FontObj),
|
||||
/// Palettes, regions, colour spaces: they take a slot but don't change the drawing.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// The state records change, saved and restored as a whole.
|
||||
/// The drawing state.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Dc {
|
||||
pen: PenObj,
|
||||
brush: BrushObj,
|
||||
/// The brush's color.
|
||||
brush: [u8; 3],
|
||||
font: FontObj,
|
||||
text_color: [u8; 3],
|
||||
text_align: u32,
|
||||
fill_rule: FillRule,
|
||||
miter: f64,
|
||||
/// Arcs run counterclockwise (the default).
|
||||
arc_ccw: bool,
|
||||
/// Logical → page (EMF world transform).
|
||||
world: Affine,
|
||||
map_mode: u32,
|
||||
win_org: Vec2,
|
||||
win_ext: Vec2,
|
||||
vp_org: Vec2,
|
||||
vp_ext: Vec2,
|
||||
clips: Vec<Arc<Clip>>,
|
||||
}
|
||||
|
||||
@@ -146,105 +144,38 @@ impl Default for Dc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pen: PenObj::solid([0; 3]),
|
||||
brush: BrushObj::Solid([255; 3]),
|
||||
brush: [255; 3],
|
||||
font: FontObj::default(),
|
||||
text_color: [0; 3],
|
||||
text_align: 0,
|
||||
fill_rule: FillRule::EvenOdd,
|
||||
miter: 10.0,
|
||||
arc_ccw: true,
|
||||
world: Affine::IDENTITY,
|
||||
map_mode: 1,
|
||||
win_org: Vec2::ZERO,
|
||||
win_ext: Vec2::new(1.0, 1.0),
|
||||
vp_org: Vec2::ZERO,
|
||||
vp_ext: Vec2::new(1.0, 1.0),
|
||||
clips: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an arc closes.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ArcKind {
|
||||
Open,
|
||||
Chord,
|
||||
Pie,
|
||||
}
|
||||
|
||||
pub(crate) struct Player {
|
||||
kind: Kind,
|
||||
/// Device units (EMF) or logical units (WMF) → document points.
|
||||
/// Picture units → document points.
|
||||
dev_to_doc: Affine,
|
||||
/// Millimetres per device pixel (EMF's fixed mapping modes).
|
||||
mm_per_px: f64,
|
||||
dc: Dc,
|
||||
saved: Vec<Dc>,
|
||||
objects: Vec<Option<Obj>>,
|
||||
/// The lowest object slot that may be free (WMF numbering).
|
||||
free_hint: usize,
|
||||
/// The path being recorded (document space), whether a figure is open in it and where that
|
||||
/// figure started (logical).
|
||||
path: Option<BezPath>,
|
||||
figure: bool,
|
||||
figure_start: Point,
|
||||
/// The artboard (document space): clips holding all of it clip nothing worth keeping.
|
||||
frame: Rect,
|
||||
/// The current position (logical).
|
||||
pos: Point,
|
||||
/// Lines drawn one after another outside a path bracket, not drawn yet.
|
||||
/// Lines drawn one after another, not drawn yet.
|
||||
pending: BezPath,
|
||||
out: Drawn,
|
||||
doc: Document,
|
||||
warnings: Vec<String>,
|
||||
skipped: usize,
|
||||
next_clip: u32,
|
||||
/// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]).
|
||||
pub pixels_left: u64,
|
||||
/// The file holds EMF+ records (which aren't read).
|
||||
pub emf_plus: bool,
|
||||
}
|
||||
|
||||
fn rgb(c: [u8; 3]) -> Paint {
|
||||
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
|
||||
}
|
||||
|
||||
/// The arc of the ellipse in `r` from the ray through `start` to the ray through `end`.
|
||||
pub(crate) fn arc_path(r: Rect, start: Point, end: Point, ccw: bool, kind: ArcKind) -> BezPath {
|
||||
let r = r.abs();
|
||||
let c = r.center();
|
||||
let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0);
|
||||
let mut bp = BezPath::new();
|
||||
if radii.x <= 0.0 || radii.y <= 0.0 {
|
||||
return bp;
|
||||
}
|
||||
let angle = |p: Point| ((p.y - c.y) / radii.y).atan2((p.x - c.x) / radii.x);
|
||||
let (a0, a1) = (angle(start), angle(end));
|
||||
let tau = std::f64::consts::TAU;
|
||||
// Counterclockwise on a y-down device is towards smaller angles.
|
||||
let sweep = if ccw {
|
||||
let s = (a0 - a1).rem_euclid(tau);
|
||||
-(if s == 0.0 { tau } else { s })
|
||||
} else {
|
||||
let s = (a1 - a0).rem_euclid(tau);
|
||||
if s == 0.0 { tau } else { s }
|
||||
};
|
||||
let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 };
|
||||
let tol = ARC_TOLERANCE * radii.x.max(radii.y).max(1e-9);
|
||||
if kind == ArcKind::Pie {
|
||||
bp.move_to(c);
|
||||
let first = c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin());
|
||||
bp.line_to(first);
|
||||
arc.append_iter(tol).for_each(|el| bp.push(el));
|
||||
} else {
|
||||
kurbo::Shape::path_elements(&arc, tol).for_each(|el| bp.push(el));
|
||||
}
|
||||
if kind != ArcKind::Open {
|
||||
bp.close_path();
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// A rectangle with elliptical corners `rx` × `ry`.
|
||||
pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
|
||||
let r = r.abs();
|
||||
@@ -261,7 +192,7 @@ pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
|
||||
}
|
||||
|
||||
impl Player {
|
||||
fn new(kind: Kind, dev_to_doc: Affine, mm_per_px: f64, artboard: Rect) -> Self {
|
||||
fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self {
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
|
||||
let (w, h) = (side(artboard.width()), side(artboard.height()));
|
||||
let mut doc = Document::new(w, h);
|
||||
@@ -269,24 +200,14 @@ impl Player {
|
||||
Self {
|
||||
kind,
|
||||
dev_to_doc,
|
||||
mm_per_px,
|
||||
dc: Dc::default(),
|
||||
saved: vec![],
|
||||
objects: vec![],
|
||||
free_hint: 0,
|
||||
path: None,
|
||||
figure: false,
|
||||
figure_start: Point::ZERO,
|
||||
frame: artboard,
|
||||
pos: Point::ZERO,
|
||||
pending: BezPath::new(),
|
||||
out: vec![],
|
||||
doc,
|
||||
warnings: vec![],
|
||||
skipped: 0,
|
||||
next_clip: 0,
|
||||
pixels_left: dib::MAX_FILE_PIXELS,
|
||||
emf_plus: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,188 +217,19 @@ impl Player {
|
||||
}
|
||||
}
|
||||
|
||||
/// A record of a kind the reader doesn't know.
|
||||
pub fn skip(&mut self) {
|
||||
self.skipped += 1;
|
||||
}
|
||||
|
||||
// ---------- mapping ----------
|
||||
|
||||
/// Logical → document.
|
||||
/// Picture units → document.
|
||||
fn xf(&self) -> Affine {
|
||||
if self.kind == Kind::Wmf {
|
||||
return self.dev_to_doc;
|
||||
}
|
||||
let d = &self.dc;
|
||||
let page_to_dev = match d.map_mode {
|
||||
// Fixed modes: millimetres a unit, y up.
|
||||
2..=6 => {
|
||||
let mm = [0.1, 0.01, 0.254, 0.0254, 25.4 / 1440.0][(d.map_mode - 2) as usize];
|
||||
let s = mm / self.mm_per_px.max(1e-12);
|
||||
Affine::translate(d.vp_org) * Affine::scale_non_uniform(s, -s) * Affine::translate(-d.win_org)
|
||||
}
|
||||
7 | 8 => {
|
||||
let ratio = |v: f64, w: f64| if w.abs() > 1e-12 && v.is_finite() { v / w } else { 1.0 };
|
||||
let (mut sx, mut sy) = (ratio(d.vp_ext.x, d.win_ext.x), ratio(d.vp_ext.y, d.win_ext.y));
|
||||
if d.map_mode == 7 {
|
||||
// Isotropic: the same scale both ways, the smaller one.
|
||||
let s = sx.abs().min(sy.abs());
|
||||
(sx, sy) = (s.copysign(sx), s.copysign(sy));
|
||||
}
|
||||
Affine::translate(d.vp_org) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-d.win_org)
|
||||
}
|
||||
_ => Affine::translate(d.vp_org - d.win_org),
|
||||
};
|
||||
self.dev_to_doc * page_to_dev * d.world
|
||||
self.dev_to_doc
|
||||
}
|
||||
|
||||
/// How much logical lengths grow in the document.
|
||||
/// How much picture lengths grow in the document.
|
||||
fn scale(&self) -> f64 {
|
||||
let s = self.xf().determinant().abs().sqrt();
|
||||
if s.is_finite() { s } else { 0.0 }
|
||||
}
|
||||
|
||||
pub fn set_map_mode(&mut self, m: u32) {
|
||||
self.dc.map_mode = m;
|
||||
}
|
||||
pub fn set_window_org(&mut self, x: f64, y: f64) {
|
||||
self.dc.win_org = Vec2::new(x, y);
|
||||
}
|
||||
pub fn set_window_ext(&mut self, x: f64, y: f64) {
|
||||
self.dc.win_ext = Vec2::new(x, y);
|
||||
}
|
||||
pub fn set_viewport_org(&mut self, x: f64, y: f64) {
|
||||
self.dc.vp_org = Vec2::new(x, y);
|
||||
}
|
||||
pub fn set_viewport_ext(&mut self, x: f64, y: f64) {
|
||||
self.dc.vp_ext = Vec2::new(x, y);
|
||||
}
|
||||
pub fn scale_ext(&mut self, window: bool, x: (f64, f64), y: (f64, f64)) {
|
||||
let e = if window { &mut self.dc.win_ext } else { &mut self.dc.vp_ext };
|
||||
if x.1 != 0.0 && y.1 != 0.0 {
|
||||
*e = Vec2::new(e.x * x.0 / x.1, e.y * y.0 / y.1);
|
||||
}
|
||||
}
|
||||
/// `SetWorldTransform` / `ModifyWorldTransform` (`mode`: 1 identity, 2 left, 3 right, 4 set).
|
||||
pub fn world(&mut self, x: Affine, mode: u32) {
|
||||
if !x.as_coeffs().iter().all(|v| v.is_finite()) {
|
||||
return;
|
||||
}
|
||||
self.dc.world = match mode {
|
||||
1 => Affine::IDENTITY,
|
||||
2 => self.dc.world * x,
|
||||
3 => x * self.dc.world,
|
||||
_ => x,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- state ----------
|
||||
|
||||
pub fn set_fill_mode(&mut self, alternate: bool) {
|
||||
self.dc.fill_rule = if alternate { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
}
|
||||
pub fn set_miter(&mut self, m: f64) {
|
||||
if m.is_finite() && m >= 1.0 {
|
||||
self.dc.miter = m;
|
||||
}
|
||||
}
|
||||
pub fn set_arc_ccw(&mut self, ccw: bool) {
|
||||
self.dc.arc_ccw = ccw;
|
||||
}
|
||||
pub fn set_text_color(&mut self, c: [u8; 3]) {
|
||||
self.dc.text_color = c;
|
||||
}
|
||||
pub fn set_text_align(&mut self, a: u32) {
|
||||
self.dc.text_align = a;
|
||||
}
|
||||
|
||||
pub fn save(&mut self) {
|
||||
if self.saved.len() < MAX_SAVED {
|
||||
self.saved.push(self.dc.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// `RestoreDC(n)`: a negative `n` counts back from the latest save, a positive one is a save's
|
||||
/// number.
|
||||
pub fn restore(&mut self, n: i32) {
|
||||
let len = self.saved.len();
|
||||
let keep = if n < 0 { len.checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1).filter(|k| *k < len) };
|
||||
if let Some(k) = keep {
|
||||
self.saved.truncate(k + 1);
|
||||
if let Some(dc) = self.saved.pop() {
|
||||
self.dc = dc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- objects ----------
|
||||
|
||||
/// Put `obj` in slot `index` (EMF numbers its objects).
|
||||
pub fn create_at(&mut self, index: u32, obj: Obj) {
|
||||
let i = index as usize;
|
||||
if i == 0 || i > u16::MAX as usize {
|
||||
return;
|
||||
}
|
||||
if self.objects.len() <= i {
|
||||
self.objects.resize(i + 1, None);
|
||||
}
|
||||
if let Some(s) = self.objects.get_mut(i) {
|
||||
*s = Some(obj);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `obj` in the lowest free slot (WMF).
|
||||
pub fn create(&mut self, obj: Obj) {
|
||||
let start = self.free_hint.min(self.objects.len());
|
||||
let i = self.objects.iter().skip(start).position(Option::is_none).map_or(self.objects.len(), |p| p + start);
|
||||
if i > u16::MAX as usize {
|
||||
// The table is full past the hint: the next creation looks from the end, not again
|
||||
// through every slot.
|
||||
self.free_hint = i;
|
||||
return;
|
||||
}
|
||||
if i == self.objects.len() {
|
||||
self.objects.push(None);
|
||||
}
|
||||
if let Some(s) = self.objects.get_mut(i) {
|
||||
*s = Some(obj);
|
||||
}
|
||||
self.free_hint = i + 1;
|
||||
}
|
||||
|
||||
pub fn delete(&mut self, index: u32) {
|
||||
if let Some(s) = self.objects.get_mut(index as usize) {
|
||||
*s = None;
|
||||
self.free_hint = self.free_hint.min(index as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Select object `index`, or a stock object (EMF: the high bit set).
|
||||
pub fn select(&mut self, index: u32) {
|
||||
if self.kind == Kind::Emf && index & 0x8000_0000 != 0 {
|
||||
match index & 0x7fff_ffff {
|
||||
0 | 18 => self.dc.brush = BrushObj::Solid([255; 3]),
|
||||
1 => self.dc.brush = BrushObj::Solid([0xc0; 3]),
|
||||
2 => self.dc.brush = BrushObj::Solid([0x80; 3]),
|
||||
3 => self.dc.brush = BrushObj::Solid([0x40; 3]),
|
||||
4 => self.dc.brush = BrushObj::Solid([0; 3]),
|
||||
5 => self.dc.brush = BrushObj::Null,
|
||||
6 => self.dc.pen = PenObj::solid([255; 3]),
|
||||
7 | 19 => self.dc.pen = PenObj::solid([0; 3]),
|
||||
8 => self.dc.pen = PenObj::NULL,
|
||||
10..=17 => self.dc.font = FontObj::default(),
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
match self.objects.get(index as usize).cloned().flatten() {
|
||||
Some(Obj::Pen(p)) => self.dc.pen = p,
|
||||
Some(Obj::Brush(b)) => self.dc.brush = b,
|
||||
Some(Obj::Font(f)) => self.dc.font = f,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- output ----------
|
||||
|
||||
fn push(&mut self, mut node: Node) {
|
||||
@@ -491,19 +243,8 @@ impl Player {
|
||||
self.out.push((self.dc.clips.clone(), node));
|
||||
}
|
||||
|
||||
fn fill_paint(&mut self) -> Option<Paint> {
|
||||
match self.dc.brush.clone() {
|
||||
BrushObj::Null => None,
|
||||
BrushObj::Solid(c) => Some(rgb(c)),
|
||||
BrushObj::Hatched(c) => {
|
||||
self.warn(HATCHES);
|
||||
Some(rgb(c))
|
||||
}
|
||||
BrushObj::Pattern => {
|
||||
self.warn(PATTERN_BRUSHES);
|
||||
Some(rgb([0x80; 3]))
|
||||
}
|
||||
}
|
||||
fn fill_paint(&self) -> Paint {
|
||||
rgb(self.dc.brush)
|
||||
}
|
||||
|
||||
fn stroke_layer(&self) -> Option<StrokeLayer> {
|
||||
@@ -549,8 +290,8 @@ impl Player {
|
||||
return;
|
||||
}
|
||||
let mut items = vec![];
|
||||
if fill && let Some(p) = self.fill_paint() {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(p)));
|
||||
if fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint())));
|
||||
}
|
||||
if stroke && let Some(st) = self.stroke_layer() {
|
||||
items.push(AppearanceItem::Stroke(st));
|
||||
@@ -573,124 +314,7 @@ impl Player {
|
||||
}
|
||||
}
|
||||
|
||||
/// A figure in logical units: added to the path being recorded, else drawn (filled when it is
|
||||
/// an area).
|
||||
pub fn figure(&mut self, mut bp: BezPath, area: bool) {
|
||||
bp.apply_affine(self.xf());
|
||||
match &mut self.path {
|
||||
Some(path) => {
|
||||
path.extend(bp);
|
||||
self.figure = false;
|
||||
}
|
||||
None => self.draw(bp, area, true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Polygon / Polyline (and Bézier ones): `pts` in logical units.
|
||||
pub fn poly(&mut self, pts: &[Point], closed: bool, bezier: bool) {
|
||||
let Some((first, rest)) = pts.split_first() else { return };
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(*first);
|
||||
if bezier {
|
||||
for c in rest.as_chunks::<3>().0 {
|
||||
bp.curve_to(c[0], c[1], c[2]);
|
||||
}
|
||||
} else {
|
||||
rest.iter().for_each(|p| bp.line_to(*p));
|
||||
}
|
||||
if closed {
|
||||
bp.close_path();
|
||||
}
|
||||
self.figure(bp, closed);
|
||||
}
|
||||
|
||||
/// Several polygons (one area) or polylines.
|
||||
pub fn poly_poly(&mut self, polys: &[Vec<Point>], closed: bool) {
|
||||
let mut bp = BezPath::new();
|
||||
for p in polys {
|
||||
let Some((first, rest)) = p.split_first() else { continue };
|
||||
bp.move_to(*first);
|
||||
rest.iter().for_each(|q| bp.line_to(*q));
|
||||
if closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
self.figure(bp, closed);
|
||||
}
|
||||
|
||||
pub fn move_to(&mut self, p: Point) {
|
||||
self.pos = p;
|
||||
self.figure = false;
|
||||
}
|
||||
|
||||
/// LineTo / PolylineTo / PolyBezierTo: from the current position through `pts` (logical).
|
||||
pub fn poly_to(&mut self, pts: &[Point], bezier: bool) {
|
||||
let Some(last) = pts.last().copied() else { return };
|
||||
let xf = self.xf();
|
||||
let start = xf * self.pos;
|
||||
let target = match &mut self.path {
|
||||
Some(path) => {
|
||||
if !self.figure {
|
||||
path.move_to(start);
|
||||
self.figure = true;
|
||||
self.figure_start = self.pos;
|
||||
}
|
||||
path
|
||||
}
|
||||
None => {
|
||||
if self.pending.elements().last().and_then(|e| e.end_point()) != Some(start) {
|
||||
self.pending.move_to(start);
|
||||
}
|
||||
&mut self.pending
|
||||
}
|
||||
};
|
||||
if bezier {
|
||||
for c in pts.as_chunks::<3>().0 {
|
||||
target.curve_to(xf * c[0], xf * c[1], xf * c[2]);
|
||||
}
|
||||
} else {
|
||||
pts.iter().for_each(|p| target.line_to(xf * *p));
|
||||
}
|
||||
self.pos = last;
|
||||
}
|
||||
|
||||
pub fn arc(&mut self, r: Rect, start: Point, end: Point, kind: ArcKind) {
|
||||
let bp = arc_path(r, start, end, self.dc.arc_ccw, kind);
|
||||
self.figure(bp, kind != ArcKind::Open);
|
||||
}
|
||||
|
||||
// ---------- paths and clips ----------
|
||||
|
||||
pub fn begin_path(&mut self) {
|
||||
self.path = Some(BezPath::new());
|
||||
self.figure = false;
|
||||
}
|
||||
pub fn end_path(&mut self) {
|
||||
// The path stays until it is filled, stroked or made the clip.
|
||||
}
|
||||
pub fn close_figure(&mut self) {
|
||||
if let Some(p) = &mut self.path
|
||||
&& self.figure
|
||||
{
|
||||
p.close_path();
|
||||
self.figure = false;
|
||||
self.pos = self.figure_start;
|
||||
}
|
||||
}
|
||||
pub fn abort_path(&mut self) {
|
||||
self.path = None;
|
||||
}
|
||||
|
||||
/// FillPath / StrokePath / StrokeAndFillPath.
|
||||
pub fn paint_path(&mut self, fill: bool, stroke: bool) {
|
||||
if let Some(mut bp) = self.path.take() {
|
||||
// Filling closes the open figure.
|
||||
if fill && self.figure {
|
||||
bp.close_path();
|
||||
}
|
||||
self.draw(bp, fill, stroke);
|
||||
}
|
||||
}
|
||||
// ---------- clips ----------
|
||||
|
||||
fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) {
|
||||
if replace {
|
||||
@@ -699,10 +323,7 @@ impl Player {
|
||||
if !sane(path.bounding_box()) {
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
// A rectangle around the whole picture (what writers clip to first) clips nothing in it.
|
||||
let lines = path.elements().iter().all(|e| !matches!(e, PathEl::QuadTo(..) | PathEl::CurveTo(..)));
|
||||
let around = path.bounding_box().inflate(0.5, 0.5);
|
||||
if lines && path.elements().len() <= 6 && around.contains(self.frame.origin()) && around.contains(Point::new(self.frame.x1, self.frame.y1)) {
|
||||
if around(&path, self.frame) {
|
||||
return;
|
||||
}
|
||||
if self.dc.clips.len() >= MAX_NEST {
|
||||
@@ -712,69 +333,10 @@ impl Player {
|
||||
self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }));
|
||||
}
|
||||
|
||||
/// SelectClipPath (`mode`: 1 and, 5 copy; the others cut out, which isn't read).
|
||||
pub fn clip_path(&mut self, mode: u32) {
|
||||
let Some(bp) = self.path.take() else { return };
|
||||
match mode {
|
||||
1 => self.push_clip(bp, self.dc.fill_rule, false),
|
||||
5 => self.push_clip(bp, self.dc.fill_rule, true),
|
||||
_ => self.warn(EXCLUDED_CLIPS),
|
||||
}
|
||||
}
|
||||
|
||||
/// IntersectClipRect (logical units).
|
||||
pub fn clip_rect(&mut self, r: Rect) {
|
||||
let mut bp = shapes::rectangle(r.abs()).to_bezpath();
|
||||
bp.apply_affine(self.xf());
|
||||
self.push_clip(bp, FillRule::NonZero, false);
|
||||
}
|
||||
|
||||
/// A clip region of `rects` in device units (`mode` as [`Self::clip_path`]); none with mode
|
||||
/// copy removes the clip.
|
||||
pub fn clip_region(&mut self, rects: &[Rect], mode: u32) {
|
||||
if rects.is_empty() {
|
||||
if mode == 5 {
|
||||
self.dc.clips.clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
for r in rects {
|
||||
bp.extend(shapes::rectangle(r.abs()).to_bezpath());
|
||||
}
|
||||
bp.apply_affine(self.dev_to_doc);
|
||||
match mode {
|
||||
1 => self.push_clip(bp, FillRule::NonZero, false),
|
||||
5 => self.push_clip(bp, FillRule::NonZero, true),
|
||||
_ => self.warn(EXCLUDED_CLIPS),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exclude_clip(&mut self) {
|
||||
self.warn(EXCLUDED_CLIPS);
|
||||
}
|
||||
|
||||
// ---------- blits, images and text ----------
|
||||
|
||||
/// A raster operation without a source over `dest` (logical): the brush, white or black.
|
||||
pub fn pattern_blit(&mut self, dest: Rect, rop: u32) {
|
||||
let brush = match rop {
|
||||
PATCOPY => self.dc.brush.clone(),
|
||||
WHITENESS => BrushObj::Solid([255; 3]),
|
||||
BLACKNESS => BrushObj::Solid([0; 3]),
|
||||
_ => return self.skip(),
|
||||
};
|
||||
let pen = std::mem::replace(&mut self.dc.pen, PenObj::NULL);
|
||||
let outer = std::mem::replace(&mut self.dc.brush, brush);
|
||||
let mut bp = shapes::rectangle(dest.abs()).to_bezpath();
|
||||
bp.apply_affine(self.xf());
|
||||
self.draw(bp, true, false);
|
||||
self.dc.pen = pen;
|
||||
self.dc.brush = outer;
|
||||
}
|
||||
// ---------- images and text ----------
|
||||
|
||||
/// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest`
|
||||
/// (logical: origin and signed size) with raster operation `rop`, at `opacity`.
|
||||
/// (picture units: origin and signed size) with raster operation `rop`, at `opacity`.
|
||||
pub fn image(&mut self, img: Result<Rgba, String>, src: Rect, dest: Rect, rop: u32, opacity: f64) {
|
||||
if rop != SRCCOPY {
|
||||
self.warn(SKIPPED_ROPS);
|
||||
@@ -793,8 +355,8 @@ impl Player {
|
||||
self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity);
|
||||
}
|
||||
|
||||
/// An image placed by `xf` (its pixels, from the top-left, → logical), at `opacity`. An image
|
||||
/// that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
|
||||
/// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An
|
||||
/// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
|
||||
/// document's images.
|
||||
pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) {
|
||||
if img.width == 0 || img.height == 0 {
|
||||
@@ -814,14 +376,13 @@ impl Player {
|
||||
self.push(n);
|
||||
}
|
||||
|
||||
/// Text at `at` (logical; the current position with TA_UPDATECP) in the current font.
|
||||
/// Text at `at` (picture units) in the current font.
|
||||
pub fn text(&mut self, at: Point, s: &str) {
|
||||
let s: String = s.chars().filter(|c| *c != '\0').collect();
|
||||
if s.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let align = self.dc.text_align;
|
||||
let at = if align & 1 != 0 { self.pos } else { at };
|
||||
let f = self.dc.font.clone();
|
||||
let k = self.scale();
|
||||
// A negative height is the em; a positive one the cell (the em and the internal leading).
|
||||
@@ -863,18 +424,7 @@ impl Player {
|
||||
/// The document: what was drawn on one layer, clipped art in clipping groups.
|
||||
fn finish(mut self) -> Imported {
|
||||
self.flush();
|
||||
if self.skipped > 0 {
|
||||
let n = self.skipped;
|
||||
self.warnings.push(format!(
|
||||
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
|
||||
if n == 1 { "" } else { "s" },
|
||||
if n == 1 { "was" } else { "were" }
|
||||
));
|
||||
}
|
||||
let out = std::mem::take(&mut self.out);
|
||||
if out.is_empty() && self.emf_plus {
|
||||
self.warnings.push("the picture is drawn with EMF+ records, which aren't read yet: nothing was imported".into());
|
||||
}
|
||||
let children = nest(&mut self.doc, out);
|
||||
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(c) = layer.children_mut() {
|
||||
@@ -904,33 +454,7 @@ fn crop(img: Rgba, src: Rect) -> Rgba {
|
||||
Rgba { width: x1 - x0, height: y1 - y0, pixels }
|
||||
}
|
||||
|
||||
/// Read a metafile.
|
||||
/// Read an EMF or WMF file.
|
||||
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
match crate::sniff(bytes) {
|
||||
Some(Kind::Emf) => emf::play(bytes),
|
||||
Some(Kind::Wmf) => wmf::play(bytes),
|
||||
None => Err("not an EMF or WMF file".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod table_tests {
|
||||
use super::*;
|
||||
|
||||
/// Once the WMF table is full, a rejected creation leaves the hint at its end, so the next
|
||||
/// ones don't scan every slot again; a freed slot is still found.
|
||||
#[test]
|
||||
fn a_full_object_table_is_not_rescanned() {
|
||||
let mut p = Player::new(Kind::Wmf, Affine::IDENTITY, 1.0, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
for _ in 0..=u16::MAX as usize + 1 {
|
||||
p.create(Obj::Other);
|
||||
}
|
||||
p.delete(5);
|
||||
p.create(Obj::Other);
|
||||
p.create(Obj::Other);
|
||||
assert!(p.free_hint > u16::MAX as usize);
|
||||
p.delete(7);
|
||||
p.create(Obj::Other);
|
||||
assert!(p.objects[7].is_some());
|
||||
}
|
||||
picture::import(bytes)
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
//! EMF records (MS-EMF) played on a [`Player`]: the header gives the frame (the artboard) and the
|
||||
//! reference device (device pixels → millimetres), then every record in turn until EMR_EOF.
|
||||
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use super::{ArcKind, BrushObj, FontObj, Obj, PenObj, Player};
|
||||
use crate::bytes::{Reader, slice};
|
||||
use crate::dib::{self, Alpha};
|
||||
use crate::{Imported, Kind};
|
||||
|
||||
/// Points per millimetre.
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
/// Most points one record may give (a hostile count can't make a huge allocation).
|
||||
const MAX_POINTS: usize = 1 << 22;
|
||||
/// Records that change nothing VectorCraft keeps (background mode and colour, raster modes,
|
||||
/// palettes, colour management, comments…).
|
||||
const IGNORED: &[u32] =
|
||||
&[1, 13, 15, 16, 18, 20, 21, 23, 25, 28, 48, 50, 51, 52, 65, 66, 70, 98, 100, 101, 104, 110, 111, 112, 113, 115, 119, 120, 121];
|
||||
|
||||
fn rect(r: &mut Reader) -> Option<Rect> {
|
||||
Some(Rect::new(f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?), f64::from(r.i32()?)))
|
||||
}
|
||||
|
||||
fn point32(r: &mut Reader) -> Option<Point> {
|
||||
Some(Point::new(f64::from(r.i32()?), f64::from(r.i32()?)))
|
||||
}
|
||||
|
||||
fn point16(r: &mut Reader) -> Option<Point> {
|
||||
Some(Point::new(f64::from(r.i16()?), f64::from(r.i16()?)))
|
||||
}
|
||||
|
||||
fn color(r: &mut Reader) -> Option<[u8; 3]> {
|
||||
let [red, g, b, _] = r.u32()?.to_le_bytes();
|
||||
Some([red, g, b])
|
||||
}
|
||||
|
||||
fn xform(r: &mut Reader) -> Option<Affine> {
|
||||
let mut v = [0.0; 6];
|
||||
for x in &mut v {
|
||||
*x = f64::from(r.f32()?);
|
||||
}
|
||||
Some(Affine::new(v))
|
||||
}
|
||||
|
||||
/// `n` points (32-bit or 16-bit), `None` when the record is shorter.
|
||||
fn points(r: &mut Reader, n: u32, wide: bool) -> Option<Vec<Point>> {
|
||||
let n = n as usize;
|
||||
if n > MAX_POINTS || r.rest().len() < n * if wide { 8 } else { 4 } {
|
||||
return None;
|
||||
}
|
||||
(0..n).map(|_| if wide { point32(r) } else { point16(r) }).collect()
|
||||
}
|
||||
|
||||
/// The polygons of a PolyPolygon / PolyPolyline record.
|
||||
fn polys(r: &mut Reader, wide: bool) -> Option<Vec<Vec<Point>>> {
|
||||
r.skip(16)?;
|
||||
let n = r.u32()? as usize;
|
||||
let total = r.u32()?;
|
||||
if n > MAX_POINTS || r.rest().len() < n * 4 {
|
||||
return None;
|
||||
}
|
||||
let counts: Vec<u32> = (0..n).map(|_| r.u32()).collect::<Option<_>>()?;
|
||||
let mut all = points(r, total, wide)?.into_iter();
|
||||
Some(counts.iter().map(|c| all.by_ref().take(*c as usize).collect()).collect())
|
||||
}
|
||||
|
||||
/// A LOGFONTW → the font.
|
||||
fn font(r: &mut Reader) -> Option<FontObj> {
|
||||
let height = f64::from(r.i32()?);
|
||||
r.skip(4)?;
|
||||
let escapement = f64::from(r.i32()?);
|
||||
r.skip(4)?;
|
||||
let weight = r.i32()?;
|
||||
let italic = r.bytes(1)?.first().is_some_and(|b| *b != 0);
|
||||
r.skip(7)?;
|
||||
let units: Vec<u16> = (0..32).map_while(|_| r.u16()).take_while(|c| *c != 0).collect();
|
||||
Some(FontObj { height, escapement, weight, italic, face: String::from_utf16_lossy(&units) })
|
||||
}
|
||||
|
||||
/// The bitmap of an image record: its BITMAPINFO and bits at the offsets the record gives.
|
||||
fn bitmap(rec: &[u8], off_bmi: u32, cb_bmi: u32, off_bits: u32, cb_bits: u32, alpha: Alpha, left: &mut u64) -> Result<dib::Rgba, String> {
|
||||
let bmi = slice(rec, off_bmi, cb_bmi).ok_or("damaged")?;
|
||||
let bits = slice(rec, off_bits, cb_bits).ok_or("damaged")?;
|
||||
dib::decode(bmi, bits, alpha, left)
|
||||
}
|
||||
|
||||
/// The rows a DIB's source rectangle counts from the bottom in (StretchDIBits on a bottom-up DIB).
|
||||
fn bottom_up(rec: &[u8], off_bmi: u32) -> bool {
|
||||
let at = off_bmi as usize;
|
||||
let size = rec.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
|
||||
let height = rec.get(at + 8..at + 12).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes);
|
||||
size.is_some_and(|s| s >= 40) && height.is_some_and(|h| h > 0)
|
||||
}
|
||||
|
||||
/// The source rectangle `(x, y, w, h)` of an image of `img`'s height, counted from the top.
|
||||
fn source(x: i32, y: i32, w: i32, h: i32, img: &Result<dib::Rgba, String>, from_bottom: bool) -> Rect {
|
||||
let ih = img.as_ref().map_or(0.0, |i| f64::from(i.height));
|
||||
let (x, y, w, h) = (f64::from(x), f64::from(y), f64::from(w), f64::from(h));
|
||||
let top = if from_bottom { ih - y - h } else { y };
|
||||
Rect::new(x, top, x + w, top + h)
|
||||
}
|
||||
|
||||
/// The size and placement of the picture: (device → document, millimetres a pixel, the artboard).
|
||||
fn frame(bytes: &[u8]) -> Option<(Affine, f64, Rect)> {
|
||||
let mut r = Reader::new(bytes);
|
||||
r.skip(4)?;
|
||||
let header_size = r.u32()?;
|
||||
let bounds = rect(&mut r)?;
|
||||
let frame = rect(&mut r)?;
|
||||
// Signature, version, bytes, records, handles, description and palette size.
|
||||
r.skip(32)?;
|
||||
let device = (f64::from(r.i32()?), f64::from(r.i32()?));
|
||||
let mm = (f64::from(r.i32()?), f64::from(r.i32()?));
|
||||
// The device in micrometres (more precise), when the header has it.
|
||||
let micro = if header_size >= 108 {
|
||||
r.skip(12)?;
|
||||
Some((f64::from(r.u32()?), f64::from(r.u32()?)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ok = |v: f64| v.is_finite() && v > 0.0;
|
||||
let mm_per_px = match micro {
|
||||
Some((mx, _)) if ok(mx) && ok(device.0) => mx / 1000.0 / device.0,
|
||||
_ if ok(mm.0) && ok(device.0) => mm.0 / device.0,
|
||||
_ => 25.4 / 96.0,
|
||||
};
|
||||
let mm_per_px = if mm_per_px.is_finite() && mm_per_px > 1e-9 { mm_per_px } else { 25.4 / 96.0 };
|
||||
let k = mm_per_px * PT_PER_MM;
|
||||
// The frame (0.01 mm) in device pixels; an empty frame falls back to the bounds.
|
||||
let f = frame.abs();
|
||||
let (origin, size) = if f.width() > 0.0 && f.height() > 0.0 {
|
||||
(Point::new(f.x0 / 100.0 / mm_per_px, f.y0 / 100.0 / mm_per_px), (f.width() / 100.0 * PT_PER_MM, f.height() / 100.0 * PT_PER_MM))
|
||||
} else {
|
||||
let b = bounds.abs();
|
||||
(b.origin(), ((b.width() + 1.0) * k, (b.height() + 1.0) * k))
|
||||
};
|
||||
let dev_to_doc = Affine::scale(k) * Affine::translate(-origin.to_vec2());
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, 1e6) } else { 1.0 };
|
||||
Some((dev_to_doc, mm_per_px, Rect::new(0.0, 0.0, side(size.0), side(size.1))))
|
||||
}
|
||||
|
||||
pub(super) fn play(bytes: &[u8]) -> Result<Imported, String> {
|
||||
let (dev_to_doc, mm_per_px, artboard) = frame(bytes).ok_or("the EMF header is damaged")?;
|
||||
let mut p = Player::new(Kind::Emf, dev_to_doc, mm_per_px, artboard);
|
||||
let mut at = 0usize;
|
||||
let mut ended = false;
|
||||
while let Some(head) = bytes.get(at..at + 8) {
|
||||
let kind = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
|
||||
let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
|
||||
let Some(rec) = bytes.get(at..at.saturating_add(size)).filter(|_| size >= 8) else { break };
|
||||
if kind == 14 {
|
||||
ended = true;
|
||||
break;
|
||||
}
|
||||
if !matches!(kind, 27 | 54 | 5 | 6 | 88 | 89) {
|
||||
p.flush();
|
||||
}
|
||||
if record(&mut p, kind, rec).is_none() {
|
||||
p.skip();
|
||||
}
|
||||
at += size;
|
||||
}
|
||||
if !ended {
|
||||
p.warn("the file ends early: what it held was imported");
|
||||
}
|
||||
Ok(p.finish())
|
||||
}
|
||||
|
||||
/// PolyBezier, Polygon, Polyline, PolyBezierTo, PolylineTo and their 16-bit forms.
|
||||
fn rec_poly(p: &mut Player, kind: u32, r: &mut Reader) -> Option<()> {
|
||||
let wide = kind < 85;
|
||||
r.skip(16)?;
|
||||
let n = r.u32()?;
|
||||
let pts = points(r, n, wide)?;
|
||||
match if wide { kind } else { kind - 83 } {
|
||||
2 => p.poly(&pts, false, true),
|
||||
3 => p.poly(&pts, true, false),
|
||||
4 => p.poly(&pts, false, false),
|
||||
5 => p.poly_to(&pts, true),
|
||||
_ => p.poly_to(&pts, false),
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// CreatePen (38).
|
||||
fn rec_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> {
|
||||
let ih = r.u32()?;
|
||||
let style = r.u32()?;
|
||||
let width = f64::from(r.i32()?);
|
||||
r.skip(4)?;
|
||||
p.create_at(ih, Obj::Pen(PenObj { style, width, color: color(r)?, entries: vec![] }));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// ExtCreatePen (95).
|
||||
fn rec_ext_create_pen(p: &mut Player, r: &mut Reader) -> Option<()> {
|
||||
let ih = r.u32()?;
|
||||
r.skip(16)?;
|
||||
let style = r.u32()?;
|
||||
let width = f64::from(r.u32()?);
|
||||
let brush = r.u32()?;
|
||||
let c = color(r)?;
|
||||
r.skip(4)?;
|
||||
let n = (r.u32()? as usize).min(64);
|
||||
let entries: Vec<f64> = (0..n).map_while(|_| r.u32()).map(f64::from).collect();
|
||||
// A pen painted with the null brush draws nothing.
|
||||
let style = if brush == 1 { super::PS_NULL } else { style };
|
||||
p.create_at(ih, Obj::Pen(PenObj { style, width, color: c, entries }));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// GdiComment (70): EMF+ records ride in comments starting "EMF+".
|
||||
fn rec_comment(p: &mut Player, r: &mut Reader) -> Option<()> {
|
||||
r.skip(4)?;
|
||||
p.emf_plus |= r.u32()? == 0x2B46_4D45;
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// ExtSelectClipRgn (75).
|
||||
fn rec_clip_region(p: &mut Player, r: &mut Reader) -> Option<()> {
|
||||
let cb = r.u32()?;
|
||||
let mode = r.u32()?;
|
||||
let data = r.bytes(cb as usize)?;
|
||||
let mut d = Reader::new(data);
|
||||
let rects = if cb >= 32 {
|
||||
d.skip(8)?;
|
||||
let n = d.u32()? as usize;
|
||||
d.skip(20)?;
|
||||
if n > MAX_POINTS || d.rest().len() < n * 16 {
|
||||
return None;
|
||||
}
|
||||
(0..n).map(|_| rect(&mut d)).collect::<Option<Vec<_>>>()?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
p.clip_region(&rects, mode);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The rectangle at `(x, y)` of size `(w, h)`.
|
||||
fn at_size(x: i32, y: i32, w: i32, h: i32) -> Rect {
|
||||
Rect::new(f64::from(x), f64::from(y), f64::from(x) + f64::from(w), f64::from(y) + f64::from(h))
|
||||
}
|
||||
|
||||
/// BitBlt (76) and StretchBlt (77).
|
||||
fn rec_blt(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> {
|
||||
r.skip(16)?;
|
||||
let dest = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
|
||||
let rop = r.u32()?;
|
||||
let (xs, ys) = (r.i32()?, r.i32()?);
|
||||
r.skip(24 + 4 + 4)?;
|
||||
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
|
||||
let (ws, hs) = if kind == 77 { (r.i32()?, r.i32()?) } else { (dest.2, dest.3) };
|
||||
let d = at_size(dest.0, dest.1, dest.2, dest.3);
|
||||
if cb_bmi == 0 {
|
||||
p.pattern_blit(d, rop);
|
||||
} else {
|
||||
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left);
|
||||
let src = source(xs, ys, ws, hs, &img, false);
|
||||
p.image(img, src, d, rop, 1.0);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// StretchDIBits (81).
|
||||
fn rec_stretch_dibits(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> {
|
||||
r.skip(16)?;
|
||||
let (xd, yd, xs, ys, ws, hs) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?, r.i32()?);
|
||||
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
|
||||
r.skip(4)?;
|
||||
let rop = r.u32()?;
|
||||
let (wd, hd) = (r.i32()?, r.i32()?);
|
||||
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, Alpha::Ignore, &mut p.pixels_left);
|
||||
let src = source(xs, ys, ws, hs, &img, bottom_up(rec, off_bmi));
|
||||
p.image(img, src, at_size(xd, yd, wd, hd), rop, 1.0);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// AlphaBlend (114).
|
||||
fn rec_alpha_blend(p: &mut Player, rec: &[u8], r: &mut Reader) -> Option<()> {
|
||||
r.skip(16)?;
|
||||
let (xd, yd, wd, hd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
|
||||
let blend = r.bytes(4)?;
|
||||
let (constant, per_pixel) = (blend.get(2).copied().unwrap_or(255), blend.get(3).is_some_and(|f| *f & 1 != 0));
|
||||
let (xs, ys) = (r.i32()?, r.i32()?);
|
||||
r.skip(24 + 4 + 4)?;
|
||||
let (off_bmi, cb_bmi, off_bits, cb_bits) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?);
|
||||
let (ws, hs) = (r.i32()?, r.i32()?);
|
||||
let alpha = if per_pixel { Alpha::Premultiplied } else { Alpha::Ignore };
|
||||
let img = bitmap(rec, off_bmi, cb_bmi, off_bits, cb_bits, alpha, &mut p.pixels_left);
|
||||
let src = source(xs, ys, ws, hs, &img, false);
|
||||
p.image(img, src, at_size(xd, yd, wd, hd), crate::import::SRCCOPY, f64::from(constant) / 255.0);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// ExtTextOutA (83) and ExtTextOutW (84).
|
||||
fn rec_text(p: &mut Player, kind: u32, rec: &[u8], r: &mut Reader) -> Option<()> {
|
||||
r.skip(16 + 4 + 8)?;
|
||||
let at = point32(r)?;
|
||||
let n = r.u32()? as usize;
|
||||
let off = r.u32()?;
|
||||
let s = if kind == 84 {
|
||||
let raw = slice(rec, off, u32::try_from(n.checked_mul(2)?).ok()?)?;
|
||||
String::from_utf16_lossy(&raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::<Vec<_>>())
|
||||
} else {
|
||||
slice(rec, off, u32::try_from(n).ok()?)?.iter().map(|b| char::from(*b)).collect()
|
||||
};
|
||||
p.text(at, &s);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Play one record (`rec`: all of it, with its type and size). `None`: unknown or damaged.
|
||||
fn record(p: &mut Player, kind: u32, rec: &[u8]) -> Option<()> {
|
||||
let mut r = Reader::new(rec.get(8..)?);
|
||||
match kind {
|
||||
2..=6 | 85..=89 => rec_poly(p, kind, &mut r)?,
|
||||
7 | 90 => p.poly_poly(&polys(&mut r, kind == 7)?, false),
|
||||
8 | 91 => p.poly_poly(&polys(&mut r, kind == 8)?, true),
|
||||
9 => p.set_window_ext(f64::from(r.i32()?), f64::from(r.i32()?)),
|
||||
10 => p.set_window_org(f64::from(r.i32()?), f64::from(r.i32()?)),
|
||||
11 => p.set_viewport_ext(f64::from(r.i32()?), f64::from(r.i32()?)),
|
||||
12 => p.set_viewport_org(f64::from(r.i32()?), f64::from(r.i32()?)),
|
||||
17 => p.set_map_mode(r.u32()?),
|
||||
19 => p.set_fill_mode(r.u32()? == 1),
|
||||
22 => p.set_text_align(r.u32()?),
|
||||
24 => p.set_text_color(color(&mut r)?),
|
||||
27 => p.move_to(point32(&mut r)?),
|
||||
29 => p.exclude_clip(),
|
||||
30 => p.clip_rect(rect(&mut r)?),
|
||||
31 | 32 => {
|
||||
let (xn, xd, yn, yd) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
|
||||
p.scale_ext(kind == 32, (f64::from(xn), f64::from(xd)), (f64::from(yn), f64::from(yd)));
|
||||
}
|
||||
33 => p.save(),
|
||||
34 => p.restore(r.i32()?),
|
||||
35 => p.world(xform(&mut r)?, 4),
|
||||
36 => {
|
||||
let x = xform(&mut r)?;
|
||||
p.world(x, r.u32()?);
|
||||
}
|
||||
37 => p.select(r.u32()?),
|
||||
38 => rec_create_pen(p, &mut r)?,
|
||||
39 => {
|
||||
let ih = r.u32()?;
|
||||
let style = r.u32()?;
|
||||
p.create_at(ih, Obj::Brush(BrushObj::from_log(style, color(&mut r)?)));
|
||||
}
|
||||
40 => p.delete(r.u32()?),
|
||||
42 => p.figure(vectorcraft_geom::shapes::ellipse(rect(&mut r)?.abs()).to_bezpath(), true),
|
||||
43 => p.figure(vectorcraft_geom::shapes::rectangle(rect(&mut r)?.abs()).to_bezpath(), true),
|
||||
44 => {
|
||||
let b = rect(&mut r)?;
|
||||
let (cx, cy) = (f64::from(r.i32()?), f64::from(r.i32()?));
|
||||
p.figure(super::round_rect(b, cx, cy), true);
|
||||
}
|
||||
45..=47 => {
|
||||
let b = rect(&mut r)?;
|
||||
let (s, e) = (point32(&mut r)?, point32(&mut r)?);
|
||||
p.arc(b, s, e, [ArcKind::Open, ArcKind::Chord, ArcKind::Pie][(kind - 45) as usize]);
|
||||
}
|
||||
49 | 99 | 122 => p.create_at(r.u32()?, Obj::Other),
|
||||
54 => {
|
||||
let pt = point32(&mut r)?;
|
||||
p.poly_to(&[pt], false);
|
||||
}
|
||||
57 => p.set_arc_ccw(r.u32()? != 2),
|
||||
58 => p.set_miter(f64::from(r.u32()?)),
|
||||
59 => p.begin_path(),
|
||||
60 => p.end_path(),
|
||||
61 => p.close_figure(),
|
||||
62 => p.paint_path(true, false),
|
||||
63 => p.paint_path(true, true),
|
||||
64 => p.paint_path(false, true),
|
||||
67 => p.clip_path(r.u32()?),
|
||||
68 => p.abort_path(),
|
||||
70 => rec_comment(p, &mut r)?,
|
||||
75 => rec_clip_region(p, &mut r)?,
|
||||
76 | 77 => rec_blt(p, kind, rec, &mut r)?,
|
||||
81 => rec_stretch_dibits(p, rec, &mut r)?,
|
||||
82 => {
|
||||
let ih = r.u32()?;
|
||||
p.create_at(ih, Obj::Font(font(&mut r)?));
|
||||
}
|
||||
83 | 84 => rec_text(p, kind, rec, &mut r)?,
|
||||
93 | 94 => p.create_at(r.u32()?, Obj::Brush(BrushObj::Pattern)),
|
||||
95 => rec_ext_create_pen(p, &mut r)?,
|
||||
114 => rec_alpha_blend(p, rec, &mut r)?,
|
||||
k if IGNORED.contains(&k) => {}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -24,7 +24,7 @@ use std::io::Cursor;
|
||||
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect, Shape, Vec2, shapes};
|
||||
|
||||
use super::{BAD_IMAGE, BrushObj, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect};
|
||||
use super::{BAD_IMAGE, FontObj, PS_GEOMETRIC, PenObj, Player, SRCCOPY, TOO_MANY_PIXELS, crop, round_rect};
|
||||
use crate::dib::{self, Rgba};
|
||||
use crate::{Imported, Kind};
|
||||
|
||||
@@ -600,7 +600,7 @@ impl Pict {
|
||||
let base = Affine::translate(-frame.origin().to_vec2());
|
||||
let artboard = Rect::new(0.0, 0.0, frame.width(), frame.height());
|
||||
// A picture's coordinates map straight onto the document, as a WMF's do.
|
||||
let p = Player::new(Kind::Wmf, base, 25.4 / 72.0, artboard);
|
||||
let p = Player::new(Kind::Wmf, base, artboard);
|
||||
Self {
|
||||
p,
|
||||
frame,
|
||||
@@ -783,7 +783,7 @@ impl Pict {
|
||||
/// Fill `bp` (picture space) with `color`.
|
||||
fn fill(&mut self, mut bp: BezPath, color: [u8; 3], rule: FillRule) {
|
||||
bp.apply_affine(self.p.xf());
|
||||
self.p.dc.brush = BrushObj::Solid(color);
|
||||
self.p.dc.brush = color;
|
||||
self.p.dc.fill_rule = rule;
|
||||
self.p.draw(bp, true, false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,658 @@
|
||||
//! EMF (with or without EMF+ records) and WMF files: `craft_metafile` plays the records into a
|
||||
//! picture, and the picture's items become document objects here.
|
||||
//!
|
||||
//! - A filled or stroked path becomes a path with a fill and a stroke (caps, joins, miter limit
|
||||
//! and dashes from the pen). Opaque solid strokes with round caps and round joins drawn one after
|
||||
//! another, each starting where the last one ended, with the same pen and clip, join into one
|
||||
//! path. Other strokes stay apart, each with its own caps and its own dashes.
|
||||
//! - A path filled with a pattern or hatched brush is filled with the average color of the
|
||||
//! brush's tile.
|
||||
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
|
||||
//! skewed with it.
|
||||
//! - Text becomes point type in the font the file names, underlined or struck through as the font
|
||||
//! is, and clipped to its rectangle when the file clips it.
|
||||
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
|
||||
//! the whole picture clips nothing and is left out.
|
||||
//!
|
||||
//! A WMF without a placeable header is read at 1440 units an inch, and one whose placeable box is
|
||||
//! empty or inverted at the units an inch the header gives. Either one that draws in a metric map
|
||||
//! mode (MM_LOMETRIC to MM_TWIPS) is read at 96 pixels an inch, as `craft_metafile` plays those
|
||||
//! modes. An EMF without a usable frame is read at its device's pixels a millimetre (96
|
||||
//! pixels an inch when the header doesn't say).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use craft_metafile::{Cap, ClipPath, HAlign, Item, Join, LineStyle, Seg, VAlign};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId,
|
||||
NodeKind, StrokeLayer, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
|
||||
|
||||
use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane};
|
||||
use crate::dib::Rgba;
|
||||
use crate::wmf::PLACEABLE_KEY;
|
||||
use crate::{Imported, Kind};
|
||||
|
||||
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
|
||||
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
|
||||
const TOO_MANY: &str = "objects past the most one file may hold were left out";
|
||||
const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read";
|
||||
|
||||
/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the
|
||||
/// limit and does not say whether more items followed, so a picture holding this many may have
|
||||
/// been cut short.
|
||||
const READER_ITEMS: usize = 200_000;
|
||||
|
||||
/// Points a unit of a WMF without a placeable header (1440 units an inch).
|
||||
const WMF_UNIT: f64 = 72.0 / 1440.0;
|
||||
/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them.
|
||||
const SAVED_LEVELS: usize = 1024;
|
||||
/// Points a pixel at 96 pixels an inch.
|
||||
const PT_PER_PX: f64 = 72.0 / 96.0;
|
||||
/// Points a millimetre.
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
|
||||
/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode
|
||||
/// lets them draw.
|
||||
const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830];
|
||||
/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode.
|
||||
const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43];
|
||||
/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN
|
||||
/// and R2_NOP.
|
||||
const WMF_MIX_SKIPS: [u16; 2] = [7, 11];
|
||||
/// The mix mode a WMF starts in (R2_COPYPEN).
|
||||
const WMF_MIX_START: u16 = 13;
|
||||
/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode
|
||||
/// allows), BLACKNESS and WHITENESS.
|
||||
const PATCOPY: u32 = 0x00F0_0021;
|
||||
const BLACKNESS: u32 = 0x0000_0042;
|
||||
const WHITENESS: u32 = 0x00FF_0062;
|
||||
|
||||
/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those
|
||||
/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in
|
||||
/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or
|
||||
/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode.
|
||||
/// `start` is where the standard header begins.
|
||||
fn wmf_metric(bytes: &[u8], start: usize) -> bool {
|
||||
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
|
||||
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let Some(words) = start.checked_add(2).and_then(u16_at) else { return false };
|
||||
let mut at = start.saturating_add(usize::from(words) * 2);
|
||||
let mut mode = 1;
|
||||
let mut mix = WMF_MIX_START;
|
||||
let metric = |mode: u16| (2..=6).contains(&mode);
|
||||
// Drawing records played in a metric mode, and in any other.
|
||||
let (mut in_metric, mut in_other) = (0usize, 0usize);
|
||||
// The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does.
|
||||
let mut saved: Vec<(u16, u16)> = Vec::new();
|
||||
// The records as the reader walks them: it stops at the end record, a record shorter than its
|
||||
// header, one that runs past the file and a SAVEDC past its 1,024 levels.
|
||||
while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) {
|
||||
let size = (words as usize).saturating_mul(2);
|
||||
let Some(next) = at.checked_add(size) else { break };
|
||||
if function == 0 || size < 6 || next > bytes.len() {
|
||||
break;
|
||||
}
|
||||
match function {
|
||||
// SETMAPMODE, when the record holds its mode.
|
||||
0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode),
|
||||
// SETROP2, when the record holds its mix mode.
|
||||
0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix),
|
||||
// SAVEDC.
|
||||
0x001E => {
|
||||
if saved.len() >= SAVED_LEVELS {
|
||||
break;
|
||||
}
|
||||
saved.push((mode, mix));
|
||||
}
|
||||
// RESTOREDC: a negative count pops that many levels, a positive one goes back to that
|
||||
// level. One that names no saved level changes nothing.
|
||||
0x0127 if size >= 8 => {
|
||||
let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes())));
|
||||
let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) };
|
||||
if let Some(level) = level
|
||||
&& let Some((m, x)) = saved.get(level).copied()
|
||||
{
|
||||
mode = m;
|
||||
mix = x;
|
||||
saved.truncate(level);
|
||||
}
|
||||
}
|
||||
f => {
|
||||
let draws = match f {
|
||||
_ if WMF_DRAWS.contains(&f) => true,
|
||||
_ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix),
|
||||
// PATBLT: its raster operation, when the record holds one.
|
||||
0x061D => match u32_at(at + 6).filter(|_| size >= 10) {
|
||||
Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix),
|
||||
Some(rop) => rop == BLACKNESS || rop == WHITENESS,
|
||||
None => false,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
if draws && metric(mode) {
|
||||
in_metric += 1;
|
||||
} else if draws {
|
||||
in_other += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
at = next;
|
||||
}
|
||||
if in_metric == in_other { metric(mode) } else { in_metric > in_other }
|
||||
}
|
||||
|
||||
/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an
|
||||
/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map
|
||||
/// mode) or device units (EMF).
|
||||
fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) {
|
||||
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
|
||||
let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]]));
|
||||
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let positive = |v: Option<i32>| v.filter(|v| *v > 0).map(f64::from);
|
||||
match kind {
|
||||
Kind::Wmf => {
|
||||
let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]);
|
||||
if placeable
|
||||
&& let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12))
|
||||
&& r > l
|
||||
&& b > t
|
||||
{
|
||||
return (1.0, 1.0);
|
||||
}
|
||||
if wmf_metric(bytes, if placeable { 22 } else { 0 }) {
|
||||
return (PT_PER_PX, PT_PER_PX);
|
||||
}
|
||||
if !placeable {
|
||||
return (WMF_UNIT, WMF_UNIT);
|
||||
}
|
||||
let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from);
|
||||
(k, k)
|
||||
}
|
||||
Kind::Emf => {
|
||||
// Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header
|
||||
// has them, else over szlMillimeters (both sizes must be positive).
|
||||
let device = positive(i32_at(72)).zip(positive(i32_at(76)));
|
||||
let micro = (u32_at(4).is_some_and(|s| s >= 108))
|
||||
.then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0)))
|
||||
.flatten();
|
||||
let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84))));
|
||||
let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh));
|
||||
let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t);
|
||||
let ok = |v: f64| v.is_finite() && v > 0.0;
|
||||
match px_mm {
|
||||
Some(_) if frame => (1.0, 1.0),
|
||||
Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y),
|
||||
_ => (PT_PER_PX, PT_PER_PX),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a stroke is drawn with, to tell whether two strokes join into one path.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Pen {
|
||||
color: [u8; 4],
|
||||
width: f32,
|
||||
line: LineStyle,
|
||||
even_odd: bool,
|
||||
chain: Vec<u32>,
|
||||
}
|
||||
|
||||
/// Strokes drawn one after another, not added yet: their pen, clips and path (document space).
|
||||
struct Pending {
|
||||
pen: Pen,
|
||||
clips: Vec<Arc<Clip>>,
|
||||
path: BezPath,
|
||||
}
|
||||
|
||||
/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for
|
||||
/// one that clips nothing in the picture.
|
||||
type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>;
|
||||
/// The last clip region and the clip made for it.
|
||||
type MadeRegion = (Vec<[f32; 4]>, Option<Arc<Clip>>);
|
||||
/// Brush tiles already averaged, by address: items filled with the same brush share its tile. The
|
||||
/// `Weak` keeps the address from being reused, and the tile's pixels are freed once the last item
|
||||
/// that uses it has been read.
|
||||
type Averaged = HashMap<*const craft_metafile::Tile, (Weak<craft_metafile::Tile>, Option<[u8; 4]>)>;
|
||||
|
||||
struct Mapper {
|
||||
/// Picture units → points.
|
||||
xf: Affine,
|
||||
/// How much lengths (stroke widths, dashes) grow from the picture to points.
|
||||
k: f64,
|
||||
frame: Rect,
|
||||
doc: Document,
|
||||
out: Drawn,
|
||||
warnings: Vec<String>,
|
||||
next_clip: u32,
|
||||
paths: MadeClips,
|
||||
region: Option<MadeRegion>,
|
||||
pending: Option<Pending>,
|
||||
averaged: Averaged,
|
||||
}
|
||||
|
||||
fn color(c: [u8; 4]) -> Paint {
|
||||
rgb([c[0], c[1], c[2]])
|
||||
}
|
||||
|
||||
/// The average color of a tile's pixels, weighted by their alpha, and their average alpha; None
|
||||
/// for a clear tile.
|
||||
fn average(rgba: &[u8]) -> Option<[u8; 4]> {
|
||||
let pixels = rgba.as_chunks::<4>().0;
|
||||
let mut sum = [0u64; 4];
|
||||
for p in pixels {
|
||||
let a = u64::from(p[3]);
|
||||
sum[0] += u64::from(p[0]) * a;
|
||||
sum[1] += u64::from(p[1]) * a;
|
||||
sum[2] += u64::from(p[2]) * a;
|
||||
sum[3] += a;
|
||||
}
|
||||
let a = sum[3];
|
||||
let alpha = (a / pixels.len().max(1) as u64) as u8;
|
||||
(a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)])
|
||||
}
|
||||
|
||||
impl Mapper {
|
||||
fn new(width: f64, height: f64, (kx, ky): (f64, f64)) -> Self {
|
||||
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
|
||||
let (w, h) = (side(width * kx), side(height * ky));
|
||||
let mut doc = Document::new(w, h);
|
||||
doc.layers.clear();
|
||||
Self {
|
||||
xf: Affine::scale_non_uniform(kx, ky),
|
||||
// The mean of the two, as the reader scales stroke lengths.
|
||||
k: (kx + ky) / 2.0,
|
||||
frame: Rect::new(0.0, 0.0, w, h),
|
||||
doc,
|
||||
out: vec![],
|
||||
warnings: vec![],
|
||||
next_clip: 0,
|
||||
paths: HashMap::new(),
|
||||
region: None,
|
||||
pending: None,
|
||||
averaged: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self, segs: &[Seg]) -> BezPath {
|
||||
let mut bp = craft_metafile::bez_path(segs);
|
||||
bp.apply_affine(self.xf);
|
||||
bp
|
||||
}
|
||||
|
||||
/// A clip of `path` (document space), or None when it clips nothing in the picture.
|
||||
fn clip(&mut self, path: BezPath, rule: FillRule) -> Option<Arc<Clip>> {
|
||||
if around(&path, self.frame) {
|
||||
return None;
|
||||
}
|
||||
self.next_clip += 1;
|
||||
Some(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }))
|
||||
}
|
||||
|
||||
/// The clips an item is drawn under, outermost first; None when it shows nowhere.
|
||||
fn chain(&mut self, region: Option<Vec<[f32; 4]>>, clips: &[Arc<ClipPath>]) -> Option<Vec<Arc<Clip>>> {
|
||||
let mut chain = vec![];
|
||||
if let Some(rects) = region {
|
||||
if rects.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let made = match &self.region {
|
||||
Some((last, made)) if *last == rects => made.clone(),
|
||||
_ => {
|
||||
let mut bp = BezPath::new();
|
||||
for [x0, y0, x1, y1] in &rects {
|
||||
bp.extend(shapes::rectangle(Rect::new(f64::from(*x0), f64::from(*y0), f64::from(*x1), f64::from(*y1))).to_bezpath());
|
||||
}
|
||||
bp.apply_affine(self.xf);
|
||||
if !sane(bp.bounding_box()) {
|
||||
self.warn(FAR_AWAY);
|
||||
return None;
|
||||
}
|
||||
let made = self.clip(bp, FillRule::NonZero);
|
||||
self.region = Some((rects, made.clone()));
|
||||
made
|
||||
}
|
||||
};
|
||||
chain.extend(made);
|
||||
}
|
||||
for c in clips {
|
||||
let key = Arc::as_ptr(c);
|
||||
let made = match self.paths.get(&key) {
|
||||
Some((_, made)) => made.clone(),
|
||||
None => {
|
||||
let bp = self.path(&c.segs);
|
||||
if !sane(bp.bounding_box()) {
|
||||
self.warn(FAR_AWAY);
|
||||
return None;
|
||||
}
|
||||
let made = self.clip(bp, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero });
|
||||
self.paths.insert(key, (c.clone(), made.clone()));
|
||||
made
|
||||
}
|
||||
};
|
||||
chain.extend(made);
|
||||
}
|
||||
if chain.len() > MAX_NEST {
|
||||
chain.truncate(MAX_NEST);
|
||||
self.warn(&deep_clips());
|
||||
}
|
||||
Some(chain)
|
||||
}
|
||||
|
||||
fn push(&mut self, clips: Vec<Arc<Clip>>, mut node: Node) {
|
||||
if self.out.len() >= MAX_NODES {
|
||||
return self.warn(TOO_MANY);
|
||||
}
|
||||
if !node.visual_bounds().is_none_or(sane) {
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
node.id = self.doc.alloc_id();
|
||||
self.out.push((clips, node));
|
||||
}
|
||||
|
||||
/// Add the strokes waiting to be joined.
|
||||
fn flush(&mut self) {
|
||||
if let Some(p) = self.pending.take() {
|
||||
let node = self.path_node(p.path, None, Some((p.pen.color, p.pen.width, &p.pen.line)), p.pen.even_odd);
|
||||
if let Some(n) = node {
|
||||
self.push(p.clips, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke_layer(&self, c: [u8; 4], width: f32, line: &LineStyle) -> StrokeLayer {
|
||||
let w = f64::from(width) * self.k;
|
||||
let mut st = StrokeLayer::new(color(c), if w > 0.0 && w.is_finite() { w } else { HAIRLINE });
|
||||
st.opacity = f32::from(c[3]) / 255.0;
|
||||
st.cap = match line.cap {
|
||||
Cap::Round => LineCap::Round,
|
||||
Cap::Square => LineCap::Square,
|
||||
Cap::Flat => LineCap::Butt,
|
||||
};
|
||||
st.join = match line.join {
|
||||
Join::Round => LineJoin::Round,
|
||||
Join::Bevel => LineJoin::Bevel,
|
||||
Join::Miter => LineJoin::Miter,
|
||||
};
|
||||
let miter = f64::from(line.miter_limit);
|
||||
if miter.is_finite() && miter >= 1.0 {
|
||||
st.miter_limit = miter;
|
||||
}
|
||||
let dash = Dash { pattern: line.dash.iter().map(|d| f64::from(*d) * self.k).collect(), offset: 0.0, align_corners: false };
|
||||
st.dash = dash.is_dashed().then_some(dash);
|
||||
st
|
||||
}
|
||||
|
||||
/// A path node painted with `fill` and `stroke`; None when neither shows.
|
||||
fn path_node(&self, bp: BezPath, fill: Option<[u8; 4]>, stroke: Option<([u8; 4], f32, &LineStyle)>, even_odd: bool) -> Option<Node> {
|
||||
if bp.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut items = vec![];
|
||||
if let Some(c) = fill.filter(|c| c[3] > 0) {
|
||||
let mut f = FillLayer::new(color(c));
|
||||
f.opacity = f32::from(c[3]) / 255.0;
|
||||
items.push(AppearanceItem::Fill(f));
|
||||
}
|
||||
if let Some((c, w, line)) = stroke.filter(|s| s.0[3] > 0) {
|
||||
items.push(AppearanceItem::Stroke(self.stroke_layer(c, w, line)));
|
||||
}
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut n = Node::path(NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() });
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
fn item(&mut self, item: Item) {
|
||||
match item {
|
||||
Item::Path { segs, fill, stroke, line, even_odd, region, clips } => {
|
||||
let Some(chain) = self.chain(region, &clips) else { return self.flush() };
|
||||
let bp = self.path(&segs);
|
||||
// An open stroke with nothing filled waits, to join the next one.
|
||||
if let (None, Some((c, w))) = (fill, stroke)
|
||||
&& !segs.iter().any(|s| matches!(s, Seg::Close))
|
||||
{
|
||||
// A stroke that reaches too far is left out here, before it joins the strokes
|
||||
// waiting, so they are still added.
|
||||
let half = f64::from(w) * self.k;
|
||||
let half = if half > 0.0 && half.is_finite() { half / 2.0 } else { HAIRLINE / 2.0 };
|
||||
if !sane(bp.bounding_box().inflate(half, half)) {
|
||||
self.flush();
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
let pen = Pen { color: c, width: w, line, even_odd, chain: chain.iter().map(|c| c.id).collect() };
|
||||
let start = bp.elements().first().and_then(|e| match e {
|
||||
PathEl::MoveTo(p) => Some(*p),
|
||||
_ => None,
|
||||
});
|
||||
// A translucent stroke stays apart, so where strokes overlap each one shows. So
|
||||
// does a dashed one, whose dashes start at its own start, and one whose caps
|
||||
// or joins aren't round: a join where two strokes meet is not their two caps.
|
||||
if let Some(p) = &mut self.pending
|
||||
&& p.pen == pen
|
||||
&& pen.color[3] == u8::MAX
|
||||
&& pen.line.dash.is_empty()
|
||||
&& matches!((&pen.line.cap, &pen.line.join), (Cap::Round, Join::Round))
|
||||
&& start.is_some()
|
||||
&& p.path.elements().last().and_then(|e| e.end_point()) == start
|
||||
{
|
||||
p.path.extend(bp.elements().iter().skip(1).copied());
|
||||
return;
|
||||
}
|
||||
self.flush();
|
||||
self.pending = Some(Pending { pen, clips: chain, path: bp });
|
||||
return;
|
||||
}
|
||||
self.flush();
|
||||
let stroke = stroke.map(|(c, w)| (c, w, &line));
|
||||
if let Some(n) = self.path_node(bp, fill, stroke, even_odd) {
|
||||
self.push(chain, n);
|
||||
}
|
||||
}
|
||||
Item::Pattern { segs, even_odd, tile, region, clips } => {
|
||||
self.flush();
|
||||
let Some(chain) = self.chain(region, &clips) else { return };
|
||||
let Some(c) = self.averaged.entry(Arc::as_ptr(&tile)).or_insert_with(|| (Arc::downgrade(&tile), average(&tile.rgba))).1 else {
|
||||
return;
|
||||
};
|
||||
self.warn(PATTERNS);
|
||||
let bp = self.path(&segs);
|
||||
if let Some(n) = self.path_node(bp, Some(c), None, even_odd) {
|
||||
self.push(chain, n);
|
||||
}
|
||||
}
|
||||
Item::Bitmap { transform, width, height, rgba, region, clips, .. } => {
|
||||
self.flush();
|
||||
let Some(chain) = self.chain(region, &clips) else { return };
|
||||
self.image(Rgba { width, height, pixels: rgba }, Affine::new(transform), chain);
|
||||
}
|
||||
Item::Text(t) => {
|
||||
self.flush();
|
||||
let Some(mut chain) = self.chain(t.region.clone(), &t.clips) else { return };
|
||||
// The text's own clip rectangle, inside the others.
|
||||
if let Some([x0, y0, x1, y1]) = t.clip {
|
||||
let mut bp = shapes::rectangle(Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)).abs()).to_bezpath();
|
||||
bp.apply_affine(self.xf);
|
||||
if !sane(bp.bounding_box()) {
|
||||
return self.warn(FAR_AWAY);
|
||||
}
|
||||
if let Some(own) = self.clip(bp, FillRule::NonZero) {
|
||||
// Past the stack, the text's own clip takes the innermost place kept.
|
||||
if chain.len() >= MAX_NEST {
|
||||
chain.truncate(MAX_NEST.saturating_sub(1));
|
||||
self.warn(&deep_clips());
|
||||
}
|
||||
chain.push(own);
|
||||
}
|
||||
}
|
||||
self.text(&t, chain);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An image whose unit square `unit` places in the picture.
|
||||
fn image(&mut self, img: Rgba, unit: Affine, chain: Vec<Arc<Clip>>) {
|
||||
if img.width == 0 || img.height == 0 {
|
||||
return;
|
||||
}
|
||||
let xf = self.xf * unit * Affine::scale_non_uniform(1.0 / f64::from(img.width), 1.0 / f64::from(img.height));
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
return;
|
||||
}
|
||||
let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) };
|
||||
let blob = ImageBlob::new("image/png", png);
|
||||
let key = blob.content_key();
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
|
||||
self.push(chain, Node::new(NodeId(0), NodeKind::Image(Box::new(im))));
|
||||
}
|
||||
|
||||
fn text(&mut self, t: &craft_metafile::Text, chain: Vec<Arc<Clip>>) {
|
||||
let s: String = t.text.chars().filter(|c| *c != '\0').collect();
|
||||
if s.trim().is_empty() || t.color[3] == 0 {
|
||||
return;
|
||||
}
|
||||
// Text space → document without the move: its vertical scale gives the type size, and what
|
||||
// is left of it (a turn, a stretch across) goes on the text object.
|
||||
let [a, b, c, d, ..] = t.transform;
|
||||
let linear = self.xf * Affine::new([a, b, c, d, 0.0, 0.0]);
|
||||
let [_, _, c, d, ..] = linear.as_coeffs();
|
||||
let k = c.hypot(d);
|
||||
let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY };
|
||||
let f = &t.font;
|
||||
let h = f64::from(f.height);
|
||||
// A negative height is the em; a positive one the cell (the em and the internal leading).
|
||||
let em = if h < 0.0 { -h } else { h * 0.85 };
|
||||
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
|
||||
let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
|
||||
if !f.family.trim().is_empty() {
|
||||
style.font_family = f.family.trim().to_string();
|
||||
}
|
||||
style.font_style = match (f.weight >= 600, f.italic) {
|
||||
(true, true) => "Bold Italic",
|
||||
(true, false) => "Bold",
|
||||
(false, true) => "Italic",
|
||||
(false, false) => "Regular",
|
||||
}
|
||||
.into();
|
||||
style.underline = f.underline;
|
||||
style.strikethrough = f.strike;
|
||||
// Where the baseline is below the reference point.
|
||||
let drop = match t.v_align {
|
||||
VAlign::Baseline => 0.0,
|
||||
VAlign::Bottom => -0.2 * size,
|
||||
VAlign::Top => 0.8 * size,
|
||||
};
|
||||
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
|
||||
let mut text = TextObject::point(Point::ZERO, &s, style);
|
||||
text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop));
|
||||
text.para.justify = match t.h_align {
|
||||
HAlign::Center => Justify::Center,
|
||||
HAlign::Right => Justify::Right,
|
||||
HAlign::Left => Justify::Left,
|
||||
};
|
||||
text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds);
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
|
||||
n.opacity = f32::from(t.color[3]) / 255.0;
|
||||
self.push(chain, n);
|
||||
}
|
||||
|
||||
/// The document: what was drawn on one layer, clipped art in clipping groups.
|
||||
fn finish(mut self, kind: Kind, skipped: u32) -> Imported {
|
||||
self.flush();
|
||||
if skipped > 0 {
|
||||
let n = skipped;
|
||||
self.warnings.push(format!(
|
||||
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
|
||||
if n == 1 { "" } else { "s" },
|
||||
if n == 1 { "was" } else { "were" }
|
||||
));
|
||||
}
|
||||
let out = std::mem::take(&mut self.out);
|
||||
let children = nest(&mut self.doc, out);
|
||||
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(c) = layer.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
self.doc.layers = vec![Arc::new(layer)];
|
||||
Imported { document: self.doc, kind, warnings: self.warnings }
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the file stop before its end-of-file record?
|
||||
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
|
||||
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
|
||||
let mut at = match kind {
|
||||
Kind::Emf => 0,
|
||||
Kind::Wmf => {
|
||||
let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 };
|
||||
let Some(words) = u16_at(start + 2) else { return true };
|
||||
start + usize::from(words) * 2
|
||||
}
|
||||
};
|
||||
loop {
|
||||
let size = match kind {
|
||||
Kind::Emf => {
|
||||
let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true };
|
||||
if kind == 14 {
|
||||
return false;
|
||||
}
|
||||
// Records are a multiple of 4 bytes long; reading stops at one that isn't.
|
||||
if !size.is_multiple_of(4) {
|
||||
return true;
|
||||
}
|
||||
size as usize
|
||||
}
|
||||
Kind::Wmf => {
|
||||
let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true };
|
||||
if function == 0 {
|
||||
return false;
|
||||
}
|
||||
(words as usize).saturating_mul(2)
|
||||
}
|
||||
};
|
||||
if size < 6 {
|
||||
return true;
|
||||
}
|
||||
at = at.saturating_add(size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an EMF or WMF file.
|
||||
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
|
||||
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
|
||||
craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(),
|
||||
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
|
||||
craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()),
|
||||
})?;
|
||||
let k = unit(bytes, kind);
|
||||
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
|
||||
if ends_early(bytes, kind) {
|
||||
m.warn(ENDS_EARLY);
|
||||
}
|
||||
if pic.items.len() >= READER_ITEMS {
|
||||
m.warn(AT_LIMIT);
|
||||
}
|
||||
for item in pic.items {
|
||||
m.item(item);
|
||||
}
|
||||
Ok(m.finish(kind, pic.skipped_records))
|
||||
}
|
||||
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user